feat: add Frida instrumentation support (#1359)

* feat: add Frida instrumentation support

* fix: resolve Frida CI checks

* test: cover Frida contract validation branches

* docs: link Frida instrumentation guide

* fix(frida): handle cancellation cleanup safely

* fix(frida): address PR review findings

* fix(frida): preserve resume and message observations

* fix(ci): use canonical registry for rolldown

* fix(frida): declare foreign code effects

* fix(frida): retain failed startup resources for cleanup retries

Keep failed startup session and spawn handles owned until detach, resume,
and remote lease cleanup complete. Serialize retries and release each
remote reference once. Await CLI provider cleanup while preserving the
primary failure and any completed observations.

Add regressions for retained startup resources, concurrent cleanup,
shared remote leases, and CLI cleanup outcomes.

Validation: 41 focused tests pass on the PR head and its latest-main
integration; serial static and docs checks pass. Real Linux Frida 17.23.2
workflows and the native spawn/controlled-failure cleanup probe pass.

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

---------

Co-authored-by: N0zoM1z0 <1705004398@qq.com>
This commit is contained in:
Daniel Gonçalves Araujo
2026-10-12 22:01:58 +08:00
committed by GitHub
co-authored by N0zoM1z0
parent 0b7145361e
commit 4a4ae9b2b9
34 changed files with 5845 additions and 148 deletions
+6
View File
@@ -22,6 +22,7 @@ import type { JsonValue } from "../domain/jsonValue.js";
import { isMachOFormat } from "../domain/binaryTargetTypes.js";
import type { ProviderAvailability } from "./AnalysisProvider.js";
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import { FRIDA_TOOL_CONTRACTS } from "../contracts/fridaToolContracts.js";
import {
clientRequirementsFor,
NO_CLIENT_FEATURES,
@@ -131,6 +132,9 @@ const ACTIVE_TARGET_KINDS: ReadonlySet<ToolKind> = new Set([
"native-provider",
"artifact-provider",
]);
const FRIDA_OPERATION_NAMES: ReadonlySet<string> = new Set(
FRIDA_TOOL_CONTRACTS.map(({ name }) => name),
);
/** Native contracts defined only for an active Mach-O executable. */
const MACHO_TARGET_OPERATIONS: ReadonlySet<string> = new Set([
@@ -316,6 +320,7 @@ const optionalProviderFailureFor = ({
if (kind === "electron-provider") return failures?.electronObservation;
if (kind === "runtime-provider")
return failures?.javascriptRuntimeObservation;
if (FRIDA_OPERATION_NAMES.has(name)) return failures?.fridaInstrumentation;
return undefined;
};
@@ -533,6 +538,7 @@ const targetAvailability = ({
targetFormat,
targetOpen,
}: AvailabilityContext): Availability | null => {
if (FRIDA_OPERATION_NAMES.has(name)) return null;
if (!targetOpen && ACTIVE_TARGET_KINDS.has(kind))
return {
reason: "target_required",
@@ -22,7 +22,10 @@ export interface OptionalProviderLoadFailure {
export type OptionalProviderLoadFailures = Readonly<
Partial<
Record<keyof OptionalObservationProviders, OptionalProviderLoadFailure>
Record<
keyof OptionalObservationProviders | "fridaInstrumentation",
OptionalProviderLoadFailure
>
>
>;
@@ -0,0 +1,988 @@
import { describe, expect, it } from "vitest";
import type {
Device,
DeviceManager,
FridaMessage,
Process,
Script,
Session,
Signal,
} from "frida";
import { FridaInstrumentationManager } from "../../frida/FridaInstrumentationManager.js";
const signal = <Handler extends (...args: never[]) => void>() => {
let connected: Handler | undefined;
const value: Signal<Handler> & {
emit: (...args: Parameters<Handler>) => void;
} = {
connect: (handler) => {
connected = handler;
},
disconnect: (handler) => {
if (connected === handler) connected = undefined;
},
emit: (...args) => connected?.(...args),
};
return value;
};
class FakeScript implements Script {
readonly message =
signal<(message: FridaMessage, data: Buffer | null) => void>();
isDestroyed = false;
loadFailure: Error | undefined;
unloadFailureCount = 0;
unloadCalls = 0;
constructor(
readonly payload: unknown = { event: "loaded" },
readonly beforeLoad: () => Promise<void> = async () => {},
readonly description = "script loaded",
readonly stack = "",
) {}
async load(): Promise<void> {
await this.beforeLoad();
if (this.loadFailure !== undefined) throw this.loadFailure;
this.message.emit(
{
type: "send",
payload: this.payload,
description: this.description,
stack: this.stack,
},
null,
);
}
async unload(): Promise<void> {
this.unloadCalls += 1;
if (this.unloadFailureCount > 0) {
this.unloadFailureCount -= 1;
throw new Error("script unload failed");
}
if (this.isDestroyed) throw new Error("Script is destroyed");
this.isDestroyed = true;
}
}
class FakeSession implements Session {
readonly detached = signal<() => void>();
readonly scripts: FakeScript[] = [];
nextPayload: unknown = { event: "loaded" };
nextDescription = "script loaded";
nextStack = "";
nextLoadFailure: Error | undefined;
nextUnloadFailureCount = 0;
detachFailureCount = 0;
scriptLoadGate: Promise<void> | undefined;
onScriptLoadStarted: (() => void) | undefined;
private detachedState = false;
readonly pid = 512;
isDetached(): boolean {
return this.detachedState;
}
async createScript(): Promise<Script> {
const script = new FakeScript(
this.nextPayload,
async () => {
this.onScriptLoadStarted?.();
await this.scriptLoadGate;
},
this.nextDescription,
this.nextStack,
);
script.loadFailure = this.nextLoadFailure;
script.unloadFailureCount = this.nextUnloadFailureCount;
this.nextPayload = { event: "loaded" };
this.nextDescription = "script loaded";
this.nextStack = "";
this.nextLoadFailure = undefined;
this.nextUnloadFailureCount = 0;
this.scripts.push(script);
return script;
}
async detach(): Promise<void> {
if (this.detachFailureCount > 0) {
this.detachFailureCount -= 1;
throw new Error("session detach failed");
}
for (const script of this.scripts) script.isDestroyed = true;
this.markDetached();
}
markDetached(): void {
this.detachedState = true;
this.detached.emit();
}
markDetachedWithoutSignal(): void {
this.detachedState = true;
}
}
class FakeDevice implements Device {
readonly id = "local";
readonly name = "Local System";
readonly type = "local";
readonly process = { pid: 512, name: "fixture" } satisfies Process;
readonly session = new FakeSession();
resumed: number[] = [];
resumeFailureCount = 0;
readonly spawned: string[] = [];
async enumerateProcesses(): Promise<Process[]> {
return [this.process];
}
async getProcessByPid(): Promise<Process> {
return this.process;
}
async spawn(program: string): Promise<number> {
this.spawned.push(program);
return this.process.pid;
}
async resume(pid: number): Promise<void> {
if (this.resumeFailureCount > 0) {
this.resumeFailureCount -= 1;
throw new Error("target resume failed");
}
this.resumed.push(pid);
}
async attach(): Promise<Session> {
return this.session;
}
}
class FakeDeviceManager implements DeviceManager {
readonly device = new FakeDevice();
removedRemote: string[] = [];
removeRemoteFailureCount = 0;
removeRemoteFailureMessage = "remote device removal failed";
async enumerateDevices(): Promise<Device[]> {
return [this.device];
}
async getDeviceById(): Promise<Device> {
return this.device;
}
async addRemoteDevice(): Promise<Device> {
return this.device;
}
async removeRemoteDevice(address: string): Promise<void> {
if (this.removeRemoteFailureCount > 0) {
this.removeRemoteFailureCount -= 1;
throw new Error(this.removeRemoteFailureMessage);
}
this.removedRemote.push(address);
}
}
const startLocalAttachedSession = async (
bindings = new FakeDeviceManager(),
) => {
const manager = new FridaInstrumentationManager({ deviceManager: bindings });
const started = await manager.startSession({
mode: "attach",
deviceId: "local",
pid: 512,
});
return { bindings, manager, started };
};
// eslint-disable-next-line max-lines-per-function -- related manager lifecycle cases share the same focused fake provider.
describe("FridaInstrumentationManager", () => {
it("retains a failed startup's spawn and remote lease until cleanup succeeds", async () => {
const bindings = new FakeDeviceManager();
bindings.device.attach = async () => {
throw new Error("attach failed after spawn");
};
bindings.device.resumeFailureCount = 2;
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
remote: { address: "127.0.0.1:27042" },
program: "/tmp/fixture",
});
if (started.ok) throw new Error("Attach unexpectedly succeeded");
expect(started.error.cleanupIncomplete).toBe(true);
expect(bindings.device.resumed).toEqual([]);
expect(bindings.removedRemote).toEqual([]);
await expect(manager.closeAll()).rejects.toThrow("cleanup was incomplete");
expect(bindings.device.resumed).toEqual([]);
expect(bindings.removedRemote).toEqual([]);
// A lookup could now select a different device with the same PID. Cleanup
// must use the original provider handle, not select the target again.
const replacement = new FakeDevice();
bindings.getDeviceById = async () => replacement;
bindings.addRemoteDevice = async () => replacement;
await Promise.all([manager.closeAll(), manager.closeAll()]);
expect(bindings.device.resumed).toEqual([512]);
expect(replacement.resumed).toEqual([]);
expect(bindings.removedRemote).toEqual(["127.0.0.1:27042"]);
await manager.closeAll();
expect(bindings.device.resumed).toEqual([512]);
expect(bindings.removedRemote).toEqual(["127.0.0.1:27042"]);
});
it("retains an acquired session when startup fails before registration", async () => {
const bindings = new FakeDeviceManager();
bindings.device.session.detached.connect = () => {
throw new Error("detached signal registration failed");
};
bindings.device.session.detachFailureCount = 1;
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
if (started.ok)
throw new Error("Signal registration unexpectedly succeeded");
expect(started.error.cleanupIncomplete).toBe(true);
expect(bindings.device.session.isDetached()).toBe(false);
expect(bindings.device.resumed).toEqual([]);
await manager.closeAll();
expect(bindings.device.session.isDetached()).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
});
it("does not release another session's remote lease when retrying failed startup removal", async () => {
const bindings = new FakeDeviceManager();
bindings.device.attach = async () => {
throw new Error("attach failed");
};
bindings.removeRemoteFailureCount = 1;
const remote = { address: "127.0.0.1:27042" };
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const failed = await manager.startSession({
mode: "spawn",
remote,
program: "/tmp/fixture",
});
if (failed.ok) throw new Error("Attach unexpectedly succeeded");
expect(failed.error.cleanupIncomplete).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
bindings.device.attach = async () => bindings.device.session;
const active = await manager.startSession({
mode: "attach",
remote,
pid: 512,
});
if (!active.ok) throw active.error;
const removedWhileSessionAttached: boolean[] = [];
const remove = bindings.removeRemoteDevice.bind(bindings);
bindings.removeRemoteDevice = async (address) => {
removedWhileSessionAttached.push(!bindings.device.session.isDetached());
await remove(address);
};
await manager.closeAll();
expect(removedWhileSessionAttached).toEqual([false]);
expect(bindings.removedRemote).toEqual([remote.address]);
expect(bindings.device.resumed).toEqual([512]);
});
it("loads instrumentation before resuming a spawned target", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
expect(started.value.state).toBe("paused");
expect(bindings.device.resumed).toEqual([]);
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({ event: 'loaded' });",
});
expect(loaded.ok).toBe(true);
if (!loaded.ok) return;
expect(loaded.value.messages).toContainEqual(
expect.objectContaining({
type: "send",
payload: { event: "loaded" },
}),
);
expect(loaded.value.sourceSha256).toMatch(/^[a-f0-9]{64}$/u);
expect(bindings.device.resumed).toEqual([]);
const resumed = await manager.resumeSession(started.value.sessionId);
expect(resumed.ok).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
expect(manager.status(started.value.sessionId)?.targetResumeObserved).toBe(
true,
);
expect(manager.status(started.value.sessionId)?.state).toBe("running");
await manager.closeAll();
expect(bindings.device.session.isDetached()).toBe(true);
});
it("removes a remote device after process discovery", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "attach",
remote: { address: "127.0.0.1:27042", token: "secret-token" },
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const listed = await manager.listProcesses({
remote: { address: "127.0.0.1:27042", token: "secret-token" },
});
expect(listed.ok).toBe(true);
if (listed.ok) {
expect(listed.value.processes[0]?.pid).toBe(512);
expect(listed.value.cleanupError).toBeNull();
}
expect(bindings.removedRemote).toEqual([]);
await manager.closeSession(started.value.sessionId);
expect(bindings.removedRemote).toEqual(["127.0.0.1:27042"]);
await manager.closeAll();
});
it("preserves remote discovery facts when cleanup fails and retries cleanup", async () => {
const bindings = new FakeDeviceManager();
bindings.removeRemoteFailureCount = 1;
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const listed = await manager.listProcesses({
remote: { address: "127.0.0.1:27042" },
});
expect(listed.ok).toBe(true);
if (listed.ok) {
expect(listed.value.processes).toEqual([
{ pid: 512, name: "fixture", identifier: null },
]);
expect(listed.value.cleanupError).toContain(
"remote device removal failed",
);
}
await manager.closeAll();
expect(bindings.removedRemote).toEqual(["127.0.0.1:27042"]);
});
it("does not expose remote credentials in shutdown cleanup failures", async () => {
const token = "synthetic-close-token";
const certificate = "synthetic-close-certificate";
const bindings = new FakeDeviceManager();
bindings.removeRemoteFailureCount = 2;
bindings.removeRemoteFailureMessage = `${token} ${certificate}`;
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "attach",
remote: { address: "127.0.0.1:27042", token, certificate },
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
let failure = "";
try {
await manager.closeAll();
} catch (cause: unknown) {
failure =
cause instanceof AggregateError
? cause.errors.map((entry: unknown) => String(entry)).join("; ")
: String(cause);
}
expect(failure).not.toBe("");
expect(failure).not.toContain(token);
expect(failure).not.toContain(certificate);
});
it("unloads scripts, resumes a paused spawn, and detaches without killing it", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(true);
const closed = await manager.closeSession(started.value.sessionId);
expect(closed.ok).toBe(true);
expect(bindings.device.session.scripts[0]?.isDestroyed).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
expect(bindings.device.session.isDetached()).toBe(true);
});
it("retains a failed script handle until a later cleanup retry releases it", async () => {
const bindings = new FakeDeviceManager();
bindings.device.session.nextLoadFailure = new Error("script load failed");
bindings.device.session.nextUnloadFailureCount = 1;
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "attach",
deviceId: "local",
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(false);
if (!loaded.ok) expect(loaded.error.cleanupIncomplete).toBe(true);
expect(manager.status(started.value.sessionId)?.scripts).toHaveLength(1);
expect(bindings.device.session.scripts[0]?.unloadCalls).toBe(1);
const closed = await manager.closeSession(started.value.sessionId);
expect(closed.ok).toBe(true);
expect(bindings.device.session.scripts[0]?.unloadCalls).toBe(2);
expect(bindings.device.session.scripts[0]?.isDestroyed).toBe(true);
expect(manager.status(started.value.sessionId)).toBeUndefined();
});
it("closes a session when its target already destroyed the script", async () => {
const { bindings, manager, started } = await startLocalAttachedSession();
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(true);
const script = bindings.device.session.scripts[0];
expect(script).toBeDefined();
if (script === undefined) return;
script.isDestroyed = true;
bindings.device.session.markDetached();
const closed = await manager.closeSession(started.value.sessionId);
expect(closed.ok).toBe(true);
expect(script.unloadCalls).toBe(0);
expect(manager.status(started.value.sessionId)).toBeUndefined();
});
it("does not resume a paused spawn after its parent session detached", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
bindings.device.session.markDetachedWithoutSignal();
const closed = await manager.closeSession(started.value.sessionId);
expect(closed.ok).toBe(true);
expect(bindings.device.resumed).toEqual([]);
expect(manager.status(started.value.sessionId)).toBeUndefined();
});
it("uses successful parent-session detach to release a script after unload fails", async () => {
const { bindings, manager, started } = await startLocalAttachedSession();
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(true);
const script = bindings.device.session.scripts[0];
expect(script).toBeDefined();
if (script === undefined) return;
script.unloadFailureCount = 1;
const closed = await manager.closeSession(started.value.sessionId);
expect(closed.ok).toBe(true);
expect(script.isDestroyed).toBe(true);
expect(manager.status(started.value.sessionId)).toBeUndefined();
});
it("keeps a paused spawn paused when script unload and session detach fail", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(true);
const script = bindings.device.session.scripts[0];
expect(script).toBeDefined();
if (script === undefined) return;
script.unloadFailureCount = 1;
bindings.device.session.detachFailureCount = 1;
const closed = await manager.closeSession(started.value.sessionId);
expect(closed.ok).toBe(false);
expect(bindings.device.resumed).toEqual([]);
expect(manager.status(started.value.sessionId)?.scripts).toHaveLength(1);
});
it("retries resuming a spawn after detach succeeded but resume failed", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(true);
bindings.device.resumeFailureCount = 1;
const firstClose = await manager.closeSession(started.value.sessionId);
expect(firstClose.ok).toBe(false);
expect(bindings.device.session.isDetached()).toBe(true);
expect(manager.status(started.value.sessionId)).toBeDefined();
const retry = await manager.closeSession(started.value.sessionId);
expect(retry.ok).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
expect(manager.status(started.value.sessionId)).toBeUndefined();
});
it("keeps a remote device while a spawned target resume is pending", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "spawn",
remote: { address: "127.0.0.1:27042" },
program: "/tmp/fixture",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
bindings.device.resumeFailureCount = 1;
const firstClose = await manager.closeSession(started.value.sessionId);
expect(firstClose.ok).toBe(false);
expect(bindings.removedRemote).toEqual([]);
const retry = await manager.closeSession(started.value.sessionId);
expect(retry.ok).toBe(true);
expect(bindings.device.resumed).toEqual([512]);
expect(bindings.removedRemote).toEqual(["127.0.0.1:27042"]);
});
it("keeps a remote device while script and session cleanup are pending", async () => {
const bindings = new FakeDeviceManager();
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const started = await manager.startSession({
mode: "attach",
remote: { address: "127.0.0.1:27042" },
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('ready');",
});
expect(loaded.ok).toBe(true);
const script = bindings.device.session.scripts[0];
expect(script).toBeDefined();
if (script === undefined) return;
script.unloadFailureCount = 1;
bindings.device.session.detachFailureCount = 1;
const firstClose = await manager.closeSession(started.value.sessionId);
expect(firstClose.ok).toBe(false);
expect(bindings.removedRemote).toEqual([]);
const retry = await manager.closeSession(started.value.sessionId);
expect(retry.ok).toBe(true);
expect(script.isDestroyed).toBe(true);
expect(bindings.removedRemote).toEqual(["127.0.0.1:27042"]);
});
});
it("does not release a newer remote lease when retrying an older session close", async () => {
const bindings = new FakeDeviceManager();
bindings.removeRemoteFailureCount = 1;
const manager = new FridaInstrumentationManager({ deviceManager: bindings });
const remote = { address: "127.0.0.1:27042" };
const first = await manager.startSession({
mode: "attach",
remote,
pid: 512,
});
expect(first.ok).toBe(true);
if (!first.ok) return;
const failedClose = await manager.closeSession(first.value.sessionId);
expect(failedClose.ok).toBe(false);
const second = await manager.startSession({
mode: "attach",
remote,
pid: 512,
});
expect(second.ok).toBe(true);
if (!second.ok) return;
const retry = await manager.closeSession(first.value.sessionId);
expect(retry.ok).toBe(true);
expect(bindings.removedRemote).toEqual([]);
expect(manager.status(second.value.sessionId)).toBeDefined();
const secondClose = await manager.closeSession(second.value.sessionId);
expect(secondClose.ok).toBe(true);
expect(bindings.removedRemote).toEqual([remote.address]);
});
it("attributes messages to their producing script and returns each load's messages", async () => {
const { bindings, manager, started } = await startLocalAttachedSession();
expect(started.ok).toBe(true);
if (!started.ok) return;
bindings.device.session.nextPayload = { tag: "A" };
const first = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({tag: 'A'});",
});
expect(first.ok).toBe(true);
if (!first.ok) return;
bindings.device.session.nextPayload = { tag: "B" };
const second = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({tag: 'B'});",
});
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(first.value.messages).toEqual([
expect.objectContaining({
script_id: first.value.scriptId,
payload: { tag: "A" },
}),
]);
expect(second.value.messages).toEqual([
expect.objectContaining({
script_id: second.value.scriptId,
payload: { tag: "B" },
}),
]);
expect(manager.status(started.value.sessionId)?.messages).toEqual([
expect.objectContaining({ script_id: first.value.scriptId }),
expect.objectContaining({ script_id: second.value.scriptId }),
]);
await manager.closeAll();
});
it("keeps an active script message bucket after its last message is evicted", async () => {
const { bindings, manager, started } = await startLocalAttachedSession();
const session = bindings.device.session;
expect(started.ok).toBe(true);
if (!started.ok) return;
session.nextPayload = { tag: "A" };
const first = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({tag: 'A'});",
});
expect(first.ok).toBe(true);
if (!first.ok) return;
let finishSecondLoad: (() => void) | undefined;
let markSecondLoadStarted: (() => void) | undefined;
const secondLoadGate = new Promise<void>((resolve) => {
finishSecondLoad = resolve;
});
const secondLoadStarted = new Promise<void>((resolve) => {
markSecondLoadStarted = resolve;
});
session.nextPayload = { tag: "B2" };
session.scriptLoadGate = secondLoadGate;
session.onScriptLoadStarted = () => markSecondLoadStarted?.();
const secondLoading = manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send({tag: 'B2'});",
});
await secondLoadStarted;
const secondScript = session.scripts[1];
expect(secondScript).toBeDefined();
if (secondScript === undefined) return;
secondScript.message.emit({ type: "send", payload: { tag: "B1" } }, null);
const firstScript = session.scripts[0];
expect(firstScript).toBeDefined();
if (firstScript === undefined) return;
for (let index = 0; index < 800; index += 1)
firstScript.message.emit(
{ type: "send", payload: "x".repeat(32_700) },
null,
);
finishSecondLoad?.();
const second = await secondLoading;
expect(second.ok).toBe(true);
if (second.ok) {
expect(second.value.messages).toContainEqual(
expect.objectContaining({
script_id: second.value.scriptId,
payload: { tag: "B2" },
}),
);
expect(second.value.messagesTruncated).toBe(true);
}
expect(manager.status(started.value.sessionId)?.messages).toContainEqual(
expect.objectContaining({
script_id: second.ok ? second.value.scriptId : "",
payload: { tag: "B2" },
}),
);
await manager.closeAll();
});
it("serializes a final remote release against a new same-endpoint session", async () => {
const bindings = new FakeDeviceManager();
let enteredRemoval: (() => void) | undefined;
const removalEntered = new Promise<void>((resolve) => {
enteredRemoval = resolve;
});
let finishRemoval: (() => void) | undefined;
const removalGate = new Promise<void>((resolve) => {
finishRemoval = resolve;
});
bindings.removeRemoteDevice = async (address) => {
enteredRemoval?.();
await removalGate;
bindings.removedRemote.push(address);
};
const manager = new FridaInstrumentationManager({
deviceManager: bindings,
});
const remote = { address: "127.0.0.1:27042", token: "same-token" };
const first = await manager.startSession({
mode: "attach",
remote,
pid: 512,
});
expect(first.ok).toBe(true);
if (!first.ok) return;
const closing = manager.closeSession(first.value.sessionId);
await removalEntered;
let secondStarted = false;
const secondPromise = manager
.startSession({ mode: "attach", remote, pid: 512 })
.then((result) => {
secondStarted = true;
return result;
});
await Promise.resolve();
expect(secondStarted).toBe(false);
finishRemoval?.();
expect((await closing).ok).toBe(true);
const second = await secondPromise;
expect(second.ok).toBe(true);
if (second.ok) await manager.closeSession(second.value.sessionId);
expect(bindings.removedRemote).toEqual([
"127.0.0.1:27042",
"127.0.0.1:27042",
]);
});
it("redacts remote credentials and maps a missing optional binding", async () => {
const secret = "synthetic-secret-token";
const remoteManager = new FakeDeviceManager();
remoteManager.addRemoteDevice = async () => {
throw new Error(`authorization rejected: ${secret}`);
};
const remote = new FridaInstrumentationManager({
deviceManager: remoteManager,
});
const failed = await remote.listProcesses({
remote: {
address: "wss://host/path?token=synthetic-url-token",
token: secret,
},
});
expect(failed.ok).toBe(false);
if (!failed.ok) {
expect(failed.error.message).not.toContain(secret);
expect(failed.error.message).not.toContain("synthetic-url-token");
}
const missing = new FridaInstrumentationManager({
deviceManagerLoader: async () => {
throw new Error("Cannot find package 'frida'");
},
});
const unavailable = await missing.listDevices();
expect(unavailable.ok).toBe(false);
if (!unavailable.ok)
expect(unavailable.error.message).toContain("Cannot find package 'frida'");
});
it("redacts remote credentials echoed by a target script", async () => {
const token = "synthetic-token-from-auth";
const certificate = "synthetic-certificate-from-auth";
const bindings = new FakeDeviceManager();
bindings.device.session.nextPayload = { token, certificate };
const manager = new FridaInstrumentationManager({ deviceManager: bindings });
const started = await manager.startSession({
mode: "attach",
remote: { address: "127.0.0.1:27042", token, certificate },
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('credential payload');",
});
expect(loaded.ok).toBe(true);
if (loaded.ok) {
const serialized = JSON.stringify(loaded.value.messages);
expect(serialized).not.toContain(token);
expect(serialized).not.toContain(certificate);
expect(serialized).toContain("[redacted]");
}
await manager.closeAll();
});
it("bounds oversized Frida message metadata before retaining it", async () => {
const bindings = new FakeDeviceManager();
bindings.device.session.nextDescription = "d".repeat(1_000_000);
bindings.device.session.nextStack = "s".repeat(1_000_000);
const manager = new FridaInstrumentationManager({ deviceManager: bindings });
const started = await manager.startSession({
mode: "attach",
deviceId: "local",
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loaded = await manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('metadata');",
});
expect(loaded.ok).toBe(true);
if (loaded.ok) {
expect(loaded.value.messagesTruncated).toBe(true);
const message = loaded.value.messages[0];
expect(message).toMatchObject({
description_truncated: true,
stack_truncated: true,
});
expect(JSON.stringify(message).length).toBeLessThan(100_000);
}
await manager.closeAll();
});
it("serializes script loading against concurrent close and unloads the loaded script", async () => {
const bindings = new FakeDeviceManager();
let finishScriptLoad: (() => void) | undefined;
const scriptLoadGate = new Promise<void>((resolve) => {
finishScriptLoad = resolve;
});
let markScriptLoadStarted: (() => void) | undefined;
const scriptLoadStarted = new Promise<void>((resolve) => {
markScriptLoadStarted = resolve;
});
bindings.device.session.scriptLoadGate = scriptLoadGate;
bindings.device.session.onScriptLoadStarted = () => markScriptLoadStarted?.();
const manager = new FridaInstrumentationManager({ deviceManager: bindings });
const started = await manager.startSession({
mode: "attach",
deviceId: "local",
pid: 512,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const loading = manager.loadScript(started.value.sessionId, {
sourceKind: "inline",
source: "send('loaded');",
});
await scriptLoadStarted;
let closed = false;
const closing = manager.closeSession(started.value.sessionId);
void closing.then(() => {
closed = true;
});
expect(manager.closeSession(started.value.sessionId)).toBe(closing);
await Promise.resolve();
expect(closed).toBe(false);
finishScriptLoad?.();
expect((await loading).ok).toBe(true);
expect((await closing).ok).toBe(true);
expect(bindings.device.session.scripts[0]?.isDestroyed).toBe(true);
expect(bindings.device.session.isDetached()).toBe(true);
});
@@ -0,0 +1,117 @@
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { OptionalProviderLoadFailure } from "../OptionalObservationProviders.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import type { Result } from "../../domain/result.js";
export interface FridaRemoteConnection {
readonly address: string;
readonly token?: string;
readonly certificate?: string;
readonly origin?: string;
readonly keepaliveInterval?: number;
}
export interface FridaDeviceSelector {
readonly deviceId?: string;
readonly remote?: FridaRemoteConnection;
}
export interface FridaDeviceObservation {
readonly deviceId: string;
readonly name: string;
readonly type: string;
}
export interface FridaProcessObservation {
readonly pid: number;
readonly name: string;
readonly identifier: string | null;
}
export type StartFridaSessionInput = FridaDeviceSelector &
(
| { readonly mode: "attach"; readonly pid: number }
| {
readonly mode: "spawn";
readonly program: string;
readonly argv?: readonly string[];
}
);
export type FridaScriptSource =
| { readonly sourceKind: "inline"; readonly source: string }
| { readonly sourceKind: "file"; readonly path: string };
export interface FridaSessionObservation {
readonly sessionId: string;
readonly deviceId: string;
readonly target: string;
readonly pid: number;
readonly mode: "attach" | "spawn";
readonly state: "paused" | "running" | "detached";
}
export interface FridaScriptObservation {
readonly scriptId: string;
readonly sourceKind: "inline" | "file";
readonly sourcePath: string | null;
readonly sourceSha256: string;
readonly messages: readonly JsonValue[];
readonly messagesTruncated: boolean;
}
export interface FridaSessionStatus extends FridaSessionObservation {
/** True only after REA has successfully resumed this spawned target. */
readonly targetResumeObserved: boolean;
readonly scripts: readonly {
readonly scriptId: string;
readonly name: string;
}[];
readonly messages: readonly JsonValue[];
readonly messagesTruncated: boolean;
}
export interface FridaSessionCleanupObservation {
readonly targetResumeObserved: boolean;
}
/** Shared application boundary for Frida runtime instrumentation workflows. */
export interface FridaInstrumentationPort {
availabilityFailure?(): OptionalProviderLoadFailure | undefined;
listDevices(remote?: FridaRemoteConnection): Promise<
Result<
{
readonly devices: readonly FridaDeviceObservation[];
readonly cleanupError: string | null;
},
AnalysisError
>
>;
listProcesses(selector: FridaDeviceSelector): Promise<
Result<
{
readonly deviceId: string;
readonly processes: readonly FridaProcessObservation[];
readonly cleanupError: string | null;
},
AnalysisError
>
>;
startSession(
input: StartFridaSessionInput,
): Promise<Result<FridaSessionObservation, AnalysisError>>;
loadScript(
sessionId: string,
source: FridaScriptSource,
): Promise<Result<FridaScriptObservation, AnalysisError>>;
resumeSession(sessionId: string): Promise<Result<null, AnalysisError>>;
unloadScript(
sessionId: string,
scriptId: string,
): Promise<Result<null, AnalysisError>>;
status(sessionId: string): FridaSessionStatus | undefined;
closeSession(
sessionId: string,
): Promise<Result<FridaSessionCleanupObservation, AnalysisError>>;
closeAll(): Promise<void>;
}
@@ -0,0 +1,508 @@
import { expect, it } from "vitest";
import type { FridaInstrumentationPort } from "./FridaInstrumentationPort.js";
import { FridaInstrumentationService } from "./FridaInstrumentationService.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
} from "../../domain/analysisErrorCore.js";
const createSession = () => ({
sessionId: "00000000-0000-4000-8000-000000000001",
deviceId: "local",
target: "fixture",
pid: 10,
mode: "spawn" as const,
state: "paused" as const,
});
const createScriptObservation = () => ({
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: "inline" as const,
sourcePath: null,
sourceSha256: "a".repeat(64),
messages: [],
messagesTruncated: false,
});
const createProvider = (
overrides: Partial<FridaInstrumentationPort> = {},
): FridaInstrumentationPort => ({
async listDevices() {
return { ok: true, value: { devices: [], cleanupError: null } };
},
async listProcesses() {
return {
ok: true,
value: { deviceId: "local", processes: [], cleanupError: null },
};
},
async startSession() {
return { ok: true, value: createSession() };
},
async loadScript() {
return { ok: true, value: createScriptObservation() };
},
async resumeSession() {
return { ok: true, value: null };
},
async unloadScript() {
return { ok: true, value: null };
},
status() {
return undefined;
},
async closeSession() {
return { ok: true, value: { targetResumeObserved: false } };
},
async closeAll() {},
...overrides,
});
it.each(["startSession", "instrument"] as const)(
"does not start Frida when %s receives an already-cancelled signal",
async (method) => {
let starts = 0;
let loads = 0;
const provider = createProvider({
async startSession() {
starts += 1;
return { ok: true, value: createSession() };
},
async loadScript() {
loads += 1;
return { ok: true, value: createScriptObservation() };
},
});
const service = new FridaInstrumentationService(provider);
const controller = new AbortController();
controller.abort(new Error("cancelled before call"));
const result =
method === "startSession"
? await service.startSession(
{ mode: "spawn", deviceId: "local", program: "/tmp/fixture" },
controller.signal,
)
: await service.instrument(
{
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 1,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
expect(starts).toBe(0);
expect(loads).toBe(0);
},
);
it("does not resume a spawned target when cancellation arrives during script loading", async () => {
const controller = new AbortController();
let resumes = 0;
let closes = 0;
const service = new FridaInstrumentationService(
createProvider({
async loadScript() {
controller.abort(new Error("cancelled while loading"));
return { ok: true, value: createScriptObservation() };
},
async resumeSession() {
resumes += 1;
return { ok: true, value: null };
},
async closeSession() {
closes += 1;
return { ok: true, value: { targetResumeObserved: true } };
},
}),
);
const result = await service.instrument(
{
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 1,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
cleanup_error: null,
target_state_before_cleanup: "paused",
target_resume_observed: true,
instrumentation_cleanup: "released",
target_liveness_after_cleanup: "unknown",
},
parameters: {
mode: "spawn",
program: "/tmp/fixture",
},
});
}
expect(resumes).toBe(0);
expect(closes).toBe(1);
});
it("reports the spawned session when cancellation arrives during resume", async () => {
const controller = new AbortController();
let closes = 0;
const service = new FridaInstrumentationService(
createProvider({
async resumeSession() {
controller.abort(new Error("cancelled while resuming"));
return { ok: true, value: null };
},
status() {
return {
...createSession(),
state: "running",
targetResumeObserved: true,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession() {
closes += 1;
return { ok: true, value: { targetResumeObserved: false } };
},
}),
);
const result = await service.instrument(
{
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
argv: ["--owned-fixture"],
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 60_000,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
target_state_before_cleanup: "running",
target_resume_observed: true,
instrumentation_cleanup: "released",
target_liveness_after_cleanup: "unknown",
},
parameters: {
argv: ["--owned-fixture"],
},
});
}
expect(closes).toBe(1);
});
it("does not infer a Frida resume for a running attached target on cancellation", async () => {
const controller = new AbortController();
const service = new FridaInstrumentationService(
createProvider({
async loadScript() {
controller.abort(new Error("cancelled while loading"));
return { ok: true, value: createScriptObservation() };
},
status() {
return {
...createSession(),
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession() {
return { ok: true, value: { targetResumeObserved: false } };
},
}),
);
const result = await service.instrument(
{
mode: "attach",
deviceId: "local",
pid: 512,
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 0,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
target_state_before_cleanup: "running",
target_resume_observed: false,
},
});
});
it("retains an observed spawn resume after the target detaches before cancellation", async () => {
const controller = new AbortController();
const service = new FridaInstrumentationService(
createProvider({
async loadScript() {
controller.abort(new Error("cancelled after target exit"));
return { ok: true, value: createScriptObservation() };
},
status() {
return {
...createSession(),
state: "detached",
targetResumeObserved: true,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession() {
return { ok: true, value: { targetResumeObserved: false } };
},
}),
);
const result = await service.instrument(
{
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 0,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
target_state_before_cleanup: "detached",
target_resume_observed: true,
},
});
});
it.each([
{ cleanupState: "running" as const, resumeObserved: true },
{ cleanupState: "paused" as const, resumeObserved: false },
])(
"uses a spawned target state transition after failed cleanup ($cleanupState)",
async ({ cleanupState, resumeObserved }) => {
const controller = new AbortController();
let statusCalls = 0;
const service = new FridaInstrumentationService(
createProvider({
async loadScript() {
controller.abort(new Error("cancelled while loading"));
return { ok: true, value: createScriptObservation() };
},
status() {
statusCalls += 1;
return {
...createSession(),
state: statusCalls === 1 ? "paused" : cleanupState,
targetResumeObserved: false,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession() {
return {
ok: false,
error: new AnalysisCapabilityUnavailableError(
"frida",
"close_frida_session",
"session cleanup failed",
),
};
},
}),
);
const result = await service.instrument(
{
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 0,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
instrumentation_cleanup: "incomplete_or_unknown",
target_state_before_cleanup: "paused",
target_resume_observed: resumeObserved,
},
});
},
);
it("records target selection in Evidence without remote authentication values", async () => {
const token = "synthetic-frida-token";
const certificate = "synthetic-frida-certificate";
const service = new FridaInstrumentationService(createProvider());
const result = await service.instrument({
mode: "spawn",
remote: {
address: "127.0.0.1:27042",
token,
certificate,
origin: "rea-test",
keepaliveInterval: 1_000,
},
program: "/tmp/fixture",
argv: ["--marker", "selected-argument"],
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 1,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.evidence.parameters).toMatchObject({
session_id: createSession().sessionId,
remote: {
address: "127.0.0.1:27042",
origin: "rea-test",
keepalive_interval: 1_000,
},
mode: "spawn",
program: "/tmp/fixture",
argv: ["--marker", "selected-argument"],
});
const parameters = JSON.stringify(result.value.evidence.parameters);
expect(parameters).not.toContain(token);
expect(parameters).not.toContain(certificate);
});
it("reports completed cleanup when closing the parent session releases a failed script", async () => {
const service = new FridaInstrumentationService(
createProvider({
async loadScript() {
return {
ok: false,
error: new AnalysisCapabilityUnavailableError(
"frida",
"load_frida_script",
"script load failed",
{
cleanup: {
reason: "script unload failed",
resources: ["script-1"],
},
},
),
};
},
}),
);
const result = await service.instrument({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: { sourceKind: "inline", source: "send('ready');" },
durationMs: 1,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.cleanupIncomplete).toBe(false);
});
it("cleans up a session and returns typed cancellation after a pending start", async () => {
let finishStart: (() => void) | undefined;
let markStartCalled: (() => void) | undefined;
const startGate = new Promise<void>((resolve) => {
finishStart = resolve;
});
const startCalled = new Promise<void>((resolve) => {
markStartCalled = resolve;
});
const closed: string[] = [];
const provider: FridaInstrumentationPort = {
async listDevices() {
return { ok: true, value: { devices: [], cleanupError: null } };
},
async listProcesses() {
return {
ok: true,
value: { deviceId: "local", processes: [], cleanupError: null },
};
},
async startSession() {
markStartCalled?.();
await startGate;
return {
ok: true,
value: {
sessionId: "00000000-0000-4000-8000-000000000001",
deviceId: "local",
target: "fixture",
pid: 10,
mode: "attach",
state: "running",
},
};
},
async loadScript() {
return {
ok: false,
error: new AnalysisInputError("load_frida_script"),
};
},
async resumeSession() {
return { ok: true, value: null };
},
async unloadScript() {
return { ok: true, value: null };
},
status() {
return undefined;
},
async closeSession(sessionId) {
closed.push(sessionId);
return { ok: true, value: { targetResumeObserved: false } };
},
async closeAll() {},
};
const service = new FridaInstrumentationService(provider);
const controller = new AbortController();
const pending = service.startSession(
{ mode: "attach", deviceId: "local", pid: 10 },
controller.signal,
);
await startCalled;
controller.abort(new Error("caller cancelled"));
finishStart?.();
const result = await pending;
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
expect(closed).toEqual(["00000000-0000-4000-8000-000000000001"]);
});
@@ -0,0 +1,400 @@
import { setTimeout as delay } from "node:timers/promises";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
FridaDeviceSelector,
FridaInstrumentationPort,
FridaRemoteConnection,
FridaScriptObservation,
FridaScriptSource,
FridaSessionObservation,
FridaSessionStatus,
StartFridaSessionInput,
} from "./FridaInstrumentationPort.js";
/** Shared CLI/MCP workflows for Frida's device and instrumentation operations. */
export class FridaInstrumentationService {
readonly #provider: FridaInstrumentationPort;
constructor(provider: FridaInstrumentationPort) {
this.#provider = provider;
}
listDevices(remote?: FridaRemoteConnection) {
return this.#provider.listDevices(remote);
}
listProcesses(selector: FridaDeviceSelector) {
return this.#provider.listProcesses(selector);
}
async startSession(input: StartFridaSessionInput, signal?: AbortSignal) {
return this.#startSession(input, signal, "start_frida_session");
}
async #startSession(
input: StartFridaSessionInput,
signal: AbortSignal | undefined,
operation: string,
) {
if (signal?.aborted)
return err(
new AnalysisCancelledError(
operation,
signal.reason === undefined ? {} : { cause: signal.reason },
),
);
const started = await this.#provider.startSession(input);
if (!started.ok || !signal?.aborted) return started;
return this.#cancelSession(operation, started.value, input, signal.reason);
}
async #cancelSession(
operation: string,
session: FridaSessionObservation,
input: StartFridaSessionInput,
cause: unknown,
loaded?: FridaScriptObservation,
): Promise<Result<never, AnalysisError>> {
const status = this.#provider.status(session.sessionId);
const observation = status ?? {
...session,
targetResumeObserved: false,
scripts: [],
messages: loaded?.messages ?? [],
messagesTruncated: loaded?.messagesTruncated ?? false,
};
const closed = await this.#provider.closeSession(session.sessionId);
const statusAfterCleanup = this.#provider.status(session.sessionId);
const partialObservation = fridaEvidence(
operation,
{
...sessionStatusOutput(observation),
...(loaded === undefined
? {}
: {
source_kind: loaded.sourceKind,
source_path: loaded.sourcePath,
source_sha256: loaded.sourceSha256,
}),
cleanup_error: closed.ok ? null : closed.error.message,
target_state_before_cleanup: observation.state,
target_resume_observed:
observation.targetResumeObserved ||
(observation.mode === "spawn" && observation.state === "running") ||
(closed.ok && closed.value.targetResumeObserved) ||
(observation.mode === "spawn" &&
observation.state !== "running" &&
statusAfterCleanup?.state === "running"),
instrumentation_cleanup: closed.ok
? "released"
: "incomplete_or_unknown",
target_liveness_after_cleanup: "unknown",
},
fridaParameters(session.sessionId, input, session.deviceId),
);
return err(
new AnalysisCancelledError(operation, {
...(cause === undefined ? {} : { cause }),
partialObservation,
...(closed.ok
? {}
: {
cleanup: {
reason: closed.error.message,
resources: [session.sessionId],
},
}),
}),
);
}
async loadScript(
sessionId: string,
source: FridaScriptSource,
): Promise<Result<Evidence, AnalysisError>> {
const loaded = await this.#provider.loadScript(sessionId, source);
return loaded.ok
? ok(
fridaEvidence("load_frida_script", scriptOutput(loaded.value), {
session_id: sessionId,
}),
)
: loaded;
}
resumeSession(sessionId: string) {
return this.#provider.resumeSession(sessionId);
}
unloadScript(sessionId: string, scriptId: string) {
return this.#provider.unloadScript(sessionId, scriptId);
}
status(sessionId: string): FridaSessionStatus | undefined {
return this.#provider.status(sessionId);
}
statusEvidence(sessionId: string): Evidence | undefined {
const status = this.#provider.status(sessionId);
return status === undefined
? undefined
: fridaEvidence("frida_session_status", sessionStatusOutput(status), {
session_id: sessionId,
});
}
async instrument(
input: StartFridaSessionInput & {
readonly source: FridaScriptSource;
readonly durationMs: number;
},
signal?: AbortSignal,
): Promise<
Result<
{ readonly evidence: Evidence; readonly cleanupError: string | null },
AnalysisError
>
> {
const started = await this.#startSession(
input,
signal,
"instrument_with_frida",
);
if (!started.ok) return started;
if (signal?.aborted)
return this.#cancelSession(
"instrument_with_frida",
started.value,
input,
signal.reason,
);
const loaded = await this.#provider.loadScript(
started.value.sessionId,
input.source,
);
if (signal?.aborted)
return this.#cancelSession(
"instrument_with_frida",
started.value,
input,
signal.reason,
loaded.ok ? loaded.value : undefined,
);
if (!loaded.ok) {
const closed = await this.#provider.closeSession(started.value.sessionId);
return closed.ok
? err(withRecoveredFridaCleanup(loaded.error))
: err(
withCleanupFailure(
loaded.error,
closed.error.message,
started.value.sessionId,
),
);
}
if (started.value.mode === "spawn") {
const resumed = await this.#provider.resumeSession(
started.value.sessionId,
);
if (signal?.aborted)
return this.#cancelSession(
"instrument_with_frida",
started.value,
input,
signal.reason,
loaded.value,
);
if (!resumed.ok) {
const closed = await this.#provider.closeSession(
started.value.sessionId,
);
return closed.ok
? resumed
: err(
withCleanupFailure(
resumed.error,
closed.error.message,
started.value.sessionId,
),
);
}
}
try {
await delay(input.durationMs, undefined, { signal });
} catch (cause: unknown) {
return this.#cancelSession(
"instrument_with_frida",
started.value,
input,
cause,
loaded.value,
);
}
if (signal?.aborted)
return this.#cancelSession(
"instrument_with_frida",
started.value,
input,
signal.reason,
loaded.value,
);
const status = this.#provider.status(started.value.sessionId);
const observation = status ?? {
...started.value,
targetResumeObserved: false,
scripts: [],
messages: loaded.value.messages,
messagesTruncated: loaded.value.messagesTruncated,
};
const closed = await this.#provider.closeSession(started.value.sessionId);
const cleanupError = closed.ok ? null : closed.error.message;
const evidence = fridaEvidence(
"instrument_with_frida",
{
...sessionStatusOutput(observation),
source_kind: loaded.value.sourceKind,
source_path: loaded.value.sourcePath,
source_sha256: loaded.value.sourceSha256,
cleanup_error: cleanupError,
},
fridaParameters(started.value.sessionId, input, started.value.deviceId),
);
return ok({
evidence,
cleanupError,
});
}
closeSession(sessionId: string) {
return this.#provider.closeSession(sessionId);
}
closeAll(): Promise<void> {
return this.#provider.closeAll();
}
}
const fridaEvidence = (
operation: string,
result: unknown,
parameters: unknown,
): Evidence =>
createEvidence(
undefined,
{ id: "frida", name: "Frida", version: null },
{
predicateType: "rea.frida.instrumentation-observation",
operation,
parameters: jsonObjectSchema.parse(parameters),
result: jsonValueSchema.parse(result),
confidence: "observed",
authority: "external-service",
environment: null,
limitations: [
"The target operating system and architecture were not reported by this observation.",
],
},
);
const fridaParameters = (
sessionId: string,
input: StartFridaSessionInput,
deviceId: string,
) => ({
session_id: sessionId,
device_id: deviceId,
...(input.remote === undefined
? {}
: {
remote: {
address: input.remote.address,
...(input.remote.origin === undefined
? {}
: { origin: input.remote.origin }),
...(input.remote.keepaliveInterval === undefined
? {}
: { keepalive_interval: input.remote.keepaliveInterval }),
},
}),
mode: input.mode,
...(input.mode === "attach"
? { pid: input.pid }
: {
program: input.program,
...(input.argv === undefined ? {} : { argv: input.argv }),
}),
});
const withCleanupFailure = (
original: AnalysisError,
cleanupReason: string,
sessionId: string,
): AnalysisError =>
new AnalysisCapabilityUnavailableError(
"frida",
"instrument_with_frida",
`${original.message}; cleanup failed: ${cleanupReason}`,
{
cause: original,
cleanup: {
reason: cleanupReason,
resources: [sessionId],
},
},
);
/** Preserve the original Frida failure after its owner confirms cleanup. */
export const withRecoveredFridaCleanup = (
error: AnalysisError,
): AnalysisError =>
error instanceof AnalysisCapabilityUnavailableError && error.cleanupIncomplete
? new AnalysisCapabilityUnavailableError(
error.providerId,
error.operation,
error.reason,
{
cause: error.cause,
...(error.capturedOutput === undefined
? {}
: { capturedOutput: error.capturedOutput }),
...(error.partialObservation === undefined
? {}
: { partialObservation: error.partialObservation }),
...(error.userMessage === undefined
? {}
: { userMessage: error.userMessage }),
},
)
: error;
const scriptOutput = (script: FridaScriptObservation) => ({
script_id: script.scriptId,
source_kind: script.sourceKind,
source_path: script.sourcePath,
source_sha256: script.sourceSha256,
messages: script.messages,
messages_truncated: script.messagesTruncated,
});
const sessionStatusOutput = (status: FridaSessionStatus) => ({
session_id: status.sessionId,
device_id: status.deviceId,
state: status.state,
target: status.target,
pid: status.pid,
mode: status.mode,
scripts: status.scripts.map((script) => ({
script_id: script.scriptId,
name: script.name,
})),
messages: status.messages,
messages_truncated: status.messagesTruncated,
});