Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(verifiers): report adb operation and cleanup failures together

morluto139d86b05c4c
diff --git a/scripts/verify-adb.mjs b/scripts/verify-adb.mjs
index 27c9cd5bf..cd162f00a 100644
--- a/scripts/verify-adb.mjs
+++ b/scripts/verify-adb.mjs
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { AdbDeviceAnalysisService } from "../dist/application/adb/AdbDeviceAnalysisService.js";
import { createAdbDeviceAnalysisProvider } from "../dist/composition/adb.js";
+import { closeVerifierResources } from "./lib/verifier-cleanup.mjs";
const options = parseArguments(process.argv.slice(2));
if (options.help) {
@@ -39,343 +40,365 @@ const run = async (operation, input) => {
return result.value.normalized_result;
};
-const client = await run("inspect_adb_client", {});
-if (client !== null) {
- check(
- "adb client reports a version",
- typeof client.client.version === "string" && client.client.version !== "",
- `binary=${client.client.binary_path} version=${client.client.version}`,
- );
-}
-
-const listing = await run("list_adb_devices", {});
-let serial = options.serial ?? null;
-if (listing !== null) {
- check(
- "device listing parsed",
- Array.isArray(listing.devices),
- `${listing.devices.length} device(s)`,
- );
- const usable = listing.devices.filter((device) => device.state === "device");
- if (serial === null && usable.length > 0) serial = usable[0].serial;
- if (serial === null) {
- process.stdout.write(
- "[FAIL] no usable device is attached; start an emulator or connect a phone\n",
- );
- failures += 1;
- } else {
- const selected = listing.devices.find((device) => device.serial === serial);
+let primaryFailure;
+try {
+ const client = await run("inspect_adb_client", {});
+ if (client !== null) {
check(
- "selected device present with a kind inference",
- selected !== undefined &&
- ["emulator", "physical", "unknown"].includes(selected.kind),
- `serial=${serial} kind=${selected?.kind} basis=${selected?.kind_basis}`,
+ "adb client reports a version",
+ typeof client.client.version === "string" && client.client.version !== "",
+ `binary=${client.client.binary_path} version=${client.client.version}`,
);
}
-}
-if (serial !== null) {
- const device = await run("inspect_adb_device", { serial });
- if (device !== null) {
+ const listing = await run("list_adb_devices", {});
+ let serial = options.serial ?? null;
+ if (listing !== null) {
check(
- "device build identity projected",
- device.properties.some(
- (property) => property.name === "ro.build.version.sdk",
- ),
- `sdk=${
- device.properties.find((p) => p.name === "ro.build.version.sdk")?.value
- } emulator_observed=${String(device.emulator_observed)}`,
+ "device listing parsed",
+ Array.isArray(listing.devices),
+ `${listing.devices.length} device(s)`,
);
- }
-
- // Observation tools: processes, window, display, settings, logcat.
- const processes = await run("list_adb_processes", { serial });
- if (processes !== null) {
- check(
- "process listing is non-empty with a header",
- processes.processes.length > 0 && typeof processes.columns === "string",
- `${processes.processes.length} process(es)`,
+ const usable = listing.devices.filter(
+ (device) => device.state === "device",
);
+ if (serial === null && usable.length > 0) serial = usable[0].serial;
+ if (serial === null) {
+ process.stdout.write(
+ "[FAIL] no usable device is attached; start an emulator or connect a phone\n",
+ );
+ failures += 1;
+ } else {
+ const selected = listing.devices.find(
+ (device) => device.serial === serial,
+ );
+ check(
+ "selected device present with a kind inference",
+ selected !== undefined &&
+ ["emulator", "physical", "unknown"].includes(selected.kind),
+ `serial=${serial} kind=${selected?.kind} basis=${selected?.kind_basis}`,
+ );
+ }
}
- const window = await run("inspect_adb_window", { serial });
- if (window !== null)
- check(
- "window focus observation completed",
- typeof window.focused_window === "string" ||
- window.focused_window === null,
- `focused_window=${String(window.focused_window).slice(0, 60)} (null is legitimate on headless devices)`,
- );
- const display = await run("inspect_adb_display", { serial });
- if (display !== null)
- check(
- "display reports a physical size",
- display.physical_size !== null &&
- display.physical_size.width > 0 &&
- display.physical_size.height > 0,
- `${display.physical_size?.width}x${display.physical_size?.height} @${String(display.physical_density)}`,
- );
- const setting = await run("read_adb_setting", {
- serial,
- namespace: "global",
- key: "adb_enabled",
- });
- if (setting !== null)
- check(
- "settings read returns the device's own value",
- setting.value === "1",
- `adb_enabled=${String(setting.value)}`,
- );
- const logcat = await run("read_adb_logcat", {
- serial,
- count: 20,
- buffer: "main",
- });
- if (logcat !== null)
- check(
- "logcat dump returns bounded lines",
- logcat.lines.length <= 20,
- `${logcat.lines.length} line(s), coverage=${logcat.coverage}`,
- );
- const features = await run("list_adb_features", { serial });
- if (features !== null)
- check(
- "feature inventory is non-empty",
- features.coverage === "complete" && features.features.length > 0,
- `${features.features.length} feature(s)`,
- );
- const services = await run("list_adb_services", { serial });
- if (services !== null)
- check(
- "service inventory is non-empty",
- services.coverage === "complete" && services.services.length > 0,
- `${services.services.length} service(s)`,
- );
- const directory = await run("list_adb_directory", {
- serial,
- device_path: "/data/local/tmp",
- });
- if (directory !== null)
- check(
- "directory listing completed",
- directory.coverage === "complete",
- `${directory.entries.length} entr(ies)`,
- );
- const packages = await run("list_adb_packages", {
- serial,
- scope: "third_party",
- });
- let pullCandidate = options.pull ?? null;
- if (packages !== null) {
- // A third-party scope may legitimately be empty (clean emulator images);
- // completeness is about unparsed lines, not row count.
- check(
- "third-party package listing reports complete coverage",
- packages.coverage === "complete",
- `${packages.packages.length} package(s)`,
- );
- const allPackages = await run("list_adb_packages", {
+ if (serial !== null) {
+ const device = await run("inspect_adb_device", { serial });
+ if (device !== null) {
+ check(
+ "device build identity projected",
+ device.properties.some(
+ (property) => property.name === "ro.build.version.sdk",
+ ),
+ `sdk=${
+ device.properties.find((p) => p.name === "ro.build.version.sdk")
+ ?.value
+ } emulator_observed=${String(device.emulator_observed)}`,
+ );
+ }
+
+ // Observation tools: processes, window, display, settings, logcat.
+ const processes = await run("list_adb_processes", { serial });
+ if (processes !== null) {
+ check(
+ "process listing is non-empty with a header",
+ processes.processes.length > 0 && typeof processes.columns === "string",
+ `${processes.processes.length} process(es)`,
+ );
+ }
+ const window = await run("inspect_adb_window", { serial });
+ if (window !== null)
+ check(
+ "window focus observation completed",
+ typeof window.focused_window === "string" ||
+ window.focused_window === null,
+ `focused_window=${String(window.focused_window).slice(0, 60)} (null is legitimate on headless devices)`,
+ );
+ const display = await run("inspect_adb_display", { serial });
+ if (display !== null)
+ check(
+ "display reports a physical size",
+ display.physical_size !== null &&
+ display.physical_size.width > 0 &&
+ display.physical_size.height > 0,
+ `${display.physical_size?.width}x${display.physical_size?.height} @${String(display.physical_density)}`,
+ );
+ const setting = await run("read_adb_setting", {
serial,
- scope: "all",
+ namespace: "global",
+ key: "adb_enabled",
});
- if (allPackages !== null) {
+ if (setting !== null)
check(
- "full package inventory is non-empty",
- allPackages.coverage === "complete" && allPackages.packages.length > 0,
- `${allPackages.packages.length} package(s)`,
+ "settings read returns the device's own value",
+ setting.value === "1",
+ `adb_enabled=${String(setting.value)}`,
+ );
+ const logcat = await run("read_adb_logcat", {
+ serial,
+ count: 20,
+ buffer: "main",
+ });
+ if (logcat !== null)
+ check(
+ "logcat dump returns bounded lines",
+ logcat.lines.length <= 20,
+ `${logcat.lines.length} line(s), coverage=${logcat.coverage}`,
+ );
+ const features = await run("list_adb_features", { serial });
+ if (features !== null)
+ check(
+ "feature inventory is non-empty",
+ features.coverage === "complete" && features.features.length > 0,
+ `${features.features.length} feature(s)`,
+ );
+ const services = await run("list_adb_services", { serial });
+ if (services !== null)
+ check(
+ "service inventory is non-empty",
+ services.coverage === "complete" && services.services.length > 0,
+ `${services.services.length} service(s)`,
+ );
+ const directory = await run("list_adb_directory", {
+ serial,
+ device_path: "/data/local/tmp",
+ });
+ if (directory !== null)
+ check(
+ "directory listing completed",
+ directory.coverage === "complete",
+ `${directory.entries.length} entr(ies)`,
);
- }
- if (pullCandidate === null && packages.packages.length > 0)
- pullCandidate = packages.packages[0].package_name;
- }
- if (pullCandidate !== null) {
- const directory = await mkdtemp(join(tmpdir(), "rea-adb-verify-"));
- try {
- const pull = await run("pull_adb_package", {
+ const packages = await run("list_adb_packages", {
+ serial,
+ scope: "third_party",
+ });
+ let pullCandidate = options.pull ?? null;
+ if (packages !== null) {
+ // A third-party scope may legitimately be empty (clean emulator images);
+ // completeness is about unparsed lines, not row count.
+ check(
+ "third-party package listing reports complete coverage",
+ packages.coverage === "complete",
+ `${packages.packages.length} package(s)`,
+ );
+ const allPackages = await run("list_adb_packages", {
serial,
- package: pullCandidate,
- output_directory: directory,
+ scope: "all",
});
- if (pull !== null) {
- // Installed /data/app packages name their APKs base.apk and
- // split_*.apk; system packages keep arbitrary names, so the lane
- // checks a non-empty artifact set and verifies each file on disk.
+ if (allPackages !== null) {
check(
- "pull returned a non-empty artifact set",
- pull.artifacts.length > 0,
- `${pull.artifacts.length} artifact(s), coverage=${pull.coverage}, roles=${pull.artifacts.map((a) => a.role).join(",")}`,
+ "full package inventory is non-empty",
+ allPackages.coverage === "complete" &&
+ allPackages.packages.length > 0,
+ `${allPackages.packages.length} package(s)`,
);
- for (const artifact of pull.artifacts) {
- const bytes = await stat(artifact.local_path).then(
- (info) => info.size,
- );
- const digest = createHash("sha256")
- .update(await readFile(artifact.local_path))
- .digest("hex");
+ }
+ if (pullCandidate === null && packages.packages.length > 0)
+ pullCandidate = packages.packages[0].package_name;
+ }
+
+ if (pullCandidate !== null) {
+ const directory = await mkdtemp(join(tmpdir(), "rea-adb-verify-"));
+ try {
+ const pull = await run("pull_adb_package", {
+ serial,
+ package: pullCandidate,
+ output_directory: directory,
+ });
+ if (pull !== null) {
+ // Installed /data/app packages name their APKs base.apk and
+ // split_*.apk; system packages keep arbitrary names, so the lane
+ // checks a non-empty artifact set and verifies each file on disk.
check(
- `artifact digest matches on disk: ${artifact.file_name}`,
- bytes === artifact.bytes && digest === artifact.sha256,
- `${bytes} bytes`,
+ "pull returned a non-empty artifact set",
+ pull.artifacts.length > 0,
+ `${pull.artifacts.length} artifact(s), coverage=${pull.coverage}, roles=${pull.artifacts.map((a) => a.role).join(",")}`,
);
+ for (const artifact of pull.artifacts) {
+ const bytes = await stat(artifact.local_path).then(
+ (info) => info.size,
+ );
+ const digest = createHash("sha256")
+ .update(await readFile(artifact.local_path))
+ .digest("hex");
+ check(
+ `artifact digest matches on disk: ${artifact.file_name}`,
+ bytes === artifact.bytes && digest === artifact.sha256,
+ `${bytes} bytes`,
+ );
+ }
}
+ } finally {
+ await rm(directory, { recursive: true, force: true });
}
- } finally {
- await rm(directory, { recursive: true, force: true });
}
- }
- // File transfer: push one lane-owned file, verify both digests, pull it
- // back, then clean up the device copy through the same fixed argv surface.
- const transferRoot = await mkdtemp(join(tmpdir(), "rea-adb-transfer-"));
- try {
- const payload = join(transferRoot, "rea-verify.txt");
- const payloadBytes = "rea adb transfer verification\n";
- await import("node:fs/promises").then((fs) =>
- fs.writeFile(payload, payloadBytes),
- );
- const deviceTarget = `/data/local/tmp/rea-verify-${Date.now()}.txt`;
- const pushed = await run("push_adb_file", {
- serial,
- local_path: payload,
- device_path: deviceTarget,
- overwrite: false,
- });
- if (pushed !== null) {
- check(
- "push reports matching device-side digest",
- pushed.device_digest_source === "device_sha256sum" &&
- pushed.device_sha256 === pushed.sha256,
- `${pushed.bytes} bytes`,
+ // File transfer: push one lane-owned file, verify both digests, pull it
+ // back, then clean up the device copy through the same fixed argv surface.
+ const transferRoot = await mkdtemp(join(tmpdir(), "rea-adb-transfer-"));
+ try {
+ const payload = join(transferRoot, "rea-verify.txt");
+ const payloadBytes = "rea adb transfer verification\n";
+ await import("node:fs/promises").then((fs) =>
+ fs.writeFile(payload, payloadBytes),
);
- const pulled = await run("pull_adb_file", {
+ const deviceTarget = `/data/local/tmp/rea-verify-${Date.now()}.txt`;
+ const pushed = await run("push_adb_file", {
serial,
+ local_path: payload,
device_path: deviceTarget,
- output_directory: transferRoot,
- });
- if (pulled !== null)
- check(
- "pulled file digest matches the pushed digest",
- pulled.sha256 === pushed.sha256,
- `${pulled.bytes} bytes`,
- );
- }
- const screenRoot = await mkdtemp(join(tmpdir(), "rea-adb-screen-"));
- try {
- const screen = await run("capture_adb_screen", {
- serial,
- output_directory: screenRoot,
- });
- if (screen !== null)
- check(
- "screen capture is a sized PNG",
- screen.width !== null && screen.height !== null && screen.bytes > 0,
- `${screen.width}x${screen.height}, ${screen.bytes} bytes`,
- );
- } finally {
- await rm(screenRoot, { recursive: true, force: true });
- }
- if (options.pull !== null) {
- const details = await run("inspect_adb_package", {
- serial,
- package: options.pull,
- });
- if (details !== null)
- check(
- "dumpsys package projection completed",
- details.coverage === "complete",
- `versionCode=${String(details.version_code)}`,
- );
- }
- if (options.installApk !== null && options.installApk !== undefined) {
- const probePackage = "com.rea.adb.probe";
- const installedProbe = await run("install_adb_package", {
- serial,
- apk_path: options.installApk,
- replace: false,
+ overwrite: false,
});
- if (installedProbe !== null) {
+ if (pushed !== null) {
check(
- "install reports the APK digest",
- typeof installedProbe.sha256 === "string" &&
- installedProbe.sha256.length === 64,
- `${installedProbe.bytes} bytes`,
+ "push reports matching device-side digest",
+ pushed.device_digest_source === "device_sha256sum" &&
+ pushed.device_sha256 === pushed.sha256,
+ `${pushed.bytes} bytes`,
);
- const resolved = await run("resolve_adb_packages", {
+ const pulled = await run("pull_adb_file", {
serial,
- query: "rea.adb.probe",
+ device_path: deviceTarget,
+ output_directory: transferRoot,
});
- if (resolved !== null)
- check(
- "resolve finds the installed probe uniquely",
- resolved.matches.length === 1 &&
- resolved.matches[0]?.package_name === probePackage,
- `${resolved.matches.length} match(es)`,
- );
- const started = await run("start_adb_app", {
- serial,
- package: probePackage,
- });
- if (started !== null)
- check(
- "app start resolves and launches the launcher activity",
- typeof started.component === "string" &&
- started.component.startsWith(probePackage),
- String(started.component),
- );
- const observedProcesses = await run("list_adb_processes", { serial });
- if (observedProcesses !== null)
+ if (pulled !== null)
check(
- "started app appears in the process listing",
- observedProcesses.processes.some(
- (process) => process.name === probePackage,
- ),
+ "pulled file digest matches the pushed digest",
+ pulled.sha256 === pushed.sha256,
+ `${pulled.bytes} bytes`,
);
- const stopped = await run("stop_adb_app", {
+ }
+ const screenRoot = await mkdtemp(join(tmpdir(), "rea-adb-screen-"));
+ try {
+ const screen = await run("capture_adb_screen", {
serial,
- package: probePackage,
+ output_directory: screenRoot,
});
- if (stopped !== null)
+ if (screen !== null)
check(
- "force-stop completes the dynamic-analysis run",
- stopped.package_name === probePackage,
+ "screen capture is a sized PNG",
+ screen.width !== null && screen.height !== null && screen.bytes > 0,
+ `${screen.width}x${screen.height}, ${screen.bytes} bytes`,
);
- const removed = await run("uninstall_adb_package", {
+ } finally {
+ await rm(screenRoot, { recursive: true, force: true });
+ }
+ if (options.pull !== null) {
+ const details = await run("inspect_adb_package", {
serial,
- package: probePackage,
+ package: options.pull,
});
- if (removed !== null)
+ if (details !== null)
check(
- "uninstall completes the lifecycle",
- removed.package_name === probePackage,
+ "dumpsys package projection completed",
+ details.coverage === "complete",
+ `versionCode=${String(details.version_code)}`,
);
- const afterRemoval = await run("resolve_adb_packages", {
+ }
+ if (options.installApk !== null && options.installApk !== undefined) {
+ const probePackage = "com.rea.adb.probe";
+ const installedProbe = await run("install_adb_package", {
serial,
- query: "rea.adb.probe",
+ apk_path: options.installApk,
+ replace: false,
});
- if (afterRemoval !== null)
+ if (installedProbe !== null) {
check(
- "resolve reports zero matches after removal",
- afterRemoval.matches.length === 0,
+ "install reports the APK digest",
+ typeof installedProbe.sha256 === "string" &&
+ installedProbe.sha256.length === 64,
+ `${installedProbe.bytes} bytes`,
);
+ const resolved = await run("resolve_adb_packages", {
+ serial,
+ query: "rea.adb.probe",
+ });
+ if (resolved !== null)
+ check(
+ "resolve finds the installed probe uniquely",
+ resolved.matches.length === 1 &&
+ resolved.matches[0]?.package_name === probePackage,
+ `${resolved.matches.length} match(es)`,
+ );
+ const started = await run("start_adb_app", {
+ serial,
+ package: probePackage,
+ });
+ if (started !== null)
+ check(
+ "app start resolves and launches the launcher activity",
+ typeof started.component === "string" &&
+ started.component.startsWith(probePackage),
+ String(started.component),
+ );
+ const observedProcesses = await run("list_adb_processes", { serial });
+ if (observedProcesses !== null)
+ check(
+ "started app appears in the process listing",
+ observedProcesses.processes.some(
+ (process) => process.name === probePackage,
+ ),
+ );
+ const stopped = await run("stop_adb_app", {
+ serial,
+ package: probePackage,
+ });
+ if (stopped !== null)
+ check(
+ "force-stop completes the dynamic-analysis run",
+ stopped.package_name === probePackage,
+ );
+ const removed = await run("uninstall_adb_package", {
+ serial,
+ package: probePackage,
+ });
+ if (removed !== null)
+ check(
+ "uninstall completes the lifecycle",
+ removed.package_name === probePackage,
+ );
+ const afterRemoval = await run("resolve_adb_packages", {
+ serial,
+ query: "rea.adb.probe",
+ });
+ if (afterRemoval !== null)
+ check(
+ "resolve reports zero matches after removal",
+ afterRemoval.matches.length === 0,
+ );
+ }
}
+ } finally {
+ await rm(transferRoot, { recursive: true, force: true });
}
- } finally {
- await rm(transferRoot, { recursive: true, force: true });
}
+} catch (cause) {
+ primaryFailure = cause;
}
+let cleanupFailure;
try {
- await provider.close();
-} catch {
- // The provider owns nothing long-lived; closing is best-effort.
+ await closeVerifierResources([() => provider.close()], primaryFailure);
+} catch (cause) {
+ cleanupFailure = cause;
}
-if (failures > 0) {
+if (primaryFailure !== undefined || cleanupFailure !== undefined) {
+ const causes =
+ cleanupFailure instanceof AggregateError
+ ? cleanupFailure.errors
+ : [cleanupFailure ?? primaryFailure];
+ process.stderr.write(
+ `ADB device verification failed: ${causes.map((cause) => (cause instanceof Error ? cause.message : String(cause))).join("; ")}\n`,
+ );
+ process.exitCode = 1;
+} else if (failures > 0) {
process.stdout.write(`\n${failures} check(s) failed\n`);
- process.exit(1);
+ process.exitCode = 1;
+} else {
+ process.stdout.write("\nall adb device checks passed\n");
}
-process.stdout.write("\nall adb device checks passed\n");
function parseArguments(argv) {
const parsed = { help: false, serial: null, pull: null, installApk: null };
diff --git a/tests/boundary/process/adbVerifierCleanup.test.ts b/tests/boundary/process/adbVerifierCleanup.test.ts
new file mode 100644
index 000000000..b22e44251
--- /dev/null
+++ b/tests/boundary/process/adbVerifierCleanup.test.ts
@@ -0,0 +1,206 @@
+import { spawn } from "node:child_process";
+import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
+import { join, resolve } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+const providerModule = `
+import { writeFile } from "node:fs/promises";
+
+export function createAdbDeviceAnalysisProvider() {
+ return {
+ async close() {
+ await writeFile(process.env.REA_ADB_TEST_CLOSE_MARKER, "closed");
+ if (process.env.REA_ADB_TEST_CLOSE_FAILURE === "1")
+ throw new Error("fake provider close failed");
+ },
+ };
+}
+`;
+
+const serviceModule = `
+import { createHash } from "node:crypto";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+const transferBytes = Buffer.from("rea adb transfer verification\\n");
+const transferDigest = createHash("sha256").update(transferBytes).digest("hex");
+const packageBytes = Buffer.from("fake package artifact");
+const packageDigest = createHash("sha256").update(packageBytes).digest("hex");
+const packages = [{
+ package_name: "com.example",
+ base_apk_device_path: "/data/app/example/base.apk",
+}];
+
+export class AdbDeviceAnalysisService {
+ async execute(operation, input) {
+ if (process.env.REA_ADB_TEST_THROW === operation)
+ throw new Error("fake operation threw");
+
+ if (operation === "pull_adb_package") {
+ await mkdir(input.output_directory, { recursive: true });
+ const local_path = join(input.output_directory, "base.apk");
+ await writeFile(local_path, packageBytes);
+ return {
+ ok: true,
+ value: {
+ normalized_result: {
+ artifacts: [{
+ local_path,
+ file_name: "base.apk",
+ bytes: packageBytes.length,
+ sha256: packageDigest,
+ role: "base",
+ }],
+ coverage: "complete",
+ },
+ },
+ };
+ }
+
+ const results = {
+ inspect_adb_client: {
+ client: { version: "test", binary_path: "/fake/adb" },
+ },
+ list_adb_devices: {
+ devices: [{ serial: "test-device", state: "device", kind: "emulator" }],
+ },
+ inspect_adb_device: {
+ properties: [{ name: "ro.build.version.sdk", value: "35" }],
+ emulator_observed: true,
+ },
+ list_adb_processes: { processes: [{ name: "system" }], columns: "PID NAME" },
+ inspect_adb_window: { focused_window: null },
+ inspect_adb_display: {
+ physical_size: { width: 1, height: 1 },
+ physical_density: 1,
+ },
+ read_adb_setting: { value: "1" },
+ read_adb_logcat: { lines: [], coverage: "complete" },
+ list_adb_features: { features: ["test-feature"], coverage: "complete" },
+ list_adb_services: { services: ["test-service"], coverage: "complete" },
+ list_adb_directory: { entries: [], coverage: "complete" },
+ list_adb_packages: { packages, coverage: "complete" },
+ push_adb_file: {
+ bytes: transferBytes.length,
+ sha256: transferDigest,
+ device_digest_source: "device_sha256sum",
+ device_sha256: transferDigest,
+ },
+ pull_adb_file: { bytes: transferBytes.length, sha256: transferDigest },
+ capture_adb_screen: { width: 1, height: 1, bytes: 1 },
+ };
+ const normalized_result = results[operation];
+ if (normalized_result === undefined)
+ throw new Error("unexpected fake operation: " + operation);
+ return { ok: true, value: { normalized_result } };
+ }
+}
+`;
+
+async function createVerifierFixture() {
+ const root = await createTestTempDirectory("rea-adb-verifier-cleanup-");
+ const scriptDirectory = join(root, "scripts");
+ const scriptLibDirectory = join(scriptDirectory, "lib");
+ const applicationDirectory = join(root, "dist/application/adb");
+ const compositionDirectory = join(root, "dist/composition");
+ await Promise.all([
+ mkdir(scriptDirectory, { recursive: true }),
+ mkdir(scriptLibDirectory, { recursive: true }),
+ mkdir(applicationDirectory, { recursive: true }),
+ mkdir(compositionDirectory, { recursive: true }),
+ ]);
+ const scriptPath = join(scriptDirectory, "verify-adb.mjs");
+ const closeMarker = join(root, "provider-closed");
+ await Promise.all([
+ copyFile(resolve("scripts/verify-adb.mjs"), scriptPath),
+ copyFile(
+ resolve("scripts/lib/verifier-cleanup.mjs"),
+ join(scriptLibDirectory, "verifier-cleanup.mjs"),
+ ),
+ writeFile(join(root, "package.json"), '{"type":"module"}\n'),
+ writeFile(
+ join(applicationDirectory, "AdbDeviceAnalysisService.js"),
+ serviceModule,
+ ),
+ writeFile(join(compositionDirectory, "adb.js"), providerModule),
+ ]);
+ return { root, scriptPath, closeMarker };
+}
+
+function runVerifier(
+ root: string,
+ scriptPath: string,
+ closeMarker: string,
+ extraEnvironment: Record<string, string> = {},
+) {
+ return new Promise<{ code: number | null; stdout: string; stderr: string }>(
+ (resolveResult, reject) => {
+ const child = spawn(process.execPath, [scriptPath], {
+ cwd: root,
+ env: {
+ ...process.env,
+ REA_ADB_TEST_CLOSE_MARKER: closeMarker,
+ ...extraEnvironment,
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => (stdout += chunk.toString()));
+ child.stderr.on("data", (chunk) => (stderr += chunk.toString()));
+ child.once("error", reject);
+ child.once("close", (code) => resolveResult({ code, stdout, stderr }));
+ },
+ );
+}
+
+it("fails verification when provider cleanup fails after successful checks", async () => {
+ const fixture = await createVerifierFixture();
+ const result = await runVerifier(
+ fixture.root,
+ fixture.scriptPath,
+ fixture.closeMarker,
+ { REA_ADB_TEST_CLOSE_FAILURE: "1" },
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(await readFile(fixture.closeMarker, "utf8")).toBe("closed");
+ expect(result.stdout + result.stderr).toContain("fake provider close failed");
+ expect(result.stdout).not.toContain("all adb device checks passed");
+});
+
+it("runs cleanup and retains operation and cleanup failures", async () => {
+ const fixture = await createVerifierFixture();
+ const result = await runVerifier(
+ fixture.root,
+ fixture.scriptPath,
+ fixture.closeMarker,
+ {
+ REA_ADB_TEST_THROW: "inspect_adb_client",
+ REA_ADB_TEST_CLOSE_FAILURE: "1",
+ },
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(await readFile(fixture.closeMarker, "utf8")).toBe("closed");
+ expect(result.stdout + result.stderr).toContain("fake operation threw");
+ expect(result.stdout + result.stderr).toContain("fake provider close failed");
+ expect(result.stdout).not.toContain("all adb device checks passed");
+});
+
+it("reports success after successful verification and provider cleanup", async () => {
+ const fixture = await createVerifierFixture();
+ const result = await runVerifier(
+ fixture.root,
+ fixture.scriptPath,
+ fixture.closeMarker,
+ );
+
+ expect(result.code).toBe(0);
+ expect(await readFile(fixture.closeMarker, "utf8")).toBe("closed");
+ expect(result.stdout).toContain("all adb device checks passed");
+});