feat(adb): complete ADB device support for Android reverse engineering (#1552)
* feat(adb): acquire installed APK sets from connected Android devices Add a read-only ADB device-acquisition family over the caller's adb binary: inspect_adb_client, list_adb_devices, inspect_adb_device, list_adb_packages, and pull_adb_package, exposed through the CLI and MCP with shared admission, Evidence provenance (binary, version, serial, transport), and fixed argv vectors that never reach a shell. pull_adb_package acquires the complete split set reported by pm path into a package-named directory that must not exist, digesting every file with SHA-256 and keeping per-file failure reasons and partial coverage. Device kind is reported as an inference with its basis; getprop whitelisting keeps build identity bounded. REA installs nothing and never manages devices or emulators; the first device query may start the caller's local adb server, recorded when observed. Verified against adb 34.0.5 on Linux with an Android 14 (API 34) x86_64 emulator: full 224-package inventory, a real two-APK split set pulled with byte-exact digests, and a 73.9 MB system-package pull. npm run verify:adb records the lane; parser goldens come from the same device. READMEs carry the new row in every supported language. * feat(adb): complete the adb surface with observation, transfer, and lifecycle tools Extend the ADB family from five to twenty-four operations, all through fixed adb argument vectors with no shell exposure: Observation: read_adb_logcat (bounded dump, count/buffer/pid), inspect_adb_package (dumpsys package projection), list_adb_processes (ps -A), list_adb_directory (ls -la with kinds and symlink targets), list_adb_features (hex GL versions), list_adb_services (AIDL slash-suffixed names), inspect_adb_display (wm size and density), inspect_adb_window (focus declarations), read_adb_setting (device-side nulls reported as such), capture_adb_screen (exec-out screencap with PNG dimensions), collect_adb_bugreport (digested device archive). Transfer and search: pull_adb_file and push_adb_file (device-side sha256sum verification, explicit overwrite authority), resolve_adb_packages (substring package search with exact-match flag — the find step of an easy get). Lifecycle for dynamic analysis, each declaring mutatesTarget: install_adb_package and uninstall_adb_package preserving the device's Success/Failure verdict, start_adb_app (resolve-activity then am start -W), start_adb_activity (typed extras as --es/--ez/--ei/--el/--ef), and stop_adb_app (am force-stop). Verified end-to-end against adb 34.0.5 on Linux with an Android 14 (API 34) x86_64 emulator: 287 services, 92 features, split-set pulls with byte-exact digests, verified push/pull roundtrip, sized screen capture, and the full install → resolve → start → observe-in-ps → force-stop → uninstall lifecycle. Fixed a v-mode regex incompatibility in the settings key pattern and added argument descriptions required by the CLI catalog audit. * fix(adb): quote remote shell operands and protect captured output * test(adb): cover bugreport destinations containing spaces --------- Co-authored-by: REA Contributor <contributor@rea.tools> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
co-authored by
REA Contributor
morluto
parent
efd81f9776
commit
fef6f73064
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ADB_BINARY_ENV,
|
||||
parseAdbVersionOutput,
|
||||
resolveAdbBinary,
|
||||
} from "./AdbConfiguration.js";
|
||||
|
||||
describe("resolveAdbBinary", () => {
|
||||
it("prefers an absolute REA_ADB_PATH", () => {
|
||||
expect(resolveAdbBinary({ [ADB_BINARY_ENV]: "/opt/tools/adb" })).toEqual({
|
||||
binary: "/opt/tools/adb",
|
||||
pathSource: "environment",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to PATH resolution without the environment key", () => {
|
||||
expect(resolveAdbBinary({})).toEqual({
|
||||
binary: "adb",
|
||||
pathSource: "path",
|
||||
});
|
||||
expect(resolveAdbBinary({ [ADB_BINARY_ENV]: " " })).toEqual({
|
||||
binary: "adb",
|
||||
pathSource: "path",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a relative environment path explicitly", () => {
|
||||
expect(() => resolveAdbBinary({ [ADB_BINARY_ENV]: "tools/adb" })).toThrow(
|
||||
/must be an absolute path/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAdbVersionOutput", () => {
|
||||
it("reads the build version and install path from real output", () => {
|
||||
expect(
|
||||
parseAdbVersionOutput(
|
||||
[
|
||||
"Android Debug Bridge version 1.0.41",
|
||||
"Version 34.0.5-debian",
|
||||
"Installed as /usr/lib/android-sdk/platform-tools/adb",
|
||||
"",
|
||||
].join("\n"),
|
||||
),
|
||||
).toEqual({
|
||||
version: "34.0.5-debian",
|
||||
installedPath: "/usr/lib/android-sdk/platform-tools/adb",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports null identity fields when the named lines are absent", () => {
|
||||
expect(parseAdbVersionOutput("unexpected output")).toEqual({
|
||||
version: null,
|
||||
installedPath: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import {
|
||||
execFileOutput,
|
||||
execFileOutputFailure,
|
||||
} from "../process/ExecFileOutput.js";
|
||||
import type { ProviderAvailability } from "../application/AnalysisProvider.js";
|
||||
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
/** Environment key selecting the caller's adb binary. */
|
||||
export const ADB_BINARY_ENV = "REA_ADB_PATH";
|
||||
|
||||
const VERSION_TIMEOUT_MS = 10_000;
|
||||
const VERSION_MAX_OUTPUT_BYTES = 64 * 1024;
|
||||
|
||||
/** How the adb binary was selected for this provider instance. */
|
||||
export interface AdbBinarySelection {
|
||||
readonly binary: string;
|
||||
readonly pathSource: "environment" | "path";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the caller-supplied adb binary. `REA_ADB_PATH` must be absolute so
|
||||
* the selection stays explicit; without it, adb is resolved from `PATH` by
|
||||
* the platform exec at run time, like any bring-your-own tool.
|
||||
*/
|
||||
export const resolveAdbBinary = (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
): AdbBinarySelection => {
|
||||
const configured = environment[ADB_BINARY_ENV];
|
||||
if (configured === undefined || configured.trim() === "")
|
||||
return { binary: "adb", pathSource: "path" };
|
||||
if (!isAbsolute(configured))
|
||||
throw new AdbConfigurationFailure(
|
||||
"not_absolute",
|
||||
`${ADB_BINARY_ENV} must be an absolute path to the adb binary`,
|
||||
{ configured_path: configured },
|
||||
);
|
||||
return { binary: configured, pathSource: "environment" };
|
||||
};
|
||||
|
||||
export type AdbConfigurationFailureCode =
|
||||
| "not_absolute"
|
||||
| "binary_missing"
|
||||
| "version_unresolved";
|
||||
|
||||
export class AdbConfigurationFailure extends Error {
|
||||
constructor(
|
||||
readonly code: AdbConfigurationFailureCode,
|
||||
message: string,
|
||||
readonly diagnostics: Readonly<Record<string, JsonValue>> = {},
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(message, options);
|
||||
}
|
||||
}
|
||||
|
||||
export interface AdbClientIdentity {
|
||||
readonly version: string | null;
|
||||
readonly installedPath: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `adb version` output. The first line carries the protocol version,
|
||||
* `Version ` the build version (no colon), and `Installed as` the binary path.
|
||||
*/
|
||||
export const parseAdbVersionOutput = (stdout: string): AdbClientIdentity => {
|
||||
const build = /^Version\s+(\S.*)$/mu.exec(stdout);
|
||||
const installed = /^Installed as\s+(.+)$/mu.exec(stdout);
|
||||
return {
|
||||
version: build === null ? null : build[1]!.trim(),
|
||||
installedPath: installed === null ? null : installed[1]!.trim(),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Probe the selected adb binary without contacting devices. `adb version`
|
||||
* never starts the adb server, so this stays a pure client check.
|
||||
*/
|
||||
export const inspectAdbClient = async (
|
||||
selection: AdbBinarySelection,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AdbClientIdentity> => {
|
||||
try {
|
||||
const { stdout } = await execFileOutput(selection.binary, ["version"], {
|
||||
timeout: VERSION_TIMEOUT_MS,
|
||||
stopSignal: "SIGTERM",
|
||||
maxBuffer: VERSION_MAX_OUTPUT_BYTES,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
return parseAdbVersionOutput(stdout);
|
||||
} catch (cause) {
|
||||
const failure = execFileOutputFailure(cause);
|
||||
if (signal?.aborted || failure?.code === "ABORT_ERR")
|
||||
throw new AnalysisCancelledError("inspect_adb_client", { cause });
|
||||
if (failure?.code === "ENOENT")
|
||||
throw new AdbConfigurationFailure(
|
||||
"binary_missing",
|
||||
`The selected adb binary was not found: ${selection.binary}`,
|
||||
{
|
||||
selected_binary: selection.binary,
|
||||
path_source: selection.pathSource,
|
||||
remediation: `Set ${ADB_BINARY_ENV} to an absolute path to an existing adb binary`,
|
||||
},
|
||||
{ cause },
|
||||
);
|
||||
throw new AdbConfigurationFailure(
|
||||
"version_unresolved",
|
||||
"The selected adb binary did not report a usable version",
|
||||
{
|
||||
selected_binary: selection.binary,
|
||||
...(failure === undefined
|
||||
? {}
|
||||
: {
|
||||
exit_code: failure.code,
|
||||
stderr_excerpt: failure.stderr.slice(0, 512),
|
||||
}),
|
||||
},
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Availability in the shape shared by every provider. */
|
||||
const rejectionCodeOf = (
|
||||
code: AdbConfigurationFailureCode,
|
||||
): ProviderRejectionCode =>
|
||||
code === "binary_missing"
|
||||
? "executable_missing"
|
||||
: code === "not_absolute"
|
||||
? "not_configured"
|
||||
: "version_unresolved";
|
||||
|
||||
export const adbConfigurationAvailability = (
|
||||
cause: AdbConfigurationFailure,
|
||||
): ProviderAvailability =>
|
||||
({
|
||||
status: "unavailable",
|
||||
code: rejectionCodeOf(cause.code),
|
||||
reason: cause.message,
|
||||
diagnostics: { ...cause.diagnostics },
|
||||
}) as ProviderAvailability;
|
||||
@@ -0,0 +1,242 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseAdbDevicesOutput,
|
||||
parseGetpropOutput,
|
||||
parsePackageListOutput,
|
||||
parsePmPathOutput,
|
||||
} from "./AdbDeviceOutput.js";
|
||||
|
||||
describe("parseAdbDevicesOutput", () => {
|
||||
it("parses emulator, USB, and network devices with their metadata", () => {
|
||||
const output = [
|
||||
"List of devices attached",
|
||||
"emulator-5554 device product:sdk_gphone64_x86_64 model:sdk_gphone64_x86_64 device:emu64xa transport_id:1",
|
||||
"07ef9c2a device usb:1-1 product:raven model:Pixel_6_Pro device:raven transport_id:2",
|
||||
"192.168.1.42:5555 device product:mock model:mock transport_id:3",
|
||||
"",
|
||||
].join("\n");
|
||||
const { devices, unparsedLines, daemonStarted } =
|
||||
parseAdbDevicesOutput(output);
|
||||
expect(unparsedLines).toEqual([]);
|
||||
expect(daemonStarted).toBe(false);
|
||||
expect(devices).toEqual([
|
||||
{
|
||||
serial: "emulator-5554",
|
||||
state: "device",
|
||||
transport: "tcp",
|
||||
product: "sdk_gphone64_x86_64",
|
||||
model: "sdk_gphone64_x86_64",
|
||||
device: "emu64xa",
|
||||
transport_id: 1,
|
||||
kind: "emulator",
|
||||
kind_basis: "emulator_serial_prefix",
|
||||
},
|
||||
{
|
||||
serial: "07ef9c2a",
|
||||
state: "device",
|
||||
transport: "usb",
|
||||
product: "raven",
|
||||
model: "Pixel_6_Pro",
|
||||
device: "raven",
|
||||
transport_id: 2,
|
||||
kind: "physical",
|
||||
kind_basis: "usb_transport",
|
||||
},
|
||||
{
|
||||
serial: "192.168.1.42:5555",
|
||||
state: "device",
|
||||
transport: "tcp",
|
||||
product: "mock",
|
||||
model: "mock",
|
||||
device: null,
|
||||
transport_id: 3,
|
||||
kind: "unknown",
|
||||
kind_basis: "none",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes daemon startup notices instead of failing the listing", () => {
|
||||
const output = [
|
||||
"* daemon not running; starting now at tcp:5037",
|
||||
"* daemon started successfully",
|
||||
"List of devices attached",
|
||||
"emulator-5554 device transport_id:1",
|
||||
"",
|
||||
].join("\n");
|
||||
const { devices, daemonStarted } = parseAdbDevicesOutput(output);
|
||||
expect(daemonStarted).toBe(true);
|
||||
expect(devices).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps non-device states such as unauthorized and offline", () => {
|
||||
const output = [
|
||||
"List of devices attached",
|
||||
"emulator-5556 offline transport_id:2",
|
||||
"HT84L0240512 unauthorized usb:1-2 transport_id:3",
|
||||
"",
|
||||
].join("\n");
|
||||
const { devices } = parseAdbDevicesOutput(output);
|
||||
expect(devices.map((device) => [device.serial, device.state])).toEqual([
|
||||
["emulator-5556", "offline"],
|
||||
["HT84L0240512", "unauthorized"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns unrecognized lines instead of dropping them", () => {
|
||||
const output = [
|
||||
"List of devices attached",
|
||||
"this is not a device line",
|
||||
"",
|
||||
].join("\n");
|
||||
const { unparsedLines } = parseAdbDevicesOutput(output);
|
||||
expect(unparsedLines).toEqual(["this is not a device line"]);
|
||||
});
|
||||
|
||||
it("reports a non-numeric transport_id as unknown", () => {
|
||||
const output = [
|
||||
"List of devices attached",
|
||||
"emulator-5554 device transport_id:not-a-number",
|
||||
"",
|
||||
].join("\n");
|
||||
const { devices } = parseAdbDevicesOutput(output);
|
||||
expect(devices[0]?.transport_id).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseGetpropOutput", () => {
|
||||
it("projects the whitelisted build identity from a real dump", () => {
|
||||
const dump = [
|
||||
"[ro.build.version.release]: [14]",
|
||||
"[ro.build.version.sdk]: [34]",
|
||||
"[ro.build.version.security_patch]: [2024-06-05]",
|
||||
"[ro.build.id]: [AP21.240617.014]",
|
||||
"[ro.build.fingerprint]: [google/sdk_gphone64_x86_64/emu64xa:14/AP21.240617.014/12094027:userdebug/dev-keys]",
|
||||
"[ro.product.brand]: [google]",
|
||||
"[ro.product.device]: [emu64xa]",
|
||||
"[ro.product.manufacturer]: [Google]",
|
||||
"[ro.product.model]: [sdk_gphone64_x86_64]",
|
||||
"[ro.product.cpu.abilist]: [x86_64,x86,arm64-v8a,armeabi-v7a,armeabi]",
|
||||
"[ro.kernel.qemu]: [1]",
|
||||
"[ro.debuggable]: [1]",
|
||||
"[sys.unlisted.property]: [dropped]",
|
||||
"",
|
||||
].join("\n");
|
||||
const { properties, emulatorObserved } = parseGetpropOutput(dump);
|
||||
expect(emulatorObserved).toBe(true);
|
||||
expect(properties).not.toContainEqual({
|
||||
name: "sys.unlisted.property",
|
||||
value: "dropped",
|
||||
});
|
||||
expect(properties).toEqual([
|
||||
{ name: "ro.build.version.release", value: "14" },
|
||||
{ name: "ro.build.version.sdk", value: "34" },
|
||||
{ name: "ro.build.version.security_patch", value: "2024-06-05" },
|
||||
{ name: "ro.build.id", value: "AP21.240617.014" },
|
||||
{
|
||||
name: "ro.build.fingerprint",
|
||||
value:
|
||||
"google/sdk_gphone64_x86_64/emu64xa:14/AP21.240617.014/12094027:userdebug/dev-keys",
|
||||
},
|
||||
{ name: "ro.debuggable", value: "1" },
|
||||
{ name: "ro.kernel.qemu", value: "1" },
|
||||
{ name: "ro.product.brand", value: "google" },
|
||||
{ name: "ro.product.device", value: "emu64xa" },
|
||||
{ name: "ro.product.manufacturer", value: "Google" },
|
||||
{ name: "ro.product.model", value: "sdk_gphone64_x86_64" },
|
||||
{
|
||||
name: "ro.product.cpu.abilist",
|
||||
value: "x86_64,x86,arm64-v8a,armeabi-v7a,armeabi",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports an explicit non-emulator build without inventing a value", () => {
|
||||
const dump = [
|
||||
"[ro.build.version.release]: [13]",
|
||||
"[ro.kernel.qemu]: [0]",
|
||||
"",
|
||||
].join("\n");
|
||||
const { emulatorObserved } = parseGetpropOutput(dump);
|
||||
expect(emulatorObserved).toBe(false);
|
||||
});
|
||||
|
||||
it("reports the emulator indicator unknown when the build omits it", () => {
|
||||
const { emulatorObserved } = parseGetpropOutput(
|
||||
"[ro.build.version.sdk]: [33]\n",
|
||||
);
|
||||
expect(emulatorObserved).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePackageListOutput", () => {
|
||||
it("parses package lines with their base APK device paths", () => {
|
||||
const output = [
|
||||
"package:/data/app/~~xy==/com.example.npzyCvVb1I-YzKIsGFvVYw==/base.apk=com.example",
|
||||
"package:/system/app/WebView/WebView.apk=com.android.webview",
|
||||
"",
|
||||
].join("\n");
|
||||
const { packages, unparsedLines } = parsePackageListOutput(output);
|
||||
expect(unparsedLines).toEqual([]);
|
||||
expect(packages).toEqual([
|
||||
{
|
||||
package_name: "com.example",
|
||||
base_apk_device_path:
|
||||
"/data/app/~~xy==/com.example.npzyCvVb1I-YzKIsGFvVYw==/base.apk",
|
||||
},
|
||||
{
|
||||
package_name: "com.android.webview",
|
||||
base_apk_device_path: "/system/app/WebView/WebView.apk",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps unrecognized lines for partial coverage reporting", () => {
|
||||
const { packages, unparsedLines } = parsePackageListOutput(
|
||||
"package:/data/app/x/base.apk=com.ok\ngarbage line\n",
|
||||
);
|
||||
expect(packages).toHaveLength(1);
|
||||
expect(unparsedLines).toEqual(["garbage line"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePmPathOutput", () => {
|
||||
it("classifies base and split APKs from their file names", () => {
|
||||
const output = [
|
||||
"package:/data/app/~~a==/com.example.b==/base.apk",
|
||||
"package:/data/app/~~a==/com.example.b==/split_config.arm64_v8a.apk",
|
||||
"package:/data/app/~~a==/com.example.b==/split_config.en.apk",
|
||||
"",
|
||||
].join("\n");
|
||||
const { paths, unparsedLines } = parsePmPathOutput(output);
|
||||
expect(unparsedLines).toEqual([]);
|
||||
expect(paths).toEqual([
|
||||
{
|
||||
device_path: "/data/app/~~a==/com.example.b==/base.apk",
|
||||
file_name: "base.apk",
|
||||
role: "base",
|
||||
},
|
||||
{
|
||||
device_path:
|
||||
"/data/app/~~a==/com.example.b==/split_config.arm64_v8a.apk",
|
||||
file_name: "split_config.arm64_v8a.apk",
|
||||
role: "split",
|
||||
},
|
||||
{
|
||||
device_path: "/data/app/~~a==/com.example.b==/split_config.en.apk",
|
||||
file_name: "split_config.en.apk",
|
||||
role: "split",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports an unknown role for names that follow neither convention", () => {
|
||||
const { paths } = parsePmPathOutput("package:/system/app/X/Y.apk\n");
|
||||
expect(paths[0]).toEqual({
|
||||
device_path: "/system/app/X/Y.apk",
|
||||
file_name: "Y.apk",
|
||||
role: "unknown",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* Parsers for the exact adb and Package Manager output formats REA consumes.
|
||||
*
|
||||
* Each parser preserves what the tool actually printed: unparseable lines are
|
||||
* retained rather than silently dropped, and derived classifications carry
|
||||
* their evidence basis.
|
||||
*/
|
||||
|
||||
/** One device exactly as `adb devices -l` reports it. */
|
||||
export interface AdbDeviceEntry {
|
||||
readonly serial: string;
|
||||
readonly state: string;
|
||||
readonly transport: "usb" | "tcp" | "unknown";
|
||||
readonly product: string | null;
|
||||
readonly model: string | null;
|
||||
readonly device: string | null;
|
||||
readonly transport_id: number | null;
|
||||
readonly kind: "emulator" | "physical" | "unknown";
|
||||
readonly kind_basis: "emulator_serial_prefix" | "usb_transport" | "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* Device states adb prints after the serial, longest first so two-word
|
||||
* states match before their single-word prefixes. A line whose remainder
|
||||
* starts with none of them is not a device line.
|
||||
*/
|
||||
const DEVICE_STATES = [
|
||||
"no permissions",
|
||||
"unauthorized",
|
||||
"authorizing",
|
||||
"offline",
|
||||
"recovery",
|
||||
"sideload",
|
||||
"connecting",
|
||||
"bootloader",
|
||||
"device",
|
||||
"unknown",
|
||||
"host",
|
||||
] as const;
|
||||
|
||||
const DEVICE_LINE = /^(\S+)\s+(.*)$/u;
|
||||
|
||||
const metadataValue = (remainder: string, key: string): string | null => {
|
||||
const match = new RegExp(`(?:^|\\s)${key}:(\\S+)`, "u").exec(remainder);
|
||||
return match === null ? null : match[1]!;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `adb devices -l` device lines. The banner, blank lines, and the
|
||||
* daemon startup notices adb prints on first use are recognized separately;
|
||||
* every other unrecognized line is returned for honest reporting.
|
||||
*/
|
||||
export const parseAdbDevicesOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
devices: readonly AdbDeviceEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
daemonStarted: boolean;
|
||||
} => {
|
||||
const devices: AdbDeviceEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
let daemonStarted = false;
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (line === "" || line.startsWith("List of devices attached")) continue;
|
||||
if (line.startsWith("* daemon")) {
|
||||
if (line.includes("started successfully")) daemonStarted = true;
|
||||
continue;
|
||||
}
|
||||
const match = DEVICE_LINE.exec(line);
|
||||
const state = DEVICE_STATES.find((candidate) =>
|
||||
match?.[2]?.startsWith(candidate),
|
||||
);
|
||||
if (match === null || state === undefined) {
|
||||
if (line.trim() !== "") unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
const serial = match[1]!;
|
||||
const remainder = match[2]!.slice(state.length);
|
||||
const usb = metadataValue(remainder, "usb");
|
||||
const transportIdText = metadataValue(remainder, "transport_id");
|
||||
const parsedTransportId =
|
||||
transportIdText === null || !/^\d+$/u.test(transportIdText)
|
||||
? null
|
||||
: Number(transportIdText);
|
||||
const isEmulator = /^emulator-\d+$/u.test(serial);
|
||||
const kind = isEmulator
|
||||
? ("emulator" as const)
|
||||
: usb !== null
|
||||
? ("physical" as const)
|
||||
: ("unknown" as const);
|
||||
devices.push({
|
||||
serial,
|
||||
state,
|
||||
transport:
|
||||
usb !== null
|
||||
? "usb"
|
||||
: isEmulator || serial.includes(":")
|
||||
? "tcp"
|
||||
: "unknown",
|
||||
product: metadataValue(remainder, "product"),
|
||||
model: metadataValue(remainder, "model"),
|
||||
device: metadataValue(remainder, "device"),
|
||||
transport_id: parsedTransportId,
|
||||
kind,
|
||||
kind_basis:
|
||||
kind === "emulator"
|
||||
? "emulator_serial_prefix"
|
||||
: kind === "physical"
|
||||
? "usb_transport"
|
||||
: "none",
|
||||
});
|
||||
}
|
||||
return { devices, unparsedLines, daemonStarted };
|
||||
};
|
||||
|
||||
/**
|
||||
* Properties projected from a `getprop` dump. The whitelist keeps device
|
||||
* inspection to build identity facts; a full dump is out of scope.
|
||||
*/
|
||||
const DEVICE_PROPERTY_WHITELIST = [
|
||||
"ro.build.version.release",
|
||||
"ro.build.version.sdk",
|
||||
"ro.build.version.security_patch",
|
||||
"ro.build.id",
|
||||
"ro.build.fingerprint",
|
||||
"ro.build.characteristics",
|
||||
"ro.debuggable",
|
||||
"ro.kernel.qemu",
|
||||
"ro.product.brand",
|
||||
"ro.product.device",
|
||||
"ro.product.manufacturer",
|
||||
"ro.product.model",
|
||||
"ro.product.cpu.abilist",
|
||||
] as const;
|
||||
|
||||
export interface AdbDeviceProperty {
|
||||
readonly name: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
/** Parse a full `getprop` dump into `[name]: [value]` pairs. */
|
||||
export const parseGetpropOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
properties: readonly AdbDeviceProperty[];
|
||||
emulatorObserved: boolean | null;
|
||||
} => {
|
||||
const values = new Map<string, string>();
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const match = /^\[([^\]]+)\]:\s*\[(.*)\]$/u.exec(rawLine.trim());
|
||||
if (match === null) continue;
|
||||
values.set(match[1]!, match[2]!);
|
||||
}
|
||||
const properties = DEVICE_PROPERTY_WHITELIST.flatMap((name) => {
|
||||
const value = values.get(name);
|
||||
return value === undefined || value === ""
|
||||
? []
|
||||
: [{ name, value } satisfies AdbDeviceProperty];
|
||||
});
|
||||
const qemu = values.get("ro.kernel.qemu");
|
||||
return {
|
||||
properties,
|
||||
emulatorObserved: qemu === undefined ? null : qemu === "1",
|
||||
};
|
||||
};
|
||||
|
||||
/** One installed package exactly as `pm list packages -f` reports it. */
|
||||
export interface AdbPackageEntry {
|
||||
readonly package_name: string;
|
||||
readonly base_apk_device_path: string;
|
||||
}
|
||||
|
||||
const PACKAGE_LINE = /^package:(.+)=([^\s=]+)$/u;
|
||||
|
||||
/** Parse `pm list packages -f` lines, retaining unrecognized lines. */
|
||||
export const parsePackageListOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
packages: readonly AdbPackageEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
} => {
|
||||
const packages: AdbPackageEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trim();
|
||||
if (line === "") continue;
|
||||
const match = PACKAGE_LINE.exec(line);
|
||||
if (match === null) {
|
||||
unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
packages.push({
|
||||
package_name: match[2]!,
|
||||
base_apk_device_path: match[1]!,
|
||||
});
|
||||
}
|
||||
return { packages, unparsedLines };
|
||||
};
|
||||
|
||||
/** One APK of an installed package exactly as `pm path` reports it. */
|
||||
export interface AdbPackagePathEntry {
|
||||
readonly device_path: string;
|
||||
readonly file_name: string;
|
||||
readonly role: "base" | "split" | "unknown";
|
||||
}
|
||||
|
||||
const fileNameOf = (devicePath: string): string => {
|
||||
const parts = devicePath.split(/\//u);
|
||||
return parts[parts.length - 1] ?? devicePath;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `pm path PACKAGE` lines. The base/split role is derived from the file
|
||||
* name (`base.apk`, `split_*.apk`), which is the only signal the output
|
||||
* carries; any other name reports an unknown role.
|
||||
*/
|
||||
export const parsePmPathOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
paths: readonly AdbPackagePathEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
} => {
|
||||
const paths: AdbPackagePathEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trim();
|
||||
if (line === "") continue;
|
||||
const match = /^package:(\S+)$/u.exec(line);
|
||||
if (match === null) {
|
||||
unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
const devicePath = match[1]!;
|
||||
const fileName = fileNameOf(devicePath);
|
||||
paths.push({
|
||||
device_path: devicePath,
|
||||
file_name: fileName,
|
||||
role:
|
||||
fileName === "base.apk"
|
||||
? "base"
|
||||
: fileName.startsWith("split_") && fileName.endsWith(".apk")
|
||||
? "split"
|
||||
: "unknown",
|
||||
});
|
||||
}
|
||||
return { paths, unparsedLines };
|
||||
};
|
||||
@@ -0,0 +1,960 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
chmod,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, onTestFinished, test } from "vitest";
|
||||
|
||||
import { AdbProvider } from "./AdbProvider.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { AdbRequest } from "../domain/adb/adbDeviceAnalysis.js";
|
||||
|
||||
const it = test.skipIf(process.platform === "win32");
|
||||
|
||||
const VERSION_BLOCK =
|
||||
"printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' \"$0\"";
|
||||
|
||||
const writeAdbStub = async (
|
||||
body: (root: string) => string,
|
||||
): Promise<{ readonly binary: string; readonly root: string }> => {
|
||||
const root = await mkdtemp(join("/tmp", "rea-adb-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const binary = join(root, "adb");
|
||||
await writeFile(binary, `#!/bin/sh\n${body(root)}\n`, { mode: 0o755 });
|
||||
await chmod(binary, 0o755);
|
||||
return { binary, root };
|
||||
};
|
||||
|
||||
const providerOver = (binary: string): AdbProvider =>
|
||||
new AdbProvider({ environment: { REA_ADB_PATH: binary } });
|
||||
|
||||
const evidenceResult = async (
|
||||
provider: AdbProvider,
|
||||
request: AdbRequest,
|
||||
): Promise<Record<string, unknown>> => {
|
||||
const result = await provider.execute(request);
|
||||
if (!result.ok) throw new Error(result.error.message);
|
||||
return result.value.result as Record<string, unknown>;
|
||||
};
|
||||
|
||||
const refusedBy = async (
|
||||
provider: AdbProvider,
|
||||
request: AdbRequest,
|
||||
): Promise<ReturnType<typeof projectAnalysisError>> => {
|
||||
const result = await provider.execute(request);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected a refusal");
|
||||
return projectAnalysisError(result.error);
|
||||
};
|
||||
|
||||
it("inspects the adb client without contacting the server", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; fi`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_client",
|
||||
input: {},
|
||||
});
|
||||
expect(result.client).toMatchObject({
|
||||
path_source: "environment",
|
||||
version: "34.0.5-stub",
|
||||
installed_path: binary,
|
||||
});
|
||||
expect(result.contacted_adb_server).toBe(false);
|
||||
});
|
||||
|
||||
it("lists devices with inferred kinds and observed daemon startup", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "devices" ]; then
|
||||
printf '* daemon not running; starting now at tcp:5037\\n* daemon started successfully\\n'
|
||||
printf 'List of devices attached\\n'
|
||||
printf 'emulator-5554 device product:sdk_gphone64_x86_64 model:sdk_gphone64_x86_64 device:emu64xa transport_id:1\\n'
|
||||
exit 0
|
||||
fi`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_devices",
|
||||
input: {},
|
||||
});
|
||||
expect(result.may_have_started_adb_server).toBe(true);
|
||||
expect(result.devices).toEqual([
|
||||
{
|
||||
serial: "emulator-5554",
|
||||
state: "device",
|
||||
transport: "tcp",
|
||||
product: "sdk_gphone64_x86_64",
|
||||
model: "sdk_gphone64_x86_64",
|
||||
device: "emu64xa",
|
||||
transport_id: 1,
|
||||
kind: "emulator",
|
||||
kind_basis: "emulator_serial_prefix",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("inspects a device through the getprop whitelist", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "shell" ] && [ "$4" = "getprop" ]; then
|
||||
printf '[ro.build.version.sdk]: [34]\\n[ro.kernel.qemu]: [1]\\n[sys.private]: [x]\\n'
|
||||
exit 0
|
||||
fi`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_device",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(result.emulator_observed).toBe(true);
|
||||
expect(result.properties).toEqual([
|
||||
{ name: "ro.build.version.sdk", value: "34" },
|
||||
{ name: "ro.kernel.qemu", value: "1" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("passes the caller scope as an exact fixed argv vector", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `printf '%s\\n' "$@" >> ${join(root, "argv.log")}
|
||||
if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "shell" ]; then printf 'package:/data/app/x/base.apk=com.example\\n'; exit 0; fi`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_packages",
|
||||
input: { serial: "emulator-5554", scope: "third_party" },
|
||||
});
|
||||
expect(result.coverage).toBe("complete");
|
||||
expect(result.packages).toEqual([
|
||||
{
|
||||
package_name: "com.example",
|
||||
base_apk_device_path: "/data/app/x/base.apk",
|
||||
},
|
||||
]);
|
||||
const logged = (await readFile(join(root, "argv.log"), "utf8"))
|
||||
.trim()
|
||||
.split("\n");
|
||||
expect(logged).toEqual([
|
||||
"version",
|
||||
"-s",
|
||||
"emulator-5554",
|
||||
"shell",
|
||||
"pm",
|
||||
"list",
|
||||
"packages",
|
||||
"-f",
|
||||
"-3",
|
||||
]);
|
||||
});
|
||||
|
||||
const pullStub = (
|
||||
paths: string,
|
||||
pullBody: string,
|
||||
): string => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "pm" ] && [ "$5" = "path" ]; then
|
||||
printf '%s\\n' ${paths}
|
||||
exit 0
|
||||
fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "pull" ]; then
|
||||
${pullBody}
|
||||
exit 0
|
||||
fi
|
||||
printf 'unexpected arguments: %s\\n' "$@"
|
||||
exit 1`;
|
||||
|
||||
/** Stub dispatching one canned stdout per first shell word (and optional second). */
|
||||
const shellStub = (
|
||||
dispatch: Readonly<Record<string, string>>,
|
||||
): ((root: string) => string) => {
|
||||
const cases = Object.entries(dispatch)
|
||||
.map(([key, output]) => {
|
||||
const [first, second] = key.split(":");
|
||||
const guard =
|
||||
second === undefined
|
||||
? `[ "$4" = "${first}" ]`
|
||||
: `[ "$4" = "${first}" ] && [ "$5" = "${second}" ]`;
|
||||
return ` if ${guard}; then printf '%b' '${output.replace(/'/gu, "'\\''")}'; exit 0; fi`;
|
||||
})
|
||||
.join("\n");
|
||||
return () => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "shell" ]; then
|
||||
${cases}
|
||||
printf 'unexpected shell command: %s %s %s\\n' "$4" "$5" "$6" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'unexpected arguments: %s\\n' "$@"
|
||||
exit 1`;
|
||||
};
|
||||
|
||||
it("pulls a complete split set with digests into a new package directory", async () => {
|
||||
const { binary, root } = await writeAdbStub(() =>
|
||||
pullStub(
|
||||
"'package:/data/app/~~a==/com.example.b==/base.apk' 'package:/data/app/~~a==/com.example.b==/split_config.en.apk'",
|
||||
` printf 'apk-bytes-for-testing' > "$5"
|
||||
printf '1 file pulled, 0 skipped.\\n'`,
|
||||
),
|
||||
);
|
||||
const output = join(root, "pulls");
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "pull_adb_package",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
package: "com.example",
|
||||
output_directory: output,
|
||||
},
|
||||
});
|
||||
expect(result.coverage).toBe("complete");
|
||||
expect(result.failures).toEqual([]);
|
||||
const artifacts = result.artifacts as {
|
||||
file_name: string;
|
||||
local_path: string;
|
||||
sha256: string;
|
||||
role: string;
|
||||
}[];
|
||||
expect(
|
||||
artifacts.map((artifact) => [artifact.file_name, artifact.role]),
|
||||
).toEqual([
|
||||
["base.apk", "base"],
|
||||
["split_config.en.apk", "split"],
|
||||
]);
|
||||
const digest = createHash("sha256")
|
||||
.update("apk-bytes-for-testing")
|
||||
.digest("hex");
|
||||
for (const artifact of artifacts) expect(artifact.sha256).toBe(digest);
|
||||
const pulled = await readFile(
|
||||
join(output, "com.example", "base.apk"),
|
||||
"utf8",
|
||||
);
|
||||
expect(pulled).toBe("apk-bytes-for-testing");
|
||||
});
|
||||
|
||||
it("keeps successful artifacts when one split pull fails", async () => {
|
||||
const { binary, root } = await writeAdbStub(() =>
|
||||
pullStub(
|
||||
"'package:/data/app/y/base.apk' 'package:/data/app/y/split_dpi.apk'",
|
||||
`case "$4" in
|
||||
*/split_dpi.apk) printf 'error: closed\\n' >&2; exit 1;;
|
||||
*) printf 'apk-bytes-for-testing' > "$5"; printf '1 file pulled.\\n';;
|
||||
esac`,
|
||||
),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "pull_adb_package",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
package: "com.partial",
|
||||
output_directory: join(root, "pulls"),
|
||||
},
|
||||
});
|
||||
expect(result.coverage).toBe("partial");
|
||||
expect(result.artifacts).toHaveLength(1);
|
||||
expect(result.failures).toEqual([
|
||||
{
|
||||
device_path: "/data/app/y/split_dpi.apk",
|
||||
stage: "pull",
|
||||
message: expect.stringContaining("closed") as unknown,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses to reuse an existing package output directory", async () => {
|
||||
const { binary, root } = await writeAdbStub(() =>
|
||||
pullStub("'package:/data/app/z/base.apk'", ` printf 'x' > "$5"`),
|
||||
);
|
||||
const output = join(root, "existing");
|
||||
await mkdir(join(output, "com.example"), { recursive: true });
|
||||
const provider = providerOver(binary);
|
||||
const result = await provider.execute({
|
||||
operation: "pull_adb_package",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
package: "com.example",
|
||||
output_directory: output,
|
||||
},
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "unreadable_output",
|
||||
});
|
||||
expect(result.error.message).toContain("already exists");
|
||||
});
|
||||
|
||||
it("reports an uninstalled package from empty pm path output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "pm" ] && [ "$5" = "path" ]; then exit 0; fi`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "pull_adb_package",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
package: "com.absent",
|
||||
output_directory: "/tmp/rea-adb-absent",
|
||||
},
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unsupported_target" });
|
||||
expect(projected.message).toContain("no APK paths");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["not found", "error: device 'emulator-9' not found", "not found"],
|
||||
["offline", "error: device offline", "offline"],
|
||||
["unauthorized", "error: device unauthorized", "unauthorized"],
|
||||
] as const)(
|
||||
"reports the %s device state as a target refusal",
|
||||
async (_, stderr, excerpt) => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ]; then printf '%s\\n' "${stderr.replace(/'/gu, "'\\''")}" >&2; exit 1; fi`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "inspect_adb_device",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unsupported_target" });
|
||||
expect(projected.message).toContain(excerpt);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports a missing selected binary as a capability gap with recovery", async () => {
|
||||
const provider = new AdbProvider({
|
||||
environment: { REA_ADB_PATH: "/nonexistent/adb" },
|
||||
});
|
||||
const availability = await provider.inspectAvailability();
|
||||
expect(availability).toMatchObject({ status: "unavailable" });
|
||||
if (availability.status !== "unavailable") return;
|
||||
expect(availability.diagnostics.remediation).toContain("REA_ADB_PATH");
|
||||
const result = await provider.execute({
|
||||
operation: "list_adb_devices",
|
||||
input: {},
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected).toMatchObject({ code: "capability_unavailable" });
|
||||
expect(projected.details).toMatchObject({
|
||||
provider_id: "adb",
|
||||
reason: expect.stringContaining("not found") as unknown,
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels before spawning anything", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `: > ${join(root, "spawned")}
|
||||
if [ "$1" = "version" ]; then ${VERSION_BLOCK}; fi`,
|
||||
);
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await providerOver(binary).execute(
|
||||
{ operation: "list_adb_devices", input: {} },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(cancelled.ok).toBe(false);
|
||||
if (cancelled.ok) return;
|
||||
expect(projectAnalysisError(cancelled.error)).toMatchObject({
|
||||
code: "cancelled",
|
||||
});
|
||||
expect(
|
||||
await readFile(join(root, "spawned")).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("reads a bounded logcat dump with the caller count and buffer", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
logcat:
|
||||
"08-10 13:00:00.000 I/Tag( 123): first\\n08-10 13:00:01.000 I/Tag( 123): second\\n",
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "read_adb_logcat",
|
||||
input: { serial: "emulator-5554", count: 500, buffer: "main" },
|
||||
});
|
||||
expect(result.lines).toEqual([
|
||||
"08-10 13:00:00.000 I/Tag( 123): first",
|
||||
"08-10 13:00:01.000 I/Tag( 123): second",
|
||||
]);
|
||||
});
|
||||
|
||||
it("projects package details from dumpsys package output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
"dumpsys:package": `Packages:
|
||||
Package [com.example] (abcdef):
|
||||
userId=10234
|
||||
versionName=1.2.3
|
||||
versionCode=45 minSdk=24 targetSdk=34
|
||||
firstInstallTime=2026-01-02 03:04:05
|
||||
lastUpdateTime=2026-02-03 04:05:06
|
||||
installerPackageName=com.android.vending
|
||||
pkgFlags=[ HAS_CODE ALLOW_CLEAR_USER_DATA ]
|
||||
requested permissions:
|
||||
android.permission.INTERNET
|
||||
android.permission.CAMERA
|
||||
`,
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.example" },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
version_name: "1.2.3",
|
||||
version_code: 45,
|
||||
first_install_time: "2026-01-02 03:04:05",
|
||||
last_update_time: "2026-02-03 04:05:06",
|
||||
installer_package_name: "com.android.vending",
|
||||
user_id: 10234,
|
||||
requested_permissions_count: 2,
|
||||
coverage: "complete",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an uninstalled package from dumpsys refusal output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({ "dumpsys:package": "Unable to find package: com.absent\n" }),
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "inspect_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.absent" },
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unsupported_target" });
|
||||
});
|
||||
|
||||
it("pulls one device file with a digest", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "pull" ]; then printf 'file-bytes' > "$5"; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const output = join(root, "pulls");
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "pull_adb_file",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
device_path: "/data/local/tmp/notes.txt",
|
||||
output_directory: output,
|
||||
},
|
||||
});
|
||||
const digest = createHash("sha256").update("file-bytes").digest("hex");
|
||||
expect(result).toMatchObject({
|
||||
device_path: "/data/local/tmp/notes.txt",
|
||||
local_path: join(output, "notes.txt"),
|
||||
bytes: 10,
|
||||
sha256: digest,
|
||||
});
|
||||
});
|
||||
|
||||
it("pushes a file and verifies the device-side digest", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "test" ]; then exit 1; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "push" ]; then exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "sha256sum" ]; then printf '%s %s\\n' "8748b5d17d1ebcec7d46674fa6a8b92c0f95598a552f27c1c8a132eb58c04043" "$5"; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const localFile = join(root, "payload.bin");
|
||||
await writeFile(localFile, "push-payload");
|
||||
const digest = createHash("sha256").update("push-payload").digest("hex");
|
||||
const pushed = await evidenceResult(providerOver(binary), {
|
||||
operation: "push_adb_file",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
local_path: localFile,
|
||||
device_path: "/data/local/tmp/payload.bin",
|
||||
overwrite: false,
|
||||
},
|
||||
});
|
||||
expect(pushed).toMatchObject({
|
||||
bytes: 12,
|
||||
sha256: digest,
|
||||
device_sha256: digest,
|
||||
overwritten: false,
|
||||
device_digest_source: "device_sha256sum",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a digest mismatch after push as a changed artifact", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "test" ]; then exit 1; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "push" ]; then exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "sha256sum" ]; then printf '%s %s\\n' "$(printf 'a%.0s' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64)" "$5"; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const localFile = join(root, "payload.bin");
|
||||
await writeFile(localFile, "push-payload");
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "push_adb_file",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
local_path: localFile,
|
||||
device_path: "/data/local/tmp/payload.bin",
|
||||
overwrite: false,
|
||||
},
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "artifact_changed" });
|
||||
});
|
||||
|
||||
it("refuses a push onto an existing device path without overwrite", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$4" = "test" ]; then exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const localFile = join(root, "payload.bin");
|
||||
await writeFile(localFile, "x");
|
||||
const result = await providerOver(binary).execute({
|
||||
operation: "push_adb_file",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
local_path: localFile,
|
||||
device_path: "/data/local/tmp/exists.bin",
|
||||
overwrite: false,
|
||||
},
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "unreadable_output",
|
||||
});
|
||||
expect(result.error.message).toContain("overwrite");
|
||||
});
|
||||
|
||||
it("reports a local push source that does not exist", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "push_adb_file",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
local_path: "/nonexistent/payload.bin",
|
||||
device_path: "/data/local/tmp/payload.bin",
|
||||
overwrite: false,
|
||||
},
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "invalid_request" });
|
||||
});
|
||||
|
||||
it("captures the screen as a digested PNG with its dimensions", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "exec-out" ]; then
|
||||
printf '\\211PNG\\r\\n\\032\\n\\0\\0\\0\\rIHDR\\0\\0\\0\\004\\0\\0\\0\\003'
|
||||
exit 0
|
||||
fi
|
||||
exit 1`,
|
||||
);
|
||||
const output = join(root, "captures");
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "capture_adb_screen",
|
||||
input: { serial: "emulator-5554", output_directory: output },
|
||||
});
|
||||
expect(result).toMatchObject({ width: 4, height: 3 });
|
||||
expect(
|
||||
await readFile(join(output, "screen.png")).then(
|
||||
(bytes) => bytes.subarray(1, 4).toString("latin1") === "PNG",
|
||||
() => false,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("lists processes, features, and services through fixed commands", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
ps: "USER PID PPID VSZ RSS WCHAN ADDR S NAME\nu0_a1 1234 567 123456 7890 0 0 S com.example.app\n",
|
||||
"pm:list":
|
||||
"feature:android.hardware.camera\nfeature:android.hardware.nfc=1\n",
|
||||
"service:list":
|
||||
"Found 2 services:\n 1 package: [android.content.pm.IPackageManager]\n 2 activity: [android.app.IActivityManager]\n",
|
||||
}),
|
||||
);
|
||||
const processes = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_processes",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(processes.processes).toEqual([
|
||||
{
|
||||
user: "u0_a1",
|
||||
pid: 1234,
|
||||
ppid: 567,
|
||||
rss: 7890,
|
||||
state: "S",
|
||||
name: "com.example.app",
|
||||
},
|
||||
]);
|
||||
const features = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_features",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(features.features).toEqual([
|
||||
{ name: "android.hardware.camera", version: null },
|
||||
{ name: "android.hardware.nfc", version: 1 },
|
||||
]);
|
||||
const services = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_services",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(services.services).toEqual([
|
||||
{ name: "package", interface: "android.content.pm.IPackageManager" },
|
||||
{ name: "activity", interface: "android.app.IActivityManager" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists a device directory with kinds and symlink targets", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
ls: "total 4\n-rw-rw---- u0_a1 u0_a1 4096 2026-01-02 11:00 app.db\nlrwxrwxrwx root root 2026-01-01 10:00 lib -> /apex/com.android.art/lib\n",
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_directory",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
device_path: "/data/data/com.example.app",
|
||||
},
|
||||
});
|
||||
expect(result.entries).toEqual([
|
||||
{
|
||||
name: "app.db",
|
||||
kind: "file",
|
||||
permissions: "-rw-rw----",
|
||||
owner: "u0_a1",
|
||||
group: "u0_a1",
|
||||
bytes: 4096,
|
||||
date: "2026-01-02 11:00",
|
||||
link_target: null,
|
||||
},
|
||||
{
|
||||
name: "lib",
|
||||
kind: "symlink",
|
||||
permissions: "lrwxrwxrwx",
|
||||
owner: "root",
|
||||
group: "root",
|
||||
bytes: null,
|
||||
date: "2026-01-01 10:00",
|
||||
link_target: "/apex/com.android.art/lib",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("inspects the display and window focus", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
"wm:size": "Physical size: 1080x2340\n",
|
||||
"wm:density": "Physical density: 420\n",
|
||||
"dumpsys:window":
|
||||
" mCurrentFocus=Window{abcdef u0 com.example.app/com.example.app.MainActivity}\n",
|
||||
}),
|
||||
);
|
||||
const display = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_display",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(display.physical_size).toEqual({ width: 1080, height: 2340 });
|
||||
expect(display.physical_density).toBe(420);
|
||||
const window = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_window",
|
||||
input: { serial: "emulator-5554" },
|
||||
});
|
||||
expect(window.focused_window).toBe(
|
||||
"Window{abcdef u0 com.example.app/com.example.app.MainActivity}",
|
||||
);
|
||||
});
|
||||
|
||||
it("reads one settings value and reports device-side nulls", async () => {
|
||||
const { binary } = await writeAdbStub(shellStub({ "settings:get": "1\n" }));
|
||||
const enabled = await evidenceResult(providerOver(binary), {
|
||||
operation: "read_adb_setting",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
namespace: "secure",
|
||||
key: "adb_enabled",
|
||||
},
|
||||
});
|
||||
expect(enabled.value).toBe("1");
|
||||
const { binary: nullBinary } = await writeAdbStub(
|
||||
shellStub({ "settings:get": "null\n" }),
|
||||
);
|
||||
const absent = await evidenceResult(providerOver(nullBinary), {
|
||||
operation: "read_adb_setting",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
namespace: "global",
|
||||
key: "absent_key",
|
||||
},
|
||||
});
|
||||
expect(absent.value).toBeNull();
|
||||
expect(absent.device_reported_null).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves packages by case-insensitive substring", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
"pm:list":
|
||||
"package:/data/app/x/base.apk=com.whatsapp\\npackage:/data/app/y/base.apk=com.whatsapp.w4b\\npackage:/data/app/z/base.apk=com.example\\n",
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "resolve_adb_packages",
|
||||
input: { serial: "emulator-5554", query: "WhatsApp" },
|
||||
});
|
||||
expect(result.matches).toEqual([
|
||||
{
|
||||
package_name: "com.whatsapp",
|
||||
base_apk_device_path: "/data/app/x/base.apk",
|
||||
},
|
||||
{
|
||||
package_name: "com.whatsapp.w4b",
|
||||
base_apk_device_path: "/data/app/y/base.apk",
|
||||
},
|
||||
]);
|
||||
expect(result.exact_match).toBe(false);
|
||||
expect(result.coverage).toBe("complete");
|
||||
});
|
||||
|
||||
it("installs a local APK and preserves the device's failure verdict", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "install" ]; then printf 'Success\\n'; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const apk = join(root, "app.apk");
|
||||
await writeFile(apk, "apk");
|
||||
const digest = createHash("sha256").update("apk").digest("hex");
|
||||
const installed = await evidenceResult(providerOver(binary), {
|
||||
operation: "install_adb_package",
|
||||
input: { serial: "emulator-5554", apk_path: apk, replace: false },
|
||||
});
|
||||
expect(installed).toMatchObject({
|
||||
bytes: 3,
|
||||
sha256: digest,
|
||||
replaced: false,
|
||||
});
|
||||
|
||||
const { binary: failing } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "install" ]; then printf 'Failure [INSTALL_FAILED_ALREADY_EXISTS]\\n'; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(failing), {
|
||||
operation: "install_adb_package",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
apk_path: apk,
|
||||
replace: false,
|
||||
},
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unsupported_target" });
|
||||
expect(projected.message).toContain("INSTALL_FAILED_ALREADY_EXISTS");
|
||||
});
|
||||
|
||||
it("uninstalls a package and reports the device's refusal for absent ones", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "uninstall" ]; then printf 'Success\\n'; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const removed = await evidenceResult(providerOver(binary), {
|
||||
operation: "uninstall_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.example" },
|
||||
});
|
||||
expect(removed.package_name).toBe("com.example");
|
||||
|
||||
const { binary: refusing } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "uninstall" ]; then printf 'Failure [not installed for 0]\\n'; exit 0; fi
|
||||
exit 1`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(refusing), {
|
||||
operation: "uninstall_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.absent" },
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unsupported_target" });
|
||||
expect(projected.message).toContain("not installed for 0");
|
||||
});
|
||||
|
||||
it("starts an app through resolved launcher component and force-stops it", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
"cmd:package":
|
||||
"priority=0 preferredOrder=0 match=0x00108000 specificIndex=-1 isDefault=true\ncom.example/.Main",
|
||||
"am:start":
|
||||
"Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example/.Main }\n",
|
||||
"am:force-stop": "",
|
||||
}),
|
||||
);
|
||||
const provider = providerOver(binary);
|
||||
const started = await evidenceResult(provider, {
|
||||
operation: "start_adb_app",
|
||||
input: { serial: "emulator-5554", package: "com.example" },
|
||||
});
|
||||
expect(started).toMatchObject({
|
||||
package_name: "com.example",
|
||||
component: "com.example/.Main",
|
||||
started_activity: expect.stringContaining(
|
||||
"cmp=com.example/.Main",
|
||||
) as unknown,
|
||||
});
|
||||
const stopped = await evidenceResult(provider, {
|
||||
operation: "stop_adb_app",
|
||||
input: { serial: "emulator-5554", package: "com.example" },
|
||||
});
|
||||
expect(stopped.package_name).toBe("com.example");
|
||||
});
|
||||
|
||||
it("reports an app without a launcher activity as unsupported", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({ "cmd:package": "No activity found\n" }),
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "start_adb_app",
|
||||
input: { serial: "emulator-5554", package: "com.library.only" },
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "unsupported_target" });
|
||||
expect(projected.message).toContain("No launcher activity");
|
||||
});
|
||||
|
||||
it("starts an intent with typed extras as a fixed argv vector", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `printf '%s\\n' "$@" >> ${join(root, "argv.log")}
|
||||
${shellStub({ "am:start": "Starting: Intent { act=android.intent.action.VIEW dat=https://example.com/ }\n" })(root)}`,
|
||||
);
|
||||
const started = await evidenceResult(providerOver(binary), {
|
||||
operation: "start_adb_activity",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
action: "android.intent.action.VIEW",
|
||||
data_uri: "https://example.com/",
|
||||
extras: [
|
||||
{ key: "level", type: "int", value: "3" },
|
||||
{ key: "label", type: "string", value: "probe" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(started.action).toBe("android.intent.action.VIEW");
|
||||
const logged = (await readFile(join(root, "argv.log"), "utf8"))
|
||||
.trim()
|
||||
.split("\n");
|
||||
expect(logged).toEqual([
|
||||
"version",
|
||||
"-s",
|
||||
"emulator-5554",
|
||||
"shell",
|
||||
"am",
|
||||
"start",
|
||||
"-W",
|
||||
"-a",
|
||||
"android.intent.action.VIEW",
|
||||
"-d",
|
||||
"https://example.com/",
|
||||
"--ei",
|
||||
"level",
|
||||
"3",
|
||||
"--es",
|
||||
"label",
|
||||
"probe",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects mistyped intent extras before touching the device", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
: > should-not-exist`,
|
||||
);
|
||||
const projected = await refusedBy(providerOver(binary), {
|
||||
operation: "start_adb_activity",
|
||||
input: {
|
||||
serial: "emulator-5554",
|
||||
action: "com.example.ACTION",
|
||||
extras: [{ key: "flag", type: "boolean", value: "yes" }],
|
||||
},
|
||||
});
|
||||
expect(projected).toMatchObject({ code: "invalid_request" });
|
||||
});
|
||||
|
||||
it("collects a device bugreport archive with its digest", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "-s" ] && [ "$3" = "bugreport" ]; then
|
||||
printf 'bugreport-bytes' > "${join(root, "bugreport test.zip")}"
|
||||
printf 'Bug report copied to ${join(root, "bugreport test.zip")}\\n'
|
||||
exit 0
|
||||
fi
|
||||
exit 1`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "collect_adb_bugreport",
|
||||
input: { serial: "emulator-5554", output_directory: root },
|
||||
});
|
||||
const digest = createHash("sha256").update("bugreport-bytes").digest("hex");
|
||||
expect(result).toMatchObject({
|
||||
local_path: join(root, "bugreport test.zip"),
|
||||
bytes: 15,
|
||||
sha256: digest,
|
||||
adb_reported_path: join(root, "bugreport test.zip"),
|
||||
});
|
||||
});
|
||||
|
||||
it("quotes caller text before adb joins the remote shell command", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
shift 3
|
||||
# Model adb's remote command joining, then execute the resulting shell string.
|
||||
printf '#!/bin/sh\nprintf "%%s" "$@" > "${join(root, "observed")}"\n' > "${join(root, "ls")}"
|
||||
chmod +x "${join(root, "ls")}"
|
||||
PATH="${root}:$PATH" sh -c "$*"
|
||||
`,
|
||||
);
|
||||
const value = `/sdcard/a 'quoted'; touch ${join(root, "injected")}`;
|
||||
await providerOver(binary).execute({
|
||||
operation: "list_adb_directory",
|
||||
input: { serial: "device", device_path: value },
|
||||
});
|
||||
expect(await readFile(join(root, "observed"), "utf8")).toContain(value);
|
||||
await expect(readFile(join(root, "injected"))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("preserves a screen output created while capture is running", async () => {
|
||||
const { binary, root } = await writeAdbStub(
|
||||
(root) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
printf 'existing evidence' > "${join(root, "captures", "screen.png")}"
|
||||
printf '\\211PNG\\r\\n\\032\\n\\0\\0\\0\\rIHDR\\0\\0\\0\\004\\0\\0\\0\\003'
|
||||
`,
|
||||
);
|
||||
const result = await providerOver(binary).execute({
|
||||
operation: "capture_adb_screen",
|
||||
input: { serial: "device", output_directory: join(root, "captures") },
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(await readFile(join(root, "captures", "screen.png"), "utf8")).toBe(
|
||||
"existing evidence",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports cancellation arriving during the version probe", async () => {
|
||||
const { binary } = await writeAdbStub(() => "exec sleep 30");
|
||||
const controller = new AbortController();
|
||||
const pending = providerOver(binary).execute(
|
||||
{ operation: "inspect_adb_client", input: {} },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const timer = setTimeout(() => controller.abort(), 50);
|
||||
try {
|
||||
const result = await pending;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(projectAnalysisError(result.error).code).toBe("cancelled");
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* Parsers for fixed observation commands REA runs through `adb shell`.
|
||||
*
|
||||
* Formats follow toybox output on Android 8+ (verified against an Android 14
|
||||
* emulator). Unparseable lines are retained rather than dropped so callers
|
||||
* can see the format drift instead of silently losing rows.
|
||||
*/
|
||||
|
||||
export interface AdbProcessEntry {
|
||||
readonly user: string;
|
||||
readonly pid: number;
|
||||
readonly ppid: number | null;
|
||||
readonly rss: number | null;
|
||||
readonly state: string | null;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
const PROCESS_LINE =
|
||||
/^(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/u;
|
||||
|
||||
/** Parse `ps -A` output; the header line is preserved verbatim as `columns`. */
|
||||
export const parseProcessListOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
columns: string | null;
|
||||
processes: readonly AdbProcessEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
} => {
|
||||
const processes: AdbProcessEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
let columns: string | null = null;
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (line === "") continue;
|
||||
if (/^USER\s+PID\s+PPID\b/u.test(line)) {
|
||||
columns = line.trim();
|
||||
continue;
|
||||
}
|
||||
const match = PROCESS_LINE.exec(line);
|
||||
if (match === null) {
|
||||
unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
processes.push({
|
||||
user: match[1]!,
|
||||
pid: Number(match[2]!),
|
||||
ppid: Number.isSafeInteger(Number(match[3]!)) ? Number(match[3]!) : null,
|
||||
rss: Number.isSafeInteger(Number(match[5]!)) ? Number(match[5]!) : null,
|
||||
state: match[8]!,
|
||||
name: match[9]!.trim(),
|
||||
});
|
||||
}
|
||||
return { columns, processes, unparsedLines };
|
||||
};
|
||||
|
||||
export interface AdbDirectoryEntry {
|
||||
readonly name: string;
|
||||
readonly kind: "directory" | "file" | "symlink" | "other";
|
||||
readonly permissions: string | null;
|
||||
readonly owner: string | null;
|
||||
readonly group: string | null;
|
||||
readonly bytes: number | null;
|
||||
readonly date: string | null;
|
||||
readonly link_target: string | null;
|
||||
}
|
||||
|
||||
const LS_LINE =
|
||||
/^([bcdlps-][rwxstST-]{9})\s+(?:(\d+)\s+)?(\S+)\s+(\S+)\s+(?:(\d+)\s+)?([\d-]{10})\s+([\d:]{4,8})\s+(.+)$/u;
|
||||
|
||||
/** Parse `ls -la` output, including `total` headers and symlink targets. */
|
||||
export const parseLsOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
entries: readonly AdbDirectoryEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
} => {
|
||||
const entries: AdbDirectoryEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (line === "" || line.startsWith("total ")) continue;
|
||||
const match = LS_LINE.exec(line);
|
||||
if (match === null) {
|
||||
if (line.trim() !== "") unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
const permissions = match[1]!;
|
||||
let name = match[8]!.trim();
|
||||
let linkTarget: string | null = null;
|
||||
const linkArrow = name.indexOf(" -> ");
|
||||
if (linkArrow !== -1 && permissions.startsWith("l")) {
|
||||
linkTarget = name.slice(linkArrow + 4);
|
||||
name = name.slice(0, linkArrow);
|
||||
}
|
||||
entries.push({
|
||||
name,
|
||||
kind: permissions.startsWith("d")
|
||||
? "directory"
|
||||
: permissions.startsWith("l")
|
||||
? "symlink"
|
||||
: permissions.startsWith("-")
|
||||
? "file"
|
||||
: "other",
|
||||
permissions,
|
||||
owner: match[3] ?? null,
|
||||
group: match[4] ?? null,
|
||||
bytes: match[5] === undefined ? null : Number(match[5]),
|
||||
date: `${match[6] ?? ""} ${match[7] ?? ""}`.trim() || null,
|
||||
link_target: linkTarget,
|
||||
});
|
||||
}
|
||||
return { entries, unparsedLines };
|
||||
};
|
||||
|
||||
export interface AdbFeatureEntry {
|
||||
readonly name: string;
|
||||
readonly version: number | null;
|
||||
}
|
||||
|
||||
const FEATURE_LINE = /^feature:([^=\s]+)(?:=(0x[0-9a-fA-F]+|\d+))?$/u;
|
||||
|
||||
const parseFeatureVersion = (text: string): number =>
|
||||
text.startsWith("0x") ? Number.parseInt(text.slice(2), 16) : Number(text);
|
||||
|
||||
/** Parse `pm list features` output, including hex GL versions. */
|
||||
export const parseFeatureListOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
features: readonly AdbFeatureEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
} => {
|
||||
const features: AdbFeatureEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trim();
|
||||
if (line === "") continue;
|
||||
const match = FEATURE_LINE.exec(line);
|
||||
if (match === null) {
|
||||
unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
features.push({
|
||||
name: match[1]!,
|
||||
version: match[2] === undefined ? null : parseFeatureVersion(match[2]!),
|
||||
});
|
||||
}
|
||||
return { features, unparsedLines };
|
||||
};
|
||||
|
||||
export interface AdbServiceEntry {
|
||||
readonly name: string;
|
||||
readonly interface: string | null;
|
||||
}
|
||||
|
||||
const SERVICE_LINE = /^\s*(?:\d+\s+)?([A-Za-z0-9._$/-]+):\s*\[([^\]]*)\]\s*$/u;
|
||||
|
||||
/** Parse `service list` output, tolerating numbered and plain formats. */
|
||||
export const parseServiceListOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
services: readonly AdbServiceEntry[];
|
||||
unparsedLines: readonly string[];
|
||||
} => {
|
||||
const services: AdbServiceEntry[] = [];
|
||||
const unparsedLines: string[] = [];
|
||||
for (const rawLine of stdout.split(/\r?\n/u)) {
|
||||
const line = rawLine.trimEnd();
|
||||
if (line.trim() === "" || /^Found \d+ services:/u.test(line.trim()))
|
||||
continue;
|
||||
const match = SERVICE_LINE.exec(line);
|
||||
if (match === null) {
|
||||
if (line.trim() !== "") unparsedLines.push(line.trim());
|
||||
continue;
|
||||
}
|
||||
services.push({
|
||||
name: match[1]!,
|
||||
interface: match[2] === "" ? null : match[2]!,
|
||||
});
|
||||
}
|
||||
return { services, unparsedLines };
|
||||
};
|
||||
|
||||
const SIZE_PAIR = /^Physical size:\s+(\d+)x(\d+)$/u;
|
||||
const SIZE_OVERRIDE = /^Override size:\s+(\d+)x(\d+)$/u;
|
||||
const DENSITY_PHYSICAL = /^Physical density:\s+(\d+)$/u;
|
||||
const DENSITY_OVERRIDE = /^Override density:\s+(\d+)$/u;
|
||||
|
||||
/** Parse `wm size` output into physical and optional override sizes. */
|
||||
export const parseWmSizeOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
physical: { readonly width: number; readonly height: number } | null;
|
||||
override: { readonly width: number; readonly height: number } | null;
|
||||
} => {
|
||||
let physical = null;
|
||||
let override = null;
|
||||
for (const line of stdout.split(/\r?\n/u)) {
|
||||
const trimmed = line.trim();
|
||||
const physicalMatch = SIZE_PAIR.exec(trimmed);
|
||||
if (physicalMatch !== null)
|
||||
physical = {
|
||||
width: Number(physicalMatch[1]!),
|
||||
height: Number(physicalMatch[2]!),
|
||||
};
|
||||
const overrideMatch = SIZE_OVERRIDE.exec(trimmed);
|
||||
if (overrideMatch !== null)
|
||||
override = {
|
||||
width: Number(overrideMatch[1]!),
|
||||
height: Number(overrideMatch[2]!),
|
||||
};
|
||||
}
|
||||
return { physical, override };
|
||||
};
|
||||
|
||||
/** Parse `wm density` output. Older builds print a bare number. */
|
||||
export const parseWmDensityOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
physical: number | null;
|
||||
override: number | null;
|
||||
} => {
|
||||
let physical = null;
|
||||
let override = null;
|
||||
for (const line of stdout.split(/\r?\n/u)) {
|
||||
const trimmed = line.trim();
|
||||
const physicalMatch = DENSITY_PHYSICAL.exec(trimmed);
|
||||
if (physicalMatch !== null) physical = Number(physicalMatch[1]!);
|
||||
const overrideMatch = DENSITY_OVERRIDE.exec(trimmed);
|
||||
if (overrideMatch !== null) override = Number(overrideMatch[1]!);
|
||||
}
|
||||
return { physical, override };
|
||||
};
|
||||
|
||||
/** Parse the focus declarations from `dumpsys window windows`. */
|
||||
export const parseWindowFocusOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
focusedWindow: string | null;
|
||||
focusedApp: string | null;
|
||||
} => {
|
||||
let focusedWindow = null;
|
||||
let focusedApp = null;
|
||||
for (const line of stdout.split(/\r?\n/u)) {
|
||||
const trimmed = line.trim();
|
||||
if (focusedWindow === null && trimmed.startsWith("mCurrentFocus="))
|
||||
focusedWindow = trimmed.slice("mCurrentFocus=".length).trim();
|
||||
if (focusedApp === null && trimmed.startsWith("mFocusedApp="))
|
||||
focusedApp = trimmed.slice("mFocusedApp=".length).trim();
|
||||
}
|
||||
return { focusedWindow, focusedApp };
|
||||
};
|
||||
|
||||
export interface AdbPackageDetails {
|
||||
readonly versionName: string | null;
|
||||
readonly versionCode: number | null;
|
||||
readonly firstInstallTime: string | null;
|
||||
readonly lastUpdateTime: string | null;
|
||||
readonly installerPackageName: string | null;
|
||||
readonly userId: number | null;
|
||||
readonly pkgFlags: string | null;
|
||||
readonly requestedPermissions: number | null;
|
||||
}
|
||||
|
||||
const DETAIL_LINE = /^\s+([A-Za-z][A-Za-z0-9_]*)=(.*)$/u;
|
||||
|
||||
/**
|
||||
* Project `dumpsys package PACKAGE` output. Only the listed fields are
|
||||
* extracted; the input is version-dependent and everything else is ignored
|
||||
* by design rather than guessed.
|
||||
*/
|
||||
export const parseDumpsysPackageOutput = (
|
||||
stdout: string,
|
||||
): AdbPackageDetails => {
|
||||
const details: {
|
||||
versionName: string | null;
|
||||
versionCode: number | null;
|
||||
firstInstallTime: string | null;
|
||||
lastUpdateTime: string | null;
|
||||
installerPackageName: string | null;
|
||||
userId: number | null;
|
||||
pkgFlags: string | null;
|
||||
} = {
|
||||
versionName: null,
|
||||
versionCode: null,
|
||||
firstInstallTime: null,
|
||||
lastUpdateTime: null,
|
||||
installerPackageName: null,
|
||||
userId: null,
|
||||
pkgFlags: null,
|
||||
};
|
||||
let inPermissions = false;
|
||||
let permissions = 0;
|
||||
for (const line of stdout.split(/\r?\n/u)) {
|
||||
if (line.trim().startsWith("requested permissions:")) {
|
||||
inPermissions = true;
|
||||
continue;
|
||||
}
|
||||
if (inPermissions && /^\s{2,}[A-Za-z0-9._]+$/.test(line)) {
|
||||
permissions += 1;
|
||||
continue;
|
||||
}
|
||||
inPermissions = false;
|
||||
const match = DETAIL_LINE.exec(line);
|
||||
if (match === null) continue;
|
||||
const key = match[1]!;
|
||||
const value = match[2]!.trim();
|
||||
if (key === "versionName" && details.versionName === null)
|
||||
details.versionName = value === "" ? null : value;
|
||||
else if (key === "versionCode" && details.versionCode === null) {
|
||||
const parsed = /^(\d+)/u.exec(value);
|
||||
if (parsed !== null) details.versionCode = Number(parsed[1]!);
|
||||
} else if (key === "firstInstallTime" && details.firstInstallTime === null)
|
||||
details.firstInstallTime = value === "" ? null : value;
|
||||
else if (key === "lastUpdateTime" && details.lastUpdateTime === null)
|
||||
details.lastUpdateTime = value === "" ? null : value;
|
||||
else if (
|
||||
key === "installerPackageName" &&
|
||||
details.installerPackageName === null
|
||||
)
|
||||
details.installerPackageName = value === "" ? null : value;
|
||||
else if (key === "userId" && details.userId === null) {
|
||||
const parsed = /^(\d+)/u.exec(value);
|
||||
if (parsed !== null) details.userId = Number(parsed[1]!);
|
||||
} else if (key === "pkgFlags" && details.pkgFlags === null)
|
||||
details.pkgFlags = value === "" ? null : value;
|
||||
}
|
||||
return { ...details, requestedPermissions: permissions };
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `settings get` output. Android prints the literal string `null` for
|
||||
* absent keys; that is reported as a device-side null observation.
|
||||
*/
|
||||
export const parseSettingsGetOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
value: string | null;
|
||||
deviceReportedNull: boolean;
|
||||
} => {
|
||||
const trimmed = stdout.replace(/\r?\n$/u, "");
|
||||
if (trimmed === "null") return { value: null, deviceReportedNull: true };
|
||||
return { value: trimmed, deviceReportedNull: false };
|
||||
};
|
||||
|
||||
/** Parse the host-side completion line from `adb bugreport`. */
|
||||
export const parseBugreportCopiedPath = (stdout: string): string | null => {
|
||||
const match = /^Bug report copied to (.+)\r?$/mu.exec(stdout.trim());
|
||||
return match === null ? null : match[1]!;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `adb install`/`adb uninstall` output. adb can print `Failure [...]`
|
||||
* with a zero exit code, so the text decides, not the exit status.
|
||||
*/
|
||||
export const parsePackageChangeOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
readonly status: "success" | "failure";
|
||||
readonly reason: string | null;
|
||||
} => {
|
||||
const text = stdout.trim();
|
||||
if (/^Success$/mu.test(text)) return { status: "success", reason: null };
|
||||
const failure = /Failure \[([^\]]+)\]/u.exec(text);
|
||||
return {
|
||||
status: "failure",
|
||||
reason: failure?.[1] ?? (text === "" ? null : text.slice(0, 512)),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `cmd package resolve-activity --brief` output: the component is the
|
||||
* last non-empty line.
|
||||
*/
|
||||
export const parseResolveActivityOutput = (stdout: string): string | null => {
|
||||
const lines = stdout
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line !== "" && !/^No activity found$/iu.test(line));
|
||||
return lines.length === 0 ? null : lines[lines.length - 1]!;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `am start` output. Success prints `Starting: Intent { ... }`;
|
||||
* refusals print lines starting with `Error:` or `Warning:` and activity
|
||||
* classes that do not exist name the component.
|
||||
*/
|
||||
export const parseAmStartOutput = (
|
||||
stdout: string,
|
||||
): {
|
||||
readonly status: "started" | "refused";
|
||||
readonly startedActivity: string | null;
|
||||
readonly reason: string | null;
|
||||
} => {
|
||||
const text = stdout.trim();
|
||||
const starting = /^Starting:\s+Intent\s*\{(.*)\}\s*$/mu.exec(text);
|
||||
if (starting !== null)
|
||||
return {
|
||||
status: "started",
|
||||
startedActivity: starting[1]!.trim(),
|
||||
reason: null,
|
||||
};
|
||||
const error = /^(?:Error|Warning|Exception)(?::|\b)(.*)$/mu.exec(text);
|
||||
return {
|
||||
status: "refused",
|
||||
startedActivity: null,
|
||||
reason:
|
||||
error?.[1]?.trim() ??
|
||||
(text === "" ? "am start returned no activity" : text.slice(0, 512)),
|
||||
};
|
||||
};
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
||||
]);
|
||||
|
||||
/** Read image dimensions from a PNG header, or null for other payloads. */
|
||||
export const parsePngDimensions = (
|
||||
bytes: Uint8Array,
|
||||
): {
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
} => {
|
||||
if (
|
||||
bytes.length < 24 ||
|
||||
!Buffer.from(bytes.subarray(0, 8)).equals(PNG_SIGNATURE)
|
||||
)
|
||||
return { width: null, height: null };
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
return {
|
||||
width: view.getUint32(16),
|
||||
height: view.getUint32(20),
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user