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:
Quentin Limo
2026-10-10 23:01:24 +08:00
committed by GitHub
co-authored by REA Contributor morluto
parent efd81f9776
commit fef6f73064
48 changed files with 6862 additions and 1 deletions
+77
View File
@@ -0,0 +1,77 @@
import { expect, it } from "vitest";
import { createCli } from "../../../src/cli.js";
const serve = async (
argv: readonly string[],
environment: Readonly<Record<string, string | undefined>> = {},
): Promise<{ readonly stdout: string; readonly exitCode: number }> => {
const cli = createCli(environment);
let stdout = "";
let exitCode = 0;
await cli.serve([...argv], {
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
});
return { stdout, exitCode };
};
it.each([
["inspect-adb-client"],
["list-adb-devices"],
["inspect-adb-device"],
["list-adb-packages"],
["pull-adb-package"],
["read-adb-logcat"],
["inspect-adb-package"],
["pull-adb-file"],
["push-adb-file"],
["capture-adb-screen"],
["list-adb-processes"],
["list-adb-directory"],
["list-adb-features"],
["list-adb-services"],
["inspect-adb-display"],
["inspect-adb-window"],
["read-adb-setting"],
["collect-adb-bugreport"],
["resolve-adb-packages"],
["install-adb-package"],
["uninstall-adb-package"],
["start-adb-app"],
["start-adb-activity"],
["stop-adb-app"],
])("%s advertises a schema through the public CLI", async (command) => {
const result = await serve([command, "--schema", "--json"]);
expect(result.exitCode, command).toBe(0);
const schema = JSON.parse(result.stdout) as { args?: unknown };
expect(schema).toBeTruthy();
});
it("reports a missing adb binary with recovery guidance", async () => {
const result = await serve(["inspect-adb-client", "--json"], {
REA_ADB_PATH: "/nonexistent/adb",
});
expect(result.stdout).toContain("capability_unavailable");
expect(result.stdout).toContain("REA_ADB_PATH");
});
it("validates device serials before contacting any device", async () => {
const result = await serve(["inspect-adb-device", "bad serial", "--json"]);
expect(result.stdout).toContain("invalid_input");
});
it("requires the output directory option on pull", async () => {
const result = await serve([
"pull-adb-package",
"emulator-5554",
"com.example",
"--json",
]);
expect(result.exitCode).not.toBe(0);
});
+397
View File
@@ -0,0 +1,397 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import type { AdbDeviceAnalysisPort } from "../../../src/application/adb/AdbDeviceAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const identity = { id: "adb", name: "Android Debug Bridge", version: null };
const clientIdentity = {
binary_path: "/usr/bin/adb",
path_source: "path",
version: "34.0.5-debian",
installed_path: "/usr/bin/adb",
};
const results: Readonly<Record<string, unknown>> = {
inspect_adb_client: {
client: clientIdentity,
contacted_adb_server: false,
},
list_adb_devices: {
client: clientIdentity,
devices: [
{
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",
},
],
may_have_started_adb_server: false,
},
inspect_adb_device: {
client: clientIdentity,
serial: "emulator-5554",
properties: [{ name: "ro.build.version.sdk", value: "34" }],
property_count: 1,
emulator_observed: true,
},
list_adb_packages: {
client: clientIdentity,
serial: "emulator-5554",
scope: "third_party",
packages: [
{
package_name: "com.example",
base_apk_device_path: "/data/app/x/base.apk",
},
],
unparsed_lines: [],
coverage: "complete",
},
pull_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example",
output_directory: "/tmp/rea-pulls",
artifacts: [
{
device_path: "/data/app/x/base.apk",
file_name: "base.apk",
local_path: "/tmp/rea-pulls/com.example/base.apk",
bytes: 2048,
sha256: "a".repeat(64),
role: "base",
role_basis: "file_name",
},
],
failures: [],
coverage: "complete",
},
read_adb_logcat: {
client: clientIdentity,
serial: "emulator-5554",
count: 500,
buffer: "main",
pid: null,
lines: ["08-10 13:00:00.000 I/Tag( 123): message"],
total_bytes: 34,
coverage: "complete",
},
inspect_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example",
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: null,
user_id: 10234,
pkg_flags: "[ HAS_CODE ]",
requested_permissions_count: 2,
coverage: "complete",
},
pull_adb_file: {
client: clientIdentity,
serial: "emulator-5554",
device_path: "/data/local/tmp/notes.txt",
local_path: "/tmp/rea-pulls/notes.txt",
bytes: 10,
sha256: "a".repeat(64),
},
push_adb_file: {
client: clientIdentity,
serial: "emulator-5554",
local_path: "/tmp/payload.bin",
device_path: "/data/local/tmp/payload.bin",
bytes: 12,
sha256: "a".repeat(64),
device_sha256: "a".repeat(64),
overwritten: false,
device_digest_source: "device_sha256sum",
},
capture_adb_screen: {
client: clientIdentity,
serial: "emulator-5554",
local_path: "/tmp/rea-captures/screen.png",
bytes: 8192,
sha256: "a".repeat(64),
width: 1080,
height: 2340,
},
list_adb_processes: {
client: clientIdentity,
serial: "emulator-5554",
columns: "USER PID PPID VSZ RSS WCHAN ADDR S NAME",
processes: [
{
user: "u0_a1",
pid: 1234,
ppid: 567,
rss: 7890,
state: "S",
name: "com.example.app",
},
],
unparsed_lines: [],
coverage: "complete",
},
list_adb_directory: {
client: clientIdentity,
serial: "emulator-5554",
device_path: "/data/local/tmp",
entries: [
{
name: "notes.txt",
kind: "file",
permissions: "-rw-rw-rw-",
owner: "shell",
group: "shell",
bytes: 10,
date: "2026-01-01 10:00",
link_target: null,
},
],
unparsed_lines: [],
coverage: "complete",
},
list_adb_features: {
client: clientIdentity,
serial: "emulator-5554",
features: [{ name: "android.hardware.camera", version: null }],
unparsed_lines: [],
coverage: "complete",
},
list_adb_services: {
client: clientIdentity,
serial: "emulator-5554",
services: [
{ name: "package", interface: "android.content.pm.IPackageManager" },
],
unparsed_lines: [],
coverage: "complete",
},
inspect_adb_display: {
client: clientIdentity,
serial: "emulator-5554",
physical_size: { width: 1080, height: 2340 },
override_size: null,
physical_density: 420,
override_density: null,
},
inspect_adb_window: {
client: clientIdentity,
serial: "emulator-5554",
focused_window: "Window{abcdef u0 com.example.app/Main}",
focused_app: null,
observed_lines: ["Window{abcdef u0 com.example.app/Main}"],
},
read_adb_setting: {
client: clientIdentity,
serial: "emulator-5554",
namespace: "secure",
key: "adb_enabled",
value: "1",
device_reported_null: false,
},
collect_adb_bugreport: {
client: clientIdentity,
serial: "emulator-5554",
local_path: "/tmp/rea-bugreports/bugreport.zip",
bytes: 1024,
sha256: "a".repeat(64),
adb_reported_path: "/tmp/rea-bugreports/bugreport.zip",
},
resolve_adb_packages: {
client: clientIdentity,
serial: "emulator-5554",
query: "whatsapp",
matches: [
{
package_name: "com.whatsapp",
base_apk_device_path: "/data/app/x/base.apk",
},
],
exact_match: true,
coverage: "complete",
},
install_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
apk_path: "/tmp/app.apk",
bytes: 2048,
sha256: "a".repeat(64),
replaced: false,
},
uninstall_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.whatsapp",
},
start_adb_app: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example.app",
component: "com.example.app/.Main",
started_activity:
"act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.app/.Main",
},
start_adb_activity: {
client: clientIdentity,
serial: "emulator-5554",
action: "android.intent.action.VIEW",
data_uri: "https://example.com/",
component: null,
extras: [],
started_activity: "act=android.intent.action.VIEW dat=https://example.com/",
},
stop_adb_app: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example.app",
},
};
it("advertises exact valid ADB schemas and records inline evidence through MCP", async () => {
const provider: AdbDeviceAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
return ok(createAnalysisExecution(results[request.operation], identity));
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ adbDeviceAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "adb-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
const names = tools.map((tool) => tool.name);
const operationNames = [
"inspect_adb_client",
"list_adb_devices",
"inspect_adb_device",
"list_adb_packages",
"pull_adb_package",
"read_adb_logcat",
"inspect_adb_package",
"pull_adb_file",
"push_adb_file",
"capture_adb_screen",
"list_adb_processes",
"list_adb_directory",
"list_adb_features",
"list_adb_services",
"inspect_adb_display",
"inspect_adb_window",
"read_adb_setting",
"collect_adb_bugreport",
"resolve_adb_packages",
"install_adb_package",
"uninstall_adb_package",
"start_adb_app",
"start_adb_activity",
"stop_adb_app",
] as const;
for (const name of operationNames) expect(names, name).toContain(name);
const ajv = new Ajv2020({ strict: false, allErrors: true });
for (const name of operationNames) {
const contract = toolContract(name);
const listed = tools.find((tool) => tool.name === name);
expect(listed, name).toBeTruthy();
if (listed?.inputSchema === undefined) continue;
// The server may present a compacted form of the contract schema; what
// must hold is that the advertised schema compiles and accepts the
// contract's own examples, and rejects unknown input.
const validate = ajv.compile(
JSON.parse(JSON.stringify(listed.inputSchema)),
);
for (const example of contract.examples)
expect(validate(example.input), `${name} example`).toBe(true);
expect(validate({ unknown_argument: true }), `${name} rejects`).toBe(false);
}
const pulled = await client.callTool({
name: "pull_adb_package",
arguments: {
serial: "emulator-5554",
package: "com.example",
output_directory: "/tmp/rea-pulls",
},
});
expect(pulled.isError).not.toBe(true);
const text = (pulled.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.provider.id).toBe("adb");
expect(evidence.operation).toBe("pull_adb_package");
expect(evidence.normalized_result).toMatchObject({
artifacts: [{ file_name: "base.apk", role: "base", bytes: 2048 }],
coverage: "complete",
});
});
it("rejects invalid tool input before reaching the provider", async () => {
const provider: AdbDeviceAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute() {
throw new Error("must not execute");
},
};
const server = createServer(
{
kind: "session",
session: createTestBinarySession(() => {
throw new Error("must not start");
}),
},
{ adbDeviceAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "adb-boundary-invalid", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const rejected = await client.callTool({
name: "inspect_adb_device",
arguments: { serial: "bad serial" },
});
expect(rejected.isError).toBe(true);
const text = (rejected.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
expect(text).toContain("Invalid arguments for tool inspect_adb_device");
});