chore: merge main and preserve tool effect exceptions
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -128,6 +128,20 @@ const parseDocument = (
|
||||
return objectSchema.parse(document);
|
||||
};
|
||||
|
||||
/** A parsed configuration whose structure, not its syntax, cannot hold MCP servers. */
|
||||
export class ClientConfigurationShapeError extends TypeError {}
|
||||
|
||||
const requireObject = (
|
||||
value: unknown,
|
||||
description: string,
|
||||
): Record<string, unknown> => {
|
||||
const parsed = objectSchema.safeParse(value);
|
||||
if (parsed.success) return parsed.data;
|
||||
throw new ClientConfigurationShapeError(`${description} must be an object`, {
|
||||
cause: parsed.error,
|
||||
});
|
||||
};
|
||||
|
||||
/** Members of OpenCode V2's `mcp` object that are not server names. */
|
||||
const OPENCODE_V2_MCP_SETTINGS = new Set(["servers", "timeout"]);
|
||||
|
||||
@@ -140,10 +154,21 @@ export const parseClientConfiguration = (
|
||||
throw new TypeError("client does not have a supported MCP config format");
|
||||
// DeepSeek Harness stores a Cordis patch list, not a server table.
|
||||
if (format === "dsh") return parseDshCordisDocument(text);
|
||||
const document = parseDocument(text, format);
|
||||
let document: Record<string, unknown>;
|
||||
try {
|
||||
document = parseDocument(text, format);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof z.ZodError)
|
||||
throw new ClientConfigurationShapeError(
|
||||
"The configuration root must be an object",
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
const serversKey = clientConfigurationServersKey(format);
|
||||
const value = document[serversKey];
|
||||
const servers = value === undefined ? {} : objectSchema.parse(value);
|
||||
const servers =
|
||||
value === undefined ? {} : requireObject(value, `"${serversKey}"`);
|
||||
const native = servers.servers;
|
||||
// A V1 server named `servers` has a string `type` discriminator; the V2
|
||||
// table may instead hold a server object named `type`.
|
||||
@@ -164,7 +189,7 @@ export const parseClientConfiguration = (
|
||||
};
|
||||
return {
|
||||
document,
|
||||
servers: objectSchema.parse(native),
|
||||
servers: requireObject(native, `"${serversKey}.servers"`),
|
||||
serversPath: [serversKey, "servers"],
|
||||
dialect: "opencode_v2",
|
||||
legacyServers: Object.fromEntries(
|
||||
|
||||
@@ -22,7 +22,10 @@ export interface OptionalProviderLoadFailure {
|
||||
|
||||
export type OptionalProviderLoadFailures = Readonly<
|
||||
Partial<
|
||||
Record<keyof OptionalObservationProviders, OptionalProviderLoadFailure>
|
||||
Record<
|
||||
keyof OptionalObservationProviders | "fridaInstrumentation",
|
||||
OptionalProviderLoadFailure
|
||||
>
|
||||
>
|
||||
>;
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
ClientConfigurationShapeError,
|
||||
parseClientConfiguration,
|
||||
serializeClientConfiguration,
|
||||
clientServerPath,
|
||||
@@ -6,7 +7,7 @@ import {
|
||||
withClientServers,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { copyFile, lstat, realpath, rm } from "node:fs/promises";
|
||||
import { copyFile, lstat, realpath, rm, rmdir } from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
|
||||
import { join } from "node:path";
|
||||
@@ -50,6 +51,8 @@ export interface UninstallFileSystem {
|
||||
stat(path: string): Promise<ManagedPathStats>;
|
||||
realpath?(path: string): Promise<string>;
|
||||
remove(path: string, recursive?: boolean): Promise<void>;
|
||||
/** Remove a directory only if it is empty; a non-empty one is kept. */
|
||||
removeEmptyDirectory?(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemFileSystem = (
|
||||
@@ -64,6 +67,7 @@ const systemFileSystem = (
|
||||
stat: (path) => lstat(path),
|
||||
realpath: (path) => realpath(path),
|
||||
remove: (path, recursive = true) => rm(path, { recursive }),
|
||||
removeEmptyDirectory: (path) => rmdir(path),
|
||||
});
|
||||
|
||||
/** One explicitly classified uninstall action. */
|
||||
@@ -279,12 +283,13 @@ const readClientConfiguration = async (
|
||||
const parsed = parseClientConfiguration(original, client.format);
|
||||
return { kind: "configuration", transactionPath, original, parsed };
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
return itemRead(
|
||||
item(
|
||||
client.name,
|
||||
"failed",
|
||||
`Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
cause instanceof ClientConfigurationShapeError
|
||||
? `Configuration was not changed: ${cause.message}. Repair it, then rerun uninstall.`
|
||||
: `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -600,10 +605,20 @@ const removeManagedSkill = async (
|
||||
"REA ownership manifest was retained because a managed file could not be safely removed.",
|
||||
),
|
||||
);
|
||||
else
|
||||
results.push(
|
||||
await removeManagedSkillFile(path, manifestName, name, fileSystem),
|
||||
else {
|
||||
const manifest = await removeManagedSkillFile(
|
||||
path,
|
||||
manifestName,
|
||||
name,
|
||||
fileSystem,
|
||||
);
|
||||
results.push(manifest);
|
||||
const directories =
|
||||
manifest.status === "removed"
|
||||
? await removeEmptyManagedDirectories(path, name, fileSystem)
|
||||
: undefined;
|
||||
if (directories !== undefined) results.push(directories);
|
||||
}
|
||||
const failed = results.find(({ status }) => status === "failed");
|
||||
if (failed !== undefined)
|
||||
return item(name, "failed", results.map(({ detail }) => detail).join(" "));
|
||||
@@ -615,6 +630,46 @@ const removeManagedSkill = async (
|
||||
);
|
||||
};
|
||||
|
||||
/** Directories setup creates for managed files, deepest first, then the root. */
|
||||
const MANAGED_SKILL_DIRECTORIES = [
|
||||
...new Set(
|
||||
MANAGED_SKILL_FILES.map((relativePath) =>
|
||||
relativePath.split("/").slice(0, -1).join("/"),
|
||||
).filter((directory) => directory.length > 0),
|
||||
),
|
||||
].sort((left, right) => right.split("/").length - left.split("/").length);
|
||||
|
||||
/** Remove managed directories left empty; any remaining user file keeps them. */
|
||||
const removeEmptyManagedDirectories = async (
|
||||
root: string,
|
||||
name: string,
|
||||
fileSystem: UninstallFileSystem,
|
||||
): Promise<UninstallItem | undefined> => {
|
||||
if (fileSystem.removeEmptyDirectory === undefined) return undefined;
|
||||
for (const directory of [
|
||||
...MANAGED_SKILL_DIRECTORIES.map((relative) => join(root, relative)),
|
||||
root,
|
||||
]) {
|
||||
try {
|
||||
await fileSystem.removeEmptyDirectory(directory);
|
||||
} catch (cause: unknown) {
|
||||
// User files, an absent directory, or a non-directory keep it as is.
|
||||
if (!isKeptDirectory(cause))
|
||||
return item(
|
||||
name,
|
||||
"failed",
|
||||
`Managed skill directory could not be removed: ${directory}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const isKeptDirectory = (cause: unknown): boolean =>
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
["ENOTEMPTY", "EEXIST", "ENOENT", "ENOTDIR"].includes(String(cause.code));
|
||||
|
||||
const removeManagedSkillFile = async (
|
||||
root: string,
|
||||
relativePath: string,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
@@ -5,6 +5,8 @@ import { registerEvmCommands } from "./cli/evmCommands.js";
|
||||
import { registerGoCommands } from "./cli/goCommands.js";
|
||||
import { registerAnalysisViewCommands } from "./cli/analysisViewCommands.js";
|
||||
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
|
||||
import { registerFridaCommands } from "./cli/fridaCommands.js";
|
||||
import type { FridaInstrumentationPort } from "./application/frida/FridaInstrumentationPort.js";
|
||||
import { Cli } from "incur";
|
||||
|
||||
import { createLogger, parseLogLevel } from "./logger.js";
|
||||
@@ -62,6 +64,7 @@ export const createCli = (
|
||||
Record<string, string | undefined>
|
||||
> = process.env,
|
||||
resultOutput?: CliResultOutput,
|
||||
fridaInstrumentation?: FridaInstrumentationPort,
|
||||
): CliInstance => {
|
||||
const environment = snapshotEnvironment(selectedEnvironment);
|
||||
const analysis = createDirectAnalysis(environment);
|
||||
@@ -100,6 +103,7 @@ export const createCli = (
|
||||
registerFirmwareCommands(cli, logger, environment);
|
||||
registerBinaryDiagnosticsCommands(cli, logger, environment);
|
||||
registerAnalysisViewCommands(cli, logger);
|
||||
registerFridaCommands(cli, logger, fridaInstrumentation);
|
||||
registerEvidenceCommands(cli, logger);
|
||||
registerProcessCommands(cli, logger, environment);
|
||||
registerBrowserCommands(cli, logger);
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { z } from "incur";
|
||||
|
||||
import {
|
||||
FridaInstrumentationService,
|
||||
withRecoveredFridaCleanup,
|
||||
} from "../application/frida/FridaInstrumentationService.js";
|
||||
import type {
|
||||
FridaInstrumentationPort,
|
||||
FridaRemoteConnection,
|
||||
} from "../application/frida/FridaInstrumentationPort.js";
|
||||
import { FridaInstrumentationManager } from "../frida/FridaInstrumentationManager.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import { FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION } from "../contracts/fridaToolContracts.js";
|
||||
import { isValidFridaRemoteAddress } from "../contracts/fridaRemoteAddress.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Register Frida discovery and one-shot instrumentation CLI operations. */
|
||||
export const registerFridaCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
provider: FridaInstrumentationPort = new FridaInstrumentationManager(),
|
||||
): void => {
|
||||
const service = new FridaInstrumentationService(provider);
|
||||
// CLI calls own a disposable provider; MCP retains its shared provider until
|
||||
// server shutdown. Await cleanup here, including failed startup resources.
|
||||
const withProviderCleanup = async <Value>(
|
||||
operation: () => Promise<Result<Value, AnalysisError>>,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
const result = await operation();
|
||||
try {
|
||||
await provider.closeAll();
|
||||
} catch (cause: unknown) {
|
||||
const cleanup = new ProviderCleanupError(
|
||||
"frida",
|
||||
["Frida sessions or connections"],
|
||||
result.ok
|
||||
? { partial_observation: jsonValueSchema.parse(result.value) }
|
||||
: {},
|
||||
{ cause, operation: "frida_cleanup" },
|
||||
);
|
||||
return err(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(
|
||||
result.error,
|
||||
cleanup,
|
||||
"frida_cleanup",
|
||||
),
|
||||
);
|
||||
}
|
||||
return result.ok ? result : err(withRecoveredFridaCleanup(result.error));
|
||||
};
|
||||
const remoteOptions = z.object({
|
||||
remoteAddress: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(2048)
|
||||
.refine(isValidFridaRemoteAddress)
|
||||
.optional()
|
||||
.describe("Remote Frida host address, optionally with a port"),
|
||||
token: z.string().min(1).optional().describe("Remote authentication token"),
|
||||
certificate: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Remote TLS certificate"),
|
||||
origin: z.string().min(1).optional().describe("Remote connection origin"),
|
||||
keepaliveInterval: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe(FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION),
|
||||
});
|
||||
const remoteFrom = (
|
||||
options: z.infer<typeof remoteOptions>,
|
||||
): FridaRemoteConnection | undefined =>
|
||||
options.remoteAddress === undefined
|
||||
? undefined
|
||||
: {
|
||||
address: options.remoteAddress,
|
||||
...(options.token === undefined ? {} : { token: options.token }),
|
||||
...(options.certificate === undefined
|
||||
? {}
|
||||
: { certificate: options.certificate }),
|
||||
...(options.origin === undefined ? {} : { origin: options.origin }),
|
||||
...(options.keepaliveInterval === undefined
|
||||
? {}
|
||||
: { keepaliveInterval: options.keepaliveInterval }),
|
||||
};
|
||||
|
||||
const remoteAddressRequired = (
|
||||
options: z.infer<typeof remoteOptions>,
|
||||
): boolean =>
|
||||
options.remoteAddress !== undefined ||
|
||||
(options.token === undefined &&
|
||||
options.certificate === undefined &&
|
||||
options.origin === undefined &&
|
||||
options.keepaliveInterval === undefined);
|
||||
|
||||
cli.command(CLI_COMMANDS.listFridaDevices, {
|
||||
description: "List local Frida devices and an optional remote endpoint",
|
||||
args: z.object({}),
|
||||
options: remoteOptions.refine(
|
||||
remoteAddressRequired,
|
||||
"Remote credentials and connection options require remoteAddress",
|
||||
),
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.listFridaDevices, async () => {
|
||||
const result = await withProviderCleanup(() =>
|
||||
service.listDevices(remoteFrom(options)),
|
||||
);
|
||||
return result.ok
|
||||
? {
|
||||
devices: result.value.devices,
|
||||
cleanup_error: result.value.cleanupError,
|
||||
}
|
||||
: projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.listFridaProcesses, {
|
||||
description: "List processes visible through a Frida device",
|
||||
args: z.object({}),
|
||||
options: remoteOptions
|
||||
.extend({
|
||||
deviceId: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Frida device identifier"),
|
||||
})
|
||||
.refine(
|
||||
(options) =>
|
||||
options.remoteAddress === undefined || options.deviceId === undefined,
|
||||
"Choose either deviceId or remoteAddress, not both",
|
||||
)
|
||||
.refine(
|
||||
remoteAddressRequired,
|
||||
"Remote credentials and connection options require remoteAddress",
|
||||
),
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.listFridaProcesses, async () => {
|
||||
const remote = remoteFrom(options);
|
||||
const result = await withProviderCleanup(() =>
|
||||
service.listProcesses(
|
||||
remote === undefined
|
||||
? { deviceId: options.deviceId ?? "local" }
|
||||
: { remote },
|
||||
),
|
||||
);
|
||||
return result.ok
|
||||
? {
|
||||
device_id: result.value.deviceId,
|
||||
processes: result.value.processes,
|
||||
cleanup_error: result.value.cleanupError,
|
||||
}
|
||||
: projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.instrumentWithFrida, {
|
||||
description: "Run one Frida script against a selected process and detach",
|
||||
args: z.object({
|
||||
mode: z
|
||||
.enum(["attach", "spawn"])
|
||||
.describe("Attach to a PID or spawn a program"),
|
||||
target: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Process ID for attach or program path for spawn"),
|
||||
}),
|
||||
options: remoteOptions
|
||||
.extend({
|
||||
deviceId: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Frida device identifier"),
|
||||
script: z.string().optional().describe("Inline JavaScript to load"),
|
||||
scriptFile: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Path to JavaScript source file"),
|
||||
argument: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe("Arguments passed to a spawned target"),
|
||||
durationMs: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(60_000)
|
||||
.default(1_000)
|
||||
.describe("Instrumentation duration in milliseconds"),
|
||||
})
|
||||
.refine(
|
||||
(options) =>
|
||||
options.remoteAddress === undefined || options.deviceId === undefined,
|
||||
"Choose either deviceId or remoteAddress, not both",
|
||||
)
|
||||
.refine(
|
||||
remoteAddressRequired,
|
||||
"Remote credentials and connection options require remoteAddress",
|
||||
),
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.instrumentWithFrida, async () => {
|
||||
if (
|
||||
(options.script === undefined) ===
|
||||
(options.scriptFile === undefined)
|
||||
)
|
||||
return projectAnalysisError(
|
||||
new AnalysisInputError(CLI_COMMANDS.instrumentWithFrida),
|
||||
);
|
||||
const remote = remoteFrom(options);
|
||||
const selected =
|
||||
remote === undefined
|
||||
? { deviceId: options.deviceId ?? "local" }
|
||||
: { remote };
|
||||
const targetInput =
|
||||
args.mode === "attach"
|
||||
? /^[1-9][0-9]*$/u.test(args.target) &&
|
||||
Number.isSafeInteger(Number(args.target)) &&
|
||||
Number(args.target) > 0
|
||||
? {
|
||||
...selected,
|
||||
mode: "attach" as const,
|
||||
pid: Number(args.target),
|
||||
}
|
||||
: undefined
|
||||
: {
|
||||
...selected,
|
||||
mode: "spawn" as const,
|
||||
program: args.target,
|
||||
...(options.argument === undefined
|
||||
? {}
|
||||
: { argv: options.argument }),
|
||||
};
|
||||
if (targetInput === undefined)
|
||||
return projectAnalysisError(
|
||||
new AnalysisInputError(CLI_COMMANDS.instrumentWithFrida),
|
||||
);
|
||||
const result = await withProviderCleanup(() =>
|
||||
service.instrument(
|
||||
{
|
||||
...targetInput,
|
||||
source:
|
||||
options.scriptFile === undefined
|
||||
? { sourceKind: "inline", source: options.script ?? "" }
|
||||
: { sourceKind: "file", path: options.scriptFile },
|
||||
durationMs: options.durationMs,
|
||||
},
|
||||
signal,
|
||||
),
|
||||
);
|
||||
if (!result.ok) return projectAnalysisError(result.error);
|
||||
if (result.value.cleanupError !== null) process.exitCode = 1;
|
||||
return {
|
||||
evidence: result.value.evidence,
|
||||
cleanup_error: result.value.cleanupError,
|
||||
};
|
||||
}),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -45,6 +45,9 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
inspectGoBinary: "inspect-go-binary",
|
||||
inspectPeResources: "inspect-pe-resources",
|
||||
inspectAnalysisView: "inspect-analysis-view",
|
||||
listFridaDevices: "list-frida-devices",
|
||||
listFridaProcesses: "list-frida-processes",
|
||||
instrumentWithFrida: "instrument-with-frida",
|
||||
inspectEvidenceBundle: "inspect-evidence-bundle",
|
||||
inspectFirmwareRegions: "inspect-firmware-regions",
|
||||
extractFirmware: "extract-firmware",
|
||||
@@ -149,6 +152,9 @@ export const CLI_COMMAND_TOOL_ALIASES = Object.freeze({
|
||||
search: ["search_strings", "search_procedures"],
|
||||
"capture-process": ["capture_process_scenario"],
|
||||
"compare-bundles": ["compare_bundles"],
|
||||
"list-frida-devices": ["list_frida_devices"],
|
||||
"list-frida-processes": ["list_frida_processes"],
|
||||
"instrument-with-frida": ["instrument_with_frida"],
|
||||
});
|
||||
|
||||
/** MCP operations without a dedicated CLI command or direct command alias. */
|
||||
@@ -206,4 +212,10 @@ export const MCP_TOOLS_WITHOUT_DEDICATED_CLI = Object.freeze([
|
||||
"get_evidence_bundle",
|
||||
"get_navigation_context",
|
||||
"inspect_address_context",
|
||||
"start_frida_session",
|
||||
"load_frida_script",
|
||||
"resume_frida_session",
|
||||
"unload_frida_script",
|
||||
"frida_session_status",
|
||||
"close_frida_session",
|
||||
]);
|
||||
|
||||
+38
-3
@@ -1,13 +1,48 @@
|
||||
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
|
||||
import { ConfigurationError } from "../domain/configurationErrors.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import type { JebMcpConnectionFactory } from "../jeb/JebMcpConnection.js";
|
||||
import { parseJebMcpEndpoint } from "../jeb/JebMcpEndpoint.js";
|
||||
import { JebProvider } from "../jeb/JebProvider.js";
|
||||
|
||||
/** Construct one JEB provider bound to the caller-selected MCP endpoint. */
|
||||
/**
|
||||
* Construct one JEB provider bound to the caller-selected MCP endpoint. An
|
||||
* unusable endpoint makes only JEB unavailable; every other CLI command and
|
||||
* MCP tool is composed alongside it.
|
||||
*/
|
||||
export const createJebAnalysisProvider = (
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
connectionFactory?: JebMcpConnectionFactory,
|
||||
): JebAnalysisPort =>
|
||||
new JebProvider({
|
||||
): JebAnalysisPort => {
|
||||
const endpoint = parseJebMcpEndpoint(environment.REA_JEB_MCP_URL);
|
||||
if (!endpoint.ok) {
|
||||
const constraint =
|
||||
typeof endpoint.error.cause === "string"
|
||||
? endpoint.error.cause
|
||||
: endpoint.error.message;
|
||||
return unconfiguredJebProvider(
|
||||
new ConfigurationError("Invalid REA environment configuration", {
|
||||
cause: endpoint.error,
|
||||
settings: [{ setting: "REA_JEB_MCP_URL", constraint }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
return new JebProvider({
|
||||
environment,
|
||||
...(connectionFactory === undefined ? {} : { connectionFactory }),
|
||||
});
|
||||
};
|
||||
|
||||
const unconfiguredJebProvider = (
|
||||
error: ConfigurationError,
|
||||
): JebAnalysisPort => ({
|
||||
inspectAvailability: () =>
|
||||
Promise.resolve({
|
||||
status: "unavailable",
|
||||
code: "not_configured",
|
||||
reason: `REA_JEB_MCP_URL is invalid: ${error.settings[0]?.constraint ?? error.message}`,
|
||||
diagnostics: { setting: "REA_JEB_MCP_URL" },
|
||||
}),
|
||||
close: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(err(error)),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Accept a Frida host address, optionally with a TCP port, without URL credentials or paths. */
|
||||
export const isValidFridaRemoteAddress = (address: string): boolean => {
|
||||
if (address.length === 0 || address.length > 2048) return false;
|
||||
if (/[?@#\s\u0000-\u001f\u007f/]/u.test(address)) return false;
|
||||
if (address.endsWith(":")) return false;
|
||||
try {
|
||||
const parsed = new URL(`tcp://${address}`);
|
||||
const port = parsed.port === "" ? undefined : Number(parsed.port);
|
||||
return (
|
||||
parsed.hostname.length > 0 &&
|
||||
(port === undefined || (port > 0 && port <= 65_535)) &&
|
||||
parsed.username.length === 0 &&
|
||||
parsed.password.length === 0 &&
|
||||
(parsed.pathname === "" || parsed.pathname === "/") &&
|
||||
parsed.search.length === 0 &&
|
||||
parsed.hash.length === 0
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { TOOL_CONTRACTS } from "./toolContracts.js";
|
||||
import { FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION } from "./fridaToolContracts.js";
|
||||
import { isValidFridaRemoteAddress } from "./fridaRemoteAddress.js";
|
||||
|
||||
const contract = (name: string) => {
|
||||
const found = TOOL_CONTRACTS.find((candidate) => candidate.name === name);
|
||||
if (found === undefined) throw new Error(`Missing contract ${name}`);
|
||||
return found.inputSchema;
|
||||
};
|
||||
|
||||
describe("Frida tool contracts", () => {
|
||||
it("documents Frida Core keepalive intervals in seconds", () => {
|
||||
expect(FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION).toBe(
|
||||
"Remote keepalive interval in seconds",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects incomplete or conflicting mode and source selectors", () => {
|
||||
const start = contract("start_frida_session");
|
||||
const load = contract("load_frida_script");
|
||||
const instrument = contract("instrument_with_frida");
|
||||
const processList = contract("list_frida_processes");
|
||||
|
||||
expect(start.safeParse({ mode: "attach", pid: 7 }).success).toBe(true);
|
||||
expect(start.safeParse({ mode: "spawn", program: "app" }).success).toBe(
|
||||
true,
|
||||
);
|
||||
for (const input of [
|
||||
{ mode: "attach" },
|
||||
{ mode: "attach", pid: 7, program: "app" },
|
||||
{ mode: "spawn" },
|
||||
{ mode: "spawn", program: "app", pid: 7 },
|
||||
{
|
||||
mode: "attach",
|
||||
pid: 7,
|
||||
device_id: "local",
|
||||
remote: { address: "host" },
|
||||
},
|
||||
])
|
||||
expect(start.safeParse(input).success).toBe(false);
|
||||
|
||||
expect(
|
||||
load.safeParse({
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "inline",
|
||||
source: "",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
load.safeParse({
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "file",
|
||||
path: "script.js",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
for (const input of [
|
||||
{
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "inline",
|
||||
},
|
||||
{
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "inline",
|
||||
source: "",
|
||||
path: "script.js",
|
||||
},
|
||||
{
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "file",
|
||||
},
|
||||
])
|
||||
expect(load.safeParse(input).success).toBe(false);
|
||||
|
||||
expect(
|
||||
instrument.safeParse({
|
||||
mode: "attach",
|
||||
pid: 7,
|
||||
source_kind: "inline",
|
||||
source: "",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
instrument.safeParse({
|
||||
mode: "spawn",
|
||||
program: "app",
|
||||
source_kind: "file",
|
||||
path: "script.js",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
for (const input of [
|
||||
{
|
||||
mode: "attach",
|
||||
pid: 7,
|
||||
source_kind: "file",
|
||||
path: "script.js",
|
||||
source: "",
|
||||
},
|
||||
{ mode: "spawn", program: "app", source_kind: "inline" },
|
||||
{
|
||||
mode: "spawn",
|
||||
program: "app",
|
||||
pid: 7,
|
||||
source_kind: "inline",
|
||||
source: "",
|
||||
},
|
||||
{
|
||||
mode: "attach",
|
||||
source_kind: "inline",
|
||||
source: "",
|
||||
device_id: "local",
|
||||
remote: { address: "host" },
|
||||
},
|
||||
])
|
||||
expect(instrument.safeParse(input).success).toBe(false);
|
||||
|
||||
expect(processList.safeParse({ device_id: "local" }).success).toBe(true);
|
||||
expect(processList.safeParse({}).success).toBe(false);
|
||||
expect(
|
||||
processList.safeParse({ device_id: "local", remote: { address: "host" } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("publishes the Frida device, process, and session operations", () => {
|
||||
expect(TOOL_CONTRACTS.map(({ name }) => name)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"list_frida_devices",
|
||||
"list_frida_processes",
|
||||
"start_frida_session",
|
||||
"load_frida_script",
|
||||
"resume_frida_session",
|
||||
"unload_frida_script",
|
||||
"frida_session_status",
|
||||
"close_frida_session",
|
||||
"instrument_with_frida",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("declares target authority for every operation that changes instrumentation", () => {
|
||||
for (const name of [
|
||||
"start_frida_session",
|
||||
"load_frida_script",
|
||||
"resume_frida_session",
|
||||
"unload_frida_script",
|
||||
"close_frida_session",
|
||||
"instrument_with_frida",
|
||||
] as const) {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
(candidate) => candidate.name === name,
|
||||
);
|
||||
expect(contract?.effects.mutatesTarget).toBe(true);
|
||||
expect(contract?.effects.idempotent).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts Frida host addresses and rejects URL-like or malformed endpoints", () => {
|
||||
expect(isValidFridaRemoteAddress("127.0.0.1:27042")).toBe(true);
|
||||
expect(isValidFridaRemoteAddress("frida-target.example")).toBe(true);
|
||||
expect(isValidFridaRemoteAddress("[::1]:27042")).toBe(true);
|
||||
expect(isValidFridaRemoteAddress("tcp://127.0.0.1:27042")).toBe(false);
|
||||
expect(isValidFridaRemoteAddress("127.0.0.1:70000")).toBe(false);
|
||||
expect(isValidFridaRemoteAddress("127.0.0.1:0")).toBe(false);
|
||||
expect(isValidFridaRemoteAddress("127.0.0.1:")).toBe(false);
|
||||
expect(isValidFridaRemoteAddress("frida-target/path")).toBe(false);
|
||||
expect(isValidFridaRemoteAddress("user@frida-target")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { isValidFridaRemoteAddress } from "./fridaRemoteAddress.js";
|
||||
|
||||
export const FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION =
|
||||
"Remote keepalive interval in seconds";
|
||||
|
||||
const remoteConnection = z.strictObject({
|
||||
address: z.string().min(1).max(2048).refine(isValidFridaRemoteAddress, {
|
||||
message: "Expected a Frida host address, optionally followed by a port",
|
||||
}),
|
||||
token: z.string().min(1).optional(),
|
||||
certificate: z.string().min(1).optional(),
|
||||
origin: z.string().min(1).optional(),
|
||||
keepalive_interval: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.describe(FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const deviceSelector = z.strictObject({
|
||||
device_id: z.string().min(1).optional(),
|
||||
remote: remoteConnection.optional(),
|
||||
});
|
||||
|
||||
const exclusiveDeviceSelector = <Schema extends z.ZodTypeAny>(schema: Schema) =>
|
||||
schema.refine(
|
||||
(value) =>
|
||||
!(
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"device_id" in value &&
|
||||
"remote" in value &&
|
||||
value.device_id !== undefined &&
|
||||
value.remote !== undefined
|
||||
),
|
||||
"Choose either device_id or remote, not both",
|
||||
);
|
||||
|
||||
const sessionId = z.string().uuid();
|
||||
|
||||
const sessionOutput = z.strictObject({
|
||||
session_id: sessionId,
|
||||
device_id: z.string(),
|
||||
target: z.string(),
|
||||
pid: z.number().int().nonnegative(),
|
||||
mode: z.enum(["attach", "spawn"]),
|
||||
state: z.enum(["paused", "running", "detached"]),
|
||||
});
|
||||
|
||||
const scriptOutput = z.strictObject({
|
||||
script_id: z.string().uuid(),
|
||||
source_kind: z.enum(["inline", "file"]),
|
||||
source_path: z.string().nullable(),
|
||||
source_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
messages: z.array(z.unknown()),
|
||||
messages_truncated: z.boolean(),
|
||||
});
|
||||
|
||||
/** Caller-facing Frida device, process, and instrumentation-session contracts. */
|
||||
export const FRIDA_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "list_frida_devices",
|
||||
...toolContractMetadata("list_frida_devices"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"List Frida devices currently available to this host, optionally connecting to the caller-selected remote Frida endpoint. Remote authentication options are used for this call only and are never returned or recorded.",
|
||||
inputSchema: z.strictObject({ remote: remoteConnection.optional() }),
|
||||
outputSchema: z.strictObject({
|
||||
devices: z.array(
|
||||
z.strictObject({
|
||||
device_id: z.string(),
|
||||
name: z.string(),
|
||||
type: z.string(),
|
||||
}),
|
||||
),
|
||||
cleanup_error: z.string().nullable(),
|
||||
}),
|
||||
examples: [{ title: "List Frida devices", input: {} }],
|
||||
},
|
||||
{
|
||||
name: "list_frida_processes",
|
||||
...toolContractMetadata("list_frida_processes"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"List processes observed on a selected Frida device or caller-supplied remote endpoint. A remote connection is closed after discovery; authentication values are never returned or recorded.",
|
||||
inputSchema: exclusiveDeviceSelector(deviceSelector).refine(
|
||||
(value) => value.device_id !== undefined || value.remote !== undefined,
|
||||
"Select a device_id or a remote endpoint",
|
||||
),
|
||||
outputSchema: z.strictObject({
|
||||
device_id: z.string(),
|
||||
processes: z.array(
|
||||
z.strictObject({
|
||||
pid: z.number().int().nonnegative(),
|
||||
name: z.string(),
|
||||
identifier: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
cleanup_error: z.string().nullable(),
|
||||
}),
|
||||
examples: [
|
||||
{
|
||||
title: "List local Frida processes",
|
||||
input: { device_id: "local" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "start_frida_session",
|
||||
...toolContractMetadata("start_frida_session"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Attach Frida to one selected process or spawn one selected target. Spawned targets remain paused until resume_frida_session, allowing scripts to load before execution. Closing a session detaches instrumentation; it does not kill the target.",
|
||||
inputSchema: z
|
||||
.strictObject({
|
||||
mode: z.enum(["attach", "spawn"]),
|
||||
...deviceSelector.shape,
|
||||
pid: z.number().int().positive().optional(),
|
||||
program: z.string().min(1).optional(),
|
||||
argv: z.array(z.string()).optional(),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
((value.mode === "attach" &&
|
||||
value.pid !== undefined &&
|
||||
value.program === undefined &&
|
||||
value.argv === undefined) ||
|
||||
(value.mode === "spawn" &&
|
||||
value.program !== undefined &&
|
||||
value.pid === undefined)) &&
|
||||
!(value.device_id !== undefined && value.remote !== undefined),
|
||||
"Select one device; attach requires pid; spawn requires program and rejects pid",
|
||||
),
|
||||
outputSchema: sessionOutput,
|
||||
examples: [
|
||||
{
|
||||
title: "Attach to a process",
|
||||
input: { mode: "attach", device_id: "local", pid: 1234 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "load_frida_script",
|
||||
...toolContractMetadata("load_frida_script"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Load caller-supplied JavaScript into a Frida session. Scripts can read or change target memory and behavior and can access the target process's capabilities. Messages and script errors are returned inline as Evidence; source content is not persisted.",
|
||||
inputSchema: z
|
||||
.strictObject({
|
||||
session_id: sessionId,
|
||||
source_kind: z.enum(["inline", "file"]),
|
||||
source: z.string().optional(),
|
||||
path: z.string().min(1).optional(),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
(value.source_kind === "inline" &&
|
||||
value.source !== undefined &&
|
||||
value.path === undefined) ||
|
||||
(value.source_kind === "file" &&
|
||||
value.path !== undefined &&
|
||||
value.source === undefined),
|
||||
"Inline source requires source; file source requires path",
|
||||
),
|
||||
outputSchema: evidenceResultOf(scriptOutput),
|
||||
examples: [
|
||||
{
|
||||
title: "Load an inline Frida script",
|
||||
input: {
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "inline",
|
||||
source: "send(Process.id);",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "resume_frida_session",
|
||||
...toolContractMetadata("resume_frida_session"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Resume the process created by a paused Frida spawn session. Attached processes are already running and cannot be resumed through this operation.",
|
||||
inputSchema: z.strictObject({ session_id: sessionId }),
|
||||
outputSchema: z.strictObject({ state: z.literal("running") }),
|
||||
examples: [
|
||||
{
|
||||
title: "Resume an instrumented process",
|
||||
input: { session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "unload_frida_script",
|
||||
...toolContractMetadata("unload_frida_script"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Unload one caller-selected Frida script from a live session. This removes that script's instrumentation from the target.",
|
||||
inputSchema: z.strictObject({
|
||||
session_id: sessionId,
|
||||
script_id: z.string().uuid(),
|
||||
}),
|
||||
outputSchema: z.strictObject({ unloaded: z.literal(true) }),
|
||||
examples: [
|
||||
{
|
||||
title: "Unload a script",
|
||||
input: {
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
script_id: "00000000-0000-4000-8000-000000000002",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "frida_session_status",
|
||||
...toolContractMetadata("frida_session_status"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Return observed Frida session state and queued script messages. Message history is bounded by the provider capture budget and reports truncation.",
|
||||
inputSchema: z.strictObject({ session_id: sessionId }),
|
||||
outputSchema: evidenceResultOf(
|
||||
z.strictObject({
|
||||
session_id: sessionId,
|
||||
device_id: z.string(),
|
||||
state: z.enum(["paused", "running", "detached"]),
|
||||
target: z.string(),
|
||||
pid: z.number().int().nonnegative(),
|
||||
mode: z.enum(["attach", "spawn"]),
|
||||
scripts: z.array(
|
||||
z.strictObject({ script_id: z.string().uuid(), name: z.string() }),
|
||||
),
|
||||
messages: z.array(z.unknown()),
|
||||
messages_truncated: z.boolean(),
|
||||
}),
|
||||
),
|
||||
examples: [
|
||||
{
|
||||
title: "Check Frida session",
|
||||
input: { session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "close_frida_session",
|
||||
...toolContractMetadata("close_frida_session"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Unload session scripts and detach REA's Frida session. If a spawned process is still paused, resume it before detaching so it is not left suspended. REA never kills the target; its final state is reported as unknown.",
|
||||
inputSchema: z.strictObject({ session_id: sessionId }),
|
||||
outputSchema: z.strictObject({ target_state: z.literal("unknown") }),
|
||||
examples: [
|
||||
{
|
||||
title: "Close Frida session",
|
||||
input: { session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "instrument_with_frida",
|
||||
...toolContractMetadata("instrument_with_frida"),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Run one caller-authored Frida script against an explicitly selected process and detach when the observation window ends. The CLI and MCP share this ephemeral workflow; use MCP session operations for persistent sessions. Remote authentication is used only for this call and excluded from Evidence.",
|
||||
inputSchema: z
|
||||
.strictObject({
|
||||
mode: z.enum(["attach", "spawn"]),
|
||||
...deviceSelector.shape,
|
||||
pid: z.number().int().positive().optional(),
|
||||
program: z.string().min(1).optional(),
|
||||
argv: z.array(z.string()).optional(),
|
||||
source_kind: z.enum(["inline", "file"]),
|
||||
source: z.string().optional(),
|
||||
path: z.string().min(1).optional(),
|
||||
duration_ms: z.number().int().min(0).max(60_000).default(1_000),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
!(value.device_id !== undefined && value.remote !== undefined) &&
|
||||
((value.mode === "attach" &&
|
||||
value.pid !== undefined &&
|
||||
value.program === undefined &&
|
||||
value.argv === undefined) ||
|
||||
(value.mode === "spawn" &&
|
||||
value.program !== undefined &&
|
||||
value.pid === undefined)) &&
|
||||
((value.source_kind === "inline" &&
|
||||
value.source !== undefined &&
|
||||
value.path === undefined) ||
|
||||
(value.source_kind === "file" &&
|
||||
value.path !== undefined &&
|
||||
value.source === undefined)),
|
||||
"Select one device and provide fields matching the mode and source_kind",
|
||||
),
|
||||
outputSchema: evidenceResultOf(
|
||||
z.strictObject({
|
||||
...sessionOutput.shape,
|
||||
scripts: z.array(
|
||||
z.strictObject({ script_id: sessionId, name: z.string() }),
|
||||
),
|
||||
messages: z.array(z.unknown()),
|
||||
messages_truncated: z.boolean(),
|
||||
source_kind: z.enum(["inline", "file"]),
|
||||
source_path: z.string().nullable(),
|
||||
source_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
cleanup_error: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
examples: [
|
||||
{
|
||||
title: "Instrument a selected process briefly",
|
||||
input: {
|
||||
mode: "attach",
|
||||
device_id: "local",
|
||||
pid: 1234,
|
||||
source_kind: "inline",
|
||||
source: "send(Process.id);",
|
||||
duration_ms: 1_000,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -81,4 +81,27 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
left_bundle_path: "/tmp/left-evidence.json",
|
||||
right_bundle_path: "/tmp/right-evidence.json",
|
||||
},
|
||||
list_frida_devices: {},
|
||||
list_frida_processes: { device_id: "local" },
|
||||
start_frida_session: { mode: "attach", device_id: "local", pid: 1234 },
|
||||
load_frida_script: {
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "inline",
|
||||
source: "send(Process.id);",
|
||||
},
|
||||
resume_frida_session: { session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
unload_frida_script: {
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
script_id: "00000000-0000-4000-8000-000000000002",
|
||||
},
|
||||
frida_session_status: { session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
close_frida_session: { session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
instrument_with_frida: {
|
||||
mode: "attach",
|
||||
device_id: "local",
|
||||
pid: 1234,
|
||||
source_kind: "inline",
|
||||
source: "send(Process.id);",
|
||||
duration_ms: 1_000,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecov
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
|
||||
import { ENHANCED_TOOL_CONTRACTS } from "./enhancedToolContracts.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
|
||||
import { FRIDA_TOOL_CONTRACTS } from "./fridaToolContracts.js";
|
||||
|
||||
/** Complete ordered public inventory used by registration and verification. */
|
||||
export const TOOL_CONTRACTS = [
|
||||
@@ -51,6 +52,7 @@ export const TOOL_CONTRACTS = [
|
||||
...WEB_NETWORK_CAPTURE_TOOL_CONTRACTS,
|
||||
...JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
|
||||
...SESSION_TOOL_CONTRACTS,
|
||||
...FRIDA_TOOL_CONTRACTS,
|
||||
] as const;
|
||||
|
||||
/** Resolve a public contract by name while retaining its exact schema types. */
|
||||
|
||||
@@ -14,6 +14,8 @@ const EXECUTION_WORDING =
|
||||
|
||||
const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
|
||||
inspect_artifact: "states that mapper execution remains unobserved",
|
||||
start_frida_session:
|
||||
"spawned targets remain suspended until resume_frida_session",
|
||||
inspect_native_load_image: "states that it does not execute the target",
|
||||
resolve_native_call_targets: "states that it does not execute code",
|
||||
inspect_pe_resources: "states that it does not execute the image",
|
||||
@@ -118,8 +120,11 @@ describe("tool effects", () => {
|
||||
"capture_native_ui_scenario",
|
||||
"capture_process_scenario",
|
||||
"install_adb_package",
|
||||
"instrument_with_frida",
|
||||
"load_frida_script",
|
||||
"observe_native_calls",
|
||||
"push_adb_file",
|
||||
"resume_frida_session",
|
||||
"start_adb_activity",
|
||||
"start_adb_app",
|
||||
"stop_adb_app",
|
||||
|
||||
@@ -98,6 +98,57 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
writesFilesystem: true,
|
||||
launchesProcess: true,
|
||||
}),
|
||||
list_frida_devices: effects({ launchesProcess: true, accessesNetwork: true }),
|
||||
list_frida_processes: effects({
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
}),
|
||||
start_frida_session: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
load_frida_script: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
resume_frida_session: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
unload_frida_script: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
frida_session_status: effects(),
|
||||
close_frida_session: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
instrument_with_frida: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
accessesNetwork: true,
|
||||
executesForeignCode: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
inspect_pe_resources: evidence,
|
||||
inspect_analysis_view: evidence,
|
||||
inspect_firmware_regions: effects({
|
||||
|
||||
@@ -4,16 +4,29 @@ import {
|
||||
} from "../../domain/wasm/wasmArtifact.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
import {
|
||||
analysisDetailSchema,
|
||||
analysisDetailOutputSchemaOf,
|
||||
} from "../analysisDetail.js";
|
||||
import { wasmArtifactSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
|
||||
|
||||
/** Delivery selection does not change the provider input or original Evidence. */
|
||||
export const wasmArtifactInspectionInputSchema =
|
||||
inspectWasmArtifactInputSchema.extend({
|
||||
detail: analysisDetailSchema.unwrap().optional(),
|
||||
});
|
||||
/** Optional caller-supplied WABT capability with target-free CLI/MCP parity. */
|
||||
export const INSPECT_WASM_ARTIFACT_CONTRACT = {
|
||||
name: "inspect_wasm_artifact",
|
||||
...toolContractMetadata("inspect_wasm_artifact"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Validate an explicit local WASM artifact with caller-supplied WABT 1.0.42, retain exact byte SHA-256, sections, upstream import/export WAT forms and decoded WAT inline as Evidence. Optionally associate selected JavaScript glue literals with explicit local candidates while preserving ambiguous URL/basename matches. Configure absolute REA_WABT_BIN_DIRECTORY. No installation, implicit fetch, WASM execution or original-source claim.",
|
||||
inputSchema: inspectWasmArtifactInputSchema,
|
||||
outputSchema: evidenceResultOf(wasmArtifactSchema),
|
||||
'Validate an explicit local WASM artifact with caller-supplied WABT 1.0.42. Omitted or complete detail returns exact byte SHA-256, sections, upstream import/export WAT forms and decoded WAT inline as Evidence. For counts, validation and WAT identity without WAT text, pass detail: "summary" on this first call; it retains the complete original Evidence and returns the same typed summary as inspect_analysis_view, avoiding oversized complete delivery. Read exact imports/exports or WAT pages with inspect_analysis_view using normalized_result.parent_evidence_id. Delivery selection does not change analysis, provider inputs or source identity. Optionally associate selected JavaScript glue literals with explicit local candidates while preserving ambiguous URL/basename matches. Configure absolute REA_WABT_BIN_DIRECTORY. No installation, implicit fetch, WASM execution or original-source claim.',
|
||||
inputSchema: wasmArtifactInspectionInputSchema,
|
||||
outputSchema: analysisDetailOutputSchemaOf(
|
||||
wasmArtifactSchema,
|
||||
wasmArtifactSummaryViewResultSchema,
|
||||
),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect a selected local WASM module",
|
||||
|
||||
@@ -127,14 +127,25 @@ describe("analysis snapshot contract", () => {
|
||||
] as const)(
|
||||
"preserves %s target and subject formats",
|
||||
(format, architecture) => {
|
||||
const target = {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable" as const,
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
};
|
||||
const target: BinaryTarget =
|
||||
format === "mach-o-universal"
|
||||
? {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
universalSlice: { offset: 0, size: 32 },
|
||||
}
|
||||
: {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
};
|
||||
const evidence = createEvidence(target, ANALYSIS_SNAPSHOT_PROVIDER, {
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
|
||||
@@ -302,6 +302,13 @@ export const artifactInventorySummaryViewResultSchema = z.strictObject({
|
||||
summary: inventorySummarySchema,
|
||||
});
|
||||
|
||||
/** Exact summary carrier for WASM inspection's optional delivery contract. */
|
||||
export const wasmArtifactSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
parent_operation: z.literal("inspect_wasm_artifact"),
|
||||
summary: wasmSummarySchema,
|
||||
});
|
||||
|
||||
/** Projected facts for one selected view of retained analysis Evidence. */
|
||||
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
z.strictObject({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
BinaryArchitecture,
|
||||
MipsElfMetadata,
|
||||
UniversalMachOSlice,
|
||||
} from "./binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "./dosMz.js";
|
||||
@@ -15,17 +16,22 @@ export type ExecutableMetadata =
|
||||
readonly mips: MipsElfMetadata;
|
||||
}
|
||||
| {
|
||||
readonly format:
|
||||
| "mach-o"
|
||||
| "mach-o-universal"
|
||||
| "elf"
|
||||
| "dos-mz"
|
||||
| "dos-com";
|
||||
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
|
||||
readonly architecture: Exclude<BinaryArchitecture, "mips">;
|
||||
readonly availableArchitectures: readonly Exclude<
|
||||
BinaryArchitecture,
|
||||
"mips"
|
||||
>[];
|
||||
readonly universalSlice?: never;
|
||||
}
|
||||
| {
|
||||
readonly format: "mach-o-universal";
|
||||
readonly architecture: Exclude<BinaryArchitecture, "mips">;
|
||||
readonly availableArchitectures: readonly Exclude<
|
||||
BinaryArchitecture,
|
||||
"mips"
|
||||
>[];
|
||||
readonly universalSlice: UniversalMachOSlice;
|
||||
}
|
||||
| {
|
||||
readonly format: "pe";
|
||||
@@ -157,10 +163,15 @@ const parseFatMachO = (
|
||||
return err(
|
||||
`truncated FAT slice: the ${preferred} slice ends at byte ${sliceEnd}; the file has ${fileSize}`,
|
||||
);
|
||||
const sliceOffset = Number(slice.offset);
|
||||
const sliceSize = Number(slice.size);
|
||||
if (!Number.isSafeInteger(sliceOffset) || !Number.isSafeInteger(sliceSize))
|
||||
return err(`FAT slice for ${preferred} exceeds addressable byte bounds`);
|
||||
return ok({
|
||||
format: "mach-o-universal",
|
||||
architecture: preferred,
|
||||
availableArchitectures: architectures,
|
||||
universalSlice: { offset: sliceOffset, size: sliceSize },
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -44,6 +44,12 @@ export interface MipsAbiFlags {
|
||||
readonly flags2: number;
|
||||
}
|
||||
|
||||
/** Byte range of the selected slice inside its universal Mach-O container. */
|
||||
export interface UniversalMachOSlice {
|
||||
readonly offset: number;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
interface BinaryTargetIdentity {
|
||||
readonly path: string;
|
||||
readonly sourcePath?: string;
|
||||
@@ -83,12 +89,15 @@ export type BinaryTarget =
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format:
|
||||
| "mach-o"
|
||||
| "mach-o-universal"
|
||||
| "elf"
|
||||
| "dos-mz"
|
||||
| "dos-com";
|
||||
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
|
||||
readonly universalSlice?: never;
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "mach-o-universal";
|
||||
/** Selected slice range a provider must analyze instead of the container. */
|
||||
readonly universalSlice: UniversalMachOSlice;
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
|
||||
@@ -121,15 +121,8 @@ export const inspectManagedNativeBoundariesBytes = (
|
||||
bytes: Buffer,
|
||||
target: BinaryTarget,
|
||||
): ManagedNativeBoundaryInspection => {
|
||||
let pe: ManagedPeLayout;
|
||||
try {
|
||||
pe = readManagedPeLayout(bytes);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ManagedReaderFailure)) throw cause;
|
||||
return emptyInspection(target, bytes, "malformed", {
|
||||
issues: [cause.issue],
|
||||
});
|
||||
}
|
||||
// An unmappable PE layout is invalid input for every managed operation.
|
||||
const pe = readManagedPeLayout(bytes);
|
||||
if (pe.cli === null)
|
||||
return emptyInspection(
|
||||
target,
|
||||
|
||||
@@ -22,6 +22,7 @@ import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
@@ -38,6 +39,7 @@ import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
|
||||
import { RegularFileCleanupFailure } from "../application/RegularFileRead.js";
|
||||
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
|
||||
import {
|
||||
hashManagedSource,
|
||||
managedCleanupError,
|
||||
@@ -135,6 +137,20 @@ class ManagedStaticClient implements AnalysisClient {
|
||||
if (cause instanceof AnalysisError) return err(cause);
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
// A PE header or section table the reader cannot map is malformed input.
|
||||
if (
|
||||
cause instanceof ManagedReaderFailure &&
|
||||
cause.issue.code !== "resource-limit"
|
||||
)
|
||||
return err(
|
||||
new AnalysisInputError(operation, { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: `Selected artifact ${this.target.path}: ${cause.issue.detail}`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
return err(
|
||||
new ProviderAdapterError(MANAGED_STATIC_PROVIDER.id, operation, {
|
||||
cause,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Vendored
+78
@@ -0,0 +1,78 @@
|
||||
declare module "frida" {
|
||||
export interface FridaMessage {
|
||||
readonly type: string;
|
||||
readonly payload?: unknown;
|
||||
readonly description?: string;
|
||||
readonly stack?: string;
|
||||
}
|
||||
|
||||
export type SignalHandler = (...args: never[]) => void;
|
||||
|
||||
export interface Signal<Handler extends SignalHandler> {
|
||||
connect(handler: Handler): void;
|
||||
disconnect(handler: Handler): void;
|
||||
}
|
||||
|
||||
export interface RemoteDeviceOptions {
|
||||
certificate?: string;
|
||||
origin?: string;
|
||||
token?: string;
|
||||
keepaliveInterval?: number;
|
||||
}
|
||||
|
||||
export interface SpawnOptions {
|
||||
argv?: string[];
|
||||
env?: Record<string, string>;
|
||||
envp?: Record<string, string>;
|
||||
cwd?: string;
|
||||
stdio?: "inherit" | "pipe";
|
||||
}
|
||||
|
||||
export interface Process {
|
||||
readonly pid: number;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface Script {
|
||||
readonly isDestroyed: boolean;
|
||||
readonly message: Signal<
|
||||
(message: FridaMessage, data: Buffer | null) => void
|
||||
>;
|
||||
load(): Promise<void>;
|
||||
unload(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
readonly pid: number;
|
||||
readonly detached: Signal<() => void>;
|
||||
isDetached(): boolean;
|
||||
createScript(
|
||||
source: string,
|
||||
options?: { readonly name?: string },
|
||||
): Promise<Script>;
|
||||
detach(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly type: string;
|
||||
enumerateProcesses(): Promise<Process[]>;
|
||||
getProcessByPid(pid: number): Promise<Process>;
|
||||
spawn(program: string, options?: SpawnOptions): Promise<number>;
|
||||
resume(pid: number): Promise<void>;
|
||||
attach(pid: number): Promise<Session>;
|
||||
}
|
||||
|
||||
export interface DeviceManager {
|
||||
enumerateDevices(): Promise<Device[]>;
|
||||
getDeviceById(id: string, timeout: number): Promise<Device>;
|
||||
addRemoteDevice(
|
||||
address: string,
|
||||
options?: RemoteDeviceOptions,
|
||||
): Promise<Device>;
|
||||
removeRemoteDevice(address: string): Promise<void>;
|
||||
}
|
||||
|
||||
export function getDeviceManager(): DeviceManager;
|
||||
}
|
||||
@@ -242,6 +242,7 @@ describe("Ghidra Mach-O slice support", () => {
|
||||
format: "mach-o-universal",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["x86_64", "arm64"],
|
||||
universalSlice: { offset: 0, size: 32 },
|
||||
};
|
||||
|
||||
expect(ghidra.inspectTargetSupport(universal)).toMatchObject({
|
||||
|
||||
@@ -11,6 +11,7 @@ it("routes physical universal Mach-O containers through Hopper's FAT loader", ()
|
||||
format: "mach-o-universal",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["x86_64", "arm64"],
|
||||
universalSlice: { offset: 0, size: 32 },
|
||||
},
|
||||
"fat64",
|
||||
);
|
||||
|
||||
@@ -506,7 +506,8 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
onObserved?.(raw);
|
||||
if (
|
||||
!sameIdaHostPath(metadata.input_path, this.#workspace.inputPath) ||
|
||||
(await idaFileDigest(this.#workspace.inputPath)) !== this.target.sha256
|
||||
(await idaFileDigest(this.#workspace.inputPath)) !==
|
||||
this.#workspace.inputSha256
|
||||
)
|
||||
throw new AnalysisProtocolError(
|
||||
"IDA headless input identity changed after target admission.",
|
||||
|
||||
+55
-8
@@ -1,6 +1,6 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream, constants } from "node:fs";
|
||||
import { copyFile, realpath } from "node:fs/promises";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { open, realpath } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, join, normalize } from "node:path";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
@@ -23,6 +23,7 @@ export const sameIdaHostPath = (left: string, right: string): boolean =>
|
||||
/** Private input copy isolates upstream database and sidecar writes from the original. */
|
||||
export class IdaWorkspace {
|
||||
readonly sessionId = `rea-${randomUUID()}`;
|
||||
#inputSha256: string | undefined;
|
||||
private constructor(
|
||||
private readonly runtime: PrivateRuntimeRoot,
|
||||
readonly inputPath: string,
|
||||
@@ -34,6 +35,11 @@ export class IdaWorkspace {
|
||||
return this.runtime.path;
|
||||
}
|
||||
|
||||
/** SHA-256 of the private input bytes copyInput admitted; undefined until prepared. */
|
||||
get inputSha256(): string | undefined {
|
||||
return this.#inputSha256;
|
||||
}
|
||||
|
||||
/** Allocate a protected workspace so its owner can retain it before input preparation. */
|
||||
static async allocate(
|
||||
target: BinaryTarget,
|
||||
@@ -49,13 +55,54 @@ export class IdaWorkspace {
|
||||
return new IdaWorkspace(runtime, inputPath, target);
|
||||
}
|
||||
|
||||
/** Copy and verify admitted bytes after the session owns this workspace's cleanup. */
|
||||
/**
|
||||
* Copy and verify admitted bytes after the session owns this workspace's
|
||||
* cleanup. Universal Mach-O containers are thinned to the selected slice so
|
||||
* the upstream engine analyzes the architecture admission reported; the
|
||||
* whole-source digest still anchors the copy against admission-time changes.
|
||||
*/
|
||||
async copyInput(): Promise<void> {
|
||||
await copyFile(this.target.path, this.inputPath, constants.COPYFILE_EXCL);
|
||||
if ((await idaFileDigest(this.inputPath)) !== this.target.sha256)
|
||||
throw new AnalysisProtocolError(
|
||||
"IDA target changed between admission and the private input copy; reopen the target.",
|
||||
);
|
||||
const slice =
|
||||
this.target.format === "mach-o-universal"
|
||||
? this.target.universalSlice
|
||||
: undefined;
|
||||
const source = await open(this.target.path, "r");
|
||||
try {
|
||||
const input = await open(this.inputPath, "wx");
|
||||
try {
|
||||
const sourceHash = createHash("sha256");
|
||||
const inputHash = createHash("sha256");
|
||||
const chunk = Buffer.allocUnsafe(64 * 1024);
|
||||
let position = 0;
|
||||
for (;;) {
|
||||
const observed = await source.read(chunk, 0, chunk.length, position);
|
||||
if (observed.bytesRead === 0) break;
|
||||
const bytes = chunk.subarray(0, observed.bytesRead);
|
||||
sourceHash.update(bytes);
|
||||
const start =
|
||||
slice === undefined ? position : Math.max(position, slice.offset);
|
||||
const end =
|
||||
slice === undefined
|
||||
? position + bytes.length
|
||||
: Math.min(position + bytes.length, slice.offset + slice.size);
|
||||
const admitted = bytes.subarray(start - position, end - position);
|
||||
if (admitted.length > 0) {
|
||||
inputHash.update(admitted);
|
||||
await input.write(admitted);
|
||||
}
|
||||
position += observed.bytesRead;
|
||||
}
|
||||
if (sourceHash.digest("hex") !== this.target.sha256)
|
||||
throw new AnalysisProtocolError(
|
||||
"IDA target changed between admission and the private input copy; reopen the target.",
|
||||
);
|
||||
this.#inputSha256 = inputHash.digest("hex");
|
||||
} finally {
|
||||
await input.close();
|
||||
}
|
||||
} finally {
|
||||
await source.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete only this object's privately allocated directory after worker cleanup. */
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
|
||||
import { parseExecutableHeader } from "../domain/binaryTarget.js";
|
||||
import { fat } from "../domain/binaryTarget.fixture.js";
|
||||
import {
|
||||
createIdaTarget,
|
||||
RecordingIdaMcp,
|
||||
} from "../../tests/fixtures/idaMcp.js";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { IdaSessionClient } from "./IdaSessionClient.js";
|
||||
import { IdaWorkspace } from "./IdaWorkspace.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const root of roots.splice(0)) {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/** Write a two-slice universal fixture and resolve it for the given host. */
|
||||
const universalTarget = async (hostArchitecture: "arm64" | "x64") => {
|
||||
const directory = await createTestTempDirectory("rea-ida-thin-");
|
||||
roots.push(directory);
|
||||
const path = join(directory, "universal");
|
||||
const bytes = fat([0x01000007, 0x0100000c]);
|
||||
await writeFile(path, bytes);
|
||||
const resolved = await parseBinaryTarget(path, { hostArchitecture });
|
||||
if (!resolved.ok) throw resolved.error;
|
||||
if (resolved.value.format !== "mach-o-universal")
|
||||
throw new Error("the universal fixture did not resolve as a FAT container");
|
||||
return { bytes, target: resolved.value };
|
||||
};
|
||||
|
||||
describe("IDA workspace input thinning", () => {
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"thins the selected arm64 slice into the private headless input",
|
||||
async () => {
|
||||
const { bytes, target } = await universalTarget("arm64");
|
||||
const workspace = await IdaWorkspace.allocate(target);
|
||||
roots.push(workspace.directory);
|
||||
await workspace.copyInput();
|
||||
|
||||
const input = await readFile(workspace.inputPath);
|
||||
const { offset, size } = target.universalSlice;
|
||||
expect(offset).toBeGreaterThan(0);
|
||||
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
|
||||
expect(input.length).toBe(size);
|
||||
expect(input.readUInt32BE(0)).toBe(0xfeedfacf);
|
||||
expect(input.readUInt32BE(4)).toBe(0x0100000c);
|
||||
expect(parseExecutableHeader(input, "arm64")).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: "mach-o", architecture: "arm64" },
|
||||
});
|
||||
expect(createHash("sha256").update(input).digest("hex")).toBe(
|
||||
workspace.inputSha256,
|
||||
);
|
||||
await workspace.remove();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"thins the x86_64 slice when the host is intel",
|
||||
async () => {
|
||||
const { bytes, target } = await universalTarget("x64");
|
||||
const workspace = await IdaWorkspace.allocate(target);
|
||||
roots.push(workspace.directory);
|
||||
await workspace.copyInput();
|
||||
|
||||
const input = await readFile(workspace.inputPath);
|
||||
const { offset, size } = target.universalSlice;
|
||||
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
|
||||
expect(input.readUInt32BE(4)).toBe(0x01000007);
|
||||
await workspace.remove();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a whole-file copy for thin targets", async () => {
|
||||
const { root, target } = await createIdaTarget("arm64");
|
||||
roots.push(root);
|
||||
const workspace = await IdaWorkspace.allocate(target, root);
|
||||
roots.push(workspace.directory);
|
||||
await workspace.copyInput();
|
||||
|
||||
const input = await readFile(workspace.inputPath);
|
||||
const source = await readFile(target.path);
|
||||
expect(input.equals(source)).toBe(true);
|
||||
expect(workspace.inputSha256).toBe(target.sha256);
|
||||
await workspace.remove();
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects a universal source that changed after admission",
|
||||
async () => {
|
||||
const { target } = await universalTarget("arm64");
|
||||
const workspace = await IdaWorkspace.allocate({
|
||||
...target,
|
||||
sha256: "a".repeat(64),
|
||||
});
|
||||
roots.push(workspace.directory);
|
||||
await expect(workspace.copyInput()).rejects.toThrow("target changed");
|
||||
await workspace.remove();
|
||||
},
|
||||
);
|
||||
|
||||
it("binds a headless session to the thinned input identity", async () => {
|
||||
const { target } = await universalTarget("arm64");
|
||||
const root = await createTestTempDirectory("rea-ida-thin-root-");
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "headless");
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "headless",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
expect((await client.execute("health", {})).ok).toBe(true);
|
||||
const open = producer.calls.find(({ name }) => name === "idb_open");
|
||||
expect(String(open?.args.input_path)).toContain("universal");
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -82,6 +82,7 @@ export const run = async (
|
||||
createShutdown({
|
||||
handle: transport.handle,
|
||||
closeAndroid: transport.closeAndroid,
|
||||
closeOptionalProviders: transport.closeOptionalProviders,
|
||||
session,
|
||||
dependencies,
|
||||
serverLogger,
|
||||
|
||||
@@ -16,6 +16,7 @@ interface ShutdownCleanupOwner {
|
||||
export const createShutdown = (input: {
|
||||
readonly handle: StdioServerHandle;
|
||||
readonly closeAndroid?: () => Promise<void>;
|
||||
readonly closeOptionalProviders?: () => Promise<void>;
|
||||
readonly session: BinarySession;
|
||||
readonly dependencies: RuntimeDependencies;
|
||||
readonly serverLogger: Logger;
|
||||
@@ -30,6 +31,9 @@ export const createShutdown = (input: {
|
||||
...(input.closeAndroid === undefined
|
||||
? []
|
||||
: [{ close: input.closeAndroid, closed: false }]),
|
||||
...(input.closeOptionalProviders === undefined
|
||||
? []
|
||||
: [{ close: input.closeOptionalProviders, closed: false }]),
|
||||
{
|
||||
close: async () => {
|
||||
const closed = await session.close({ retainProviderDocuments: true });
|
||||
|
||||
@@ -31,6 +31,7 @@ export const startMcpTransport = async (
|
||||
readonly ok: true;
|
||||
readonly handle: StdioServerHandle;
|
||||
readonly closeAndroid: () => Promise<void>;
|
||||
readonly closeOptionalProviders: () => Promise<void>;
|
||||
}
|
||||
| { readonly ok: false }
|
||||
> => {
|
||||
@@ -62,6 +63,11 @@ export const startMcpTransport = async (
|
||||
for (const result of results)
|
||||
if (result.status === "rejected") throw result.reason;
|
||||
};
|
||||
// Optional providers are shared by every server instance the SDK creates,
|
||||
// including a discarded discovery probe, so only process shutdown closes them.
|
||||
const closeOptionalProviders = async (): Promise<void> => {
|
||||
await optionalProviders.browserScenarioCapture?.close?.();
|
||||
};
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
handle = dependencies.serve(
|
||||
@@ -124,5 +130,5 @@ export const startMcpTransport = async (
|
||||
}
|
||||
return { ok: false };
|
||||
}
|
||||
return { ok: true, handle, closeAndroid };
|
||||
return { ok: true, handle, closeAndroid, closeOptionalProviders };
|
||||
};
|
||||
|
||||
@@ -15,6 +15,8 @@ import { registerGoTools } from "./registerGoTools.js";
|
||||
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
|
||||
import { registerAnalysisViewTool } from "./registerAnalysisViewTool.js";
|
||||
import { registerBinaryDiagnosticsTools } from "./registerBinaryDiagnosticsTools.js";
|
||||
import { FridaInstrumentationManager } from "../frida/FridaInstrumentationManager.js";
|
||||
import { registerFridaTools } from "./registerFridaTools.js";
|
||||
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
|
||||
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
|
||||
import { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
@@ -36,6 +38,7 @@ import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioC
|
||||
import type { ElectronActiveObservationPort } from "../application/javascript/ElectronActiveObservationPort.js";
|
||||
import type { ElectronObservationPort } from "../application/javascript/ElectronObservationPort.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "../application/javascript/JavaScriptRuntimeObservationPort.js";
|
||||
import type { FridaInstrumentationPort } from "../application/frida/FridaInstrumentationPort.js";
|
||||
import type { OptionalProviderLoadFailures } from "../application/OptionalObservationProviders.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
@@ -130,6 +133,7 @@ export interface CreateServerOptions {
|
||||
readonly electronObservation?: ElectronObservationPort;
|
||||
readonly electronActiveObservation?: ElectronActiveObservationPort;
|
||||
readonly javascriptRuntimeObservation?: JavaScriptRuntimeObservationPort;
|
||||
readonly fridaInstrumentation?: FridaInstrumentationPort;
|
||||
readonly availabilityPolicy?: () => AvailabilityPolicy;
|
||||
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
|
||||
}
|
||||
@@ -138,13 +142,14 @@ const installSessionToolAvailability = (
|
||||
session: BinarySessionPort | undefined,
|
||||
options: CreateServerOptions,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
fridaInstrumentation: FridaInstrumentationPort,
|
||||
) => {
|
||||
if (session === undefined) return undefined;
|
||||
const linux = process.platform === "linux";
|
||||
const linuxX64 = linux && process.arch === "x64";
|
||||
const pwntools =
|
||||
linuxX64 && isAbsolute(environment.REA_PWNTOOLS_PYTHON ?? "");
|
||||
const policy = sessionAvailabilityPolicy(options.availabilityPolicy, {
|
||||
const basePolicy = sessionAvailabilityPolicy(options.availabilityPolicy, {
|
||||
optionalProviderLoadFailures: options.optionalProviderLoadFailures,
|
||||
optionalFeatures: {
|
||||
wasmArtifactEnabled:
|
||||
@@ -174,6 +179,21 @@ const installSessionToolAvailability = (
|
||||
options.javascriptRuntimeObservation !== undefined,
|
||||
},
|
||||
});
|
||||
const policy = (): AvailabilityPolicy => {
|
||||
const value = basePolicy();
|
||||
const fridaFailure =
|
||||
options.optionalProviderLoadFailures?.fridaInstrumentation ??
|
||||
fridaInstrumentation.availabilityFailure?.();
|
||||
return fridaFailure === undefined
|
||||
? value
|
||||
: {
|
||||
...value,
|
||||
optionalProviderLoadFailures: {
|
||||
...value.optionalProviderLoadFailures,
|
||||
fridaInstrumentation: fridaFailure,
|
||||
},
|
||||
};
|
||||
};
|
||||
return {
|
||||
policy,
|
||||
};
|
||||
@@ -246,6 +266,8 @@ export const createServer = (
|
||||
);
|
||||
const android =
|
||||
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
|
||||
const fridaInstrumentation =
|
||||
options.fridaInstrumentation ?? new FridaInstrumentationManager();
|
||||
const wasmArtifact = wasmArtifactModule.create(
|
||||
environment,
|
||||
options.wasmArtifact,
|
||||
@@ -260,6 +282,7 @@ export const createServer = (
|
||||
const closeProviders = (): Promise<void> => {
|
||||
providerClose ??= Promise.allSettled([
|
||||
android.close(),
|
||||
fridaInstrumentation.closeAll(),
|
||||
wasmArtifact.close(),
|
||||
apktool.close(),
|
||||
jeb.close(),
|
||||
@@ -270,7 +293,6 @@ export const createServer = (
|
||||
javascriptRecovery.close?.() ?? Promise.resolve(),
|
||||
artifactResources.close(),
|
||||
firmwareAnalysis.close(),
|
||||
options.browserScenarioCapture?.close?.() ?? Promise.resolve(),
|
||||
])
|
||||
.then((results) => {
|
||||
const failures = results.flatMap((result) =>
|
||||
@@ -289,6 +311,7 @@ export const createServer = (
|
||||
session,
|
||||
options,
|
||||
environment,
|
||||
fridaInstrumentation,
|
||||
);
|
||||
const toolLogger = logger.child({ layer: "server" });
|
||||
const {
|
||||
@@ -312,6 +335,15 @@ export const createServer = (
|
||||
artifactResources,
|
||||
};
|
||||
registerBinaryAnalysisTools(toolContext);
|
||||
registerFridaTools(
|
||||
server,
|
||||
fridaInstrumentation,
|
||||
toolLogger,
|
||||
delivery,
|
||||
session === undefined
|
||||
? undefined
|
||||
: (input) => session.recordEvidence(input),
|
||||
);
|
||||
const previousOnclose = server.server.onclose;
|
||||
server.server.onclose = () => {
|
||||
previousOnclose?.();
|
||||
@@ -454,6 +486,7 @@ const registerConfiguredAnalysisTools = (
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
evidenceById,
|
||||
);
|
||||
registerEvmTools(
|
||||
server,
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { FridaInstrumentationService } from "../application/frida/FridaInstrumentationService.js";
|
||||
import type { FridaInstrumentationPort } from "../application/frida/FridaInstrumentationPort.js";
|
||||
import type { FridaRemoteConnection } from "../application/frida/FridaInstrumentationPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { ToolResultDelivery } from "./toolResult.js";
|
||||
|
||||
/** Register Frida device discovery and persistent instrumentation operations. */
|
||||
export const registerFridaTools = (
|
||||
server: McpServer,
|
||||
provider: FridaInstrumentationPort,
|
||||
logger: Logger,
|
||||
delivery: ToolResultDelivery,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
): void => {
|
||||
const service = new FridaInstrumentationService(provider);
|
||||
const listDevices = toolContract("list_frida_devices");
|
||||
const listProcesses = toolContract("list_frida_processes");
|
||||
const start = toolContract("start_frida_session");
|
||||
const load = toolContract("load_frida_script");
|
||||
const resume = toolContract("resume_frida_session");
|
||||
const unload = toolContract("unload_frida_script");
|
||||
const status = toolContract("frida_session_status");
|
||||
const close = toolContract("close_frida_session");
|
||||
const instrument = toolContract("instrument_with_frida");
|
||||
|
||||
server.registerTool(
|
||||
listDevices.name,
|
||||
toolRegistrationOptions(listDevices),
|
||||
async (input) => {
|
||||
const result = await logToolExecution(logger, listDevices.name, () =>
|
||||
service.listDevices(remoteConnection(input.remote)),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: jsonValueSchema.parse({
|
||||
devices: result.value.devices.map((device) => ({
|
||||
device_id: device.deviceId,
|
||||
name: device.name,
|
||||
type: device.type,
|
||||
})),
|
||||
cleanup_error: result.value.cleanupError,
|
||||
}),
|
||||
},
|
||||
listDevices,
|
||||
)
|
||||
: delivery.toCallToolResult(result, listDevices);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
listProcesses.name,
|
||||
toolRegistrationOptions(listProcesses),
|
||||
async (input) => {
|
||||
const remote = remoteConnection(input.remote);
|
||||
const result = await logToolExecution(logger, listProcesses.name, () =>
|
||||
service.listProcesses({
|
||||
...(input.device_id === undefined
|
||||
? {}
|
||||
: { deviceId: input.device_id }),
|
||||
...(remote === undefined ? {} : { remote }),
|
||||
}),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: jsonValueSchema.parse({
|
||||
device_id: result.value.deviceId,
|
||||
processes: result.value.processes,
|
||||
cleanup_error: result.value.cleanupError,
|
||||
}),
|
||||
},
|
||||
listProcesses,
|
||||
)
|
||||
: delivery.toCallToolResult(result, listProcesses);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
start.name,
|
||||
toolRegistrationOptions(start),
|
||||
async (input, context: ServerContext) => {
|
||||
const remote = remoteConnection(input.remote);
|
||||
const selected = {
|
||||
...(input.device_id === undefined ? {} : { deviceId: input.device_id }),
|
||||
...(remote === undefined ? {} : { remote }),
|
||||
};
|
||||
const result = await logToolExecution(logger, start.name, () =>
|
||||
input.mode === "attach" && input.pid !== undefined
|
||||
? service.startSession(
|
||||
{
|
||||
...selected,
|
||||
mode: input.mode,
|
||||
pid: input.pid,
|
||||
},
|
||||
context.mcpReq.signal,
|
||||
)
|
||||
: input.mode === "spawn" && input.program !== undefined
|
||||
? service.startSession(
|
||||
{
|
||||
...selected,
|
||||
mode: input.mode,
|
||||
program: input.program,
|
||||
...(input.argv === undefined ? {} : { argv: input.argv }),
|
||||
},
|
||||
context.mcpReq.signal,
|
||||
)
|
||||
: Promise.resolve({
|
||||
ok: false as const,
|
||||
error: new AnalysisInputError(start.name),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) {
|
||||
recordPartialEvidence(result.error, recordEvidence);
|
||||
return delivery.toCallToolResult(result, start);
|
||||
}
|
||||
return delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: jsonValueSchema.parse(sessionOutput(result.value)),
|
||||
},
|
||||
start,
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
load.name,
|
||||
toolRegistrationOptions(load),
|
||||
async (input) => {
|
||||
const result = await logToolExecution(logger, load.name, () =>
|
||||
input.source_kind === "inline" && input.source !== undefined
|
||||
? service.loadScript(input.session_id, {
|
||||
sourceKind: "inline",
|
||||
source: input.source,
|
||||
})
|
||||
: input.source_kind === "file" && input.path !== undefined
|
||||
? service.loadScript(input.session_id, {
|
||||
sourceKind: "file",
|
||||
path: input.path,
|
||||
})
|
||||
: Promise.resolve({
|
||||
ok: false as const,
|
||||
error: new AnalysisInputError(load.name),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return delivery.toCallToolResult(result, load);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
load,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
resume.name,
|
||||
toolRegistrationOptions(resume),
|
||||
async (input) => {
|
||||
const result = await logToolExecution(logger, resume.name, () =>
|
||||
service.resumeSession(input.session_id),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult(
|
||||
{ ok: true, value: { state: "running" } },
|
||||
resume,
|
||||
)
|
||||
: delivery.toCallToolResult(result, resume);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
unload.name,
|
||||
toolRegistrationOptions(unload),
|
||||
async (input) => {
|
||||
const result = await logToolExecution(logger, unload.name, () =>
|
||||
service.unloadScript(input.session_id, input.script_id),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult(
|
||||
{ ok: true, value: { unloaded: true } },
|
||||
unload,
|
||||
)
|
||||
: delivery.toCallToolResult(result, unload);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
status.name,
|
||||
toolRegistrationOptions(status),
|
||||
async (input) => {
|
||||
const evidence = service.statusEvidence(input.session_id);
|
||||
if (evidence === undefined)
|
||||
return delivery.toCallToolResult(
|
||||
{
|
||||
ok: false as const,
|
||||
error: new AnalysisInputError(status.name),
|
||||
},
|
||||
status,
|
||||
);
|
||||
return delivery.toEvidenceToolResult(
|
||||
evidence,
|
||||
status,
|
||||
recordEvidence?.(evidence),
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
close.name,
|
||||
toolRegistrationOptions(close),
|
||||
async (input) => {
|
||||
const result = await logToolExecution(logger, close.name, () =>
|
||||
service.closeSession(input.session_id),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult(
|
||||
{ ok: true, value: { target_state: "unknown" } },
|
||||
close,
|
||||
)
|
||||
: delivery.toCallToolResult(result, close);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
instrument.name,
|
||||
toolRegistrationOptions(instrument),
|
||||
async (input, context: ServerContext) => {
|
||||
const remote = remoteConnection(input.remote);
|
||||
const selected = {
|
||||
...(input.device_id === undefined ? {} : { deviceId: input.device_id }),
|
||||
...(remote === undefined ? {} : { remote }),
|
||||
};
|
||||
const source =
|
||||
input.source_kind === "inline" && input.source !== undefined
|
||||
? { sourceKind: "inline" as const, source: input.source }
|
||||
: input.source_kind === "file" && input.path !== undefined
|
||||
? { sourceKind: "file" as const, path: input.path }
|
||||
: undefined;
|
||||
if (source === undefined)
|
||||
return delivery.toCallToolResult(
|
||||
{ ok: false, error: new AnalysisInputError(instrument.name) },
|
||||
instrument,
|
||||
);
|
||||
const operation =
|
||||
input.mode === "attach" && input.pid !== undefined
|
||||
? service.instrument(
|
||||
{
|
||||
...selected,
|
||||
mode: "attach",
|
||||
pid: input.pid,
|
||||
source,
|
||||
durationMs: input.duration_ms,
|
||||
},
|
||||
context.mcpReq.signal,
|
||||
)
|
||||
: input.mode === "spawn" && input.program !== undefined
|
||||
? service.instrument(
|
||||
{
|
||||
...selected,
|
||||
mode: "spawn",
|
||||
program: input.program,
|
||||
...(input.argv === undefined ? {} : { argv: input.argv }),
|
||||
source,
|
||||
durationMs: input.duration_ms,
|
||||
},
|
||||
context.mcpReq.signal,
|
||||
)
|
||||
: Promise.resolve({
|
||||
ok: false as const,
|
||||
error: new AnalysisInputError(instrument.name),
|
||||
});
|
||||
const result = await logToolExecution(
|
||||
logger,
|
||||
instrument.name,
|
||||
() => operation,
|
||||
);
|
||||
if (!result.ok) {
|
||||
recordPartialEvidence(result.error, recordEvidence);
|
||||
return delivery.toCallToolResult(result, instrument);
|
||||
}
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value.evidence,
|
||||
instrument,
|
||||
recordEvidence?.(result.value.evidence),
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const recordPartialEvidence = (
|
||||
error: { readonly partialObservation?: unknown },
|
||||
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
|
||||
): void => {
|
||||
if (error.partialObservation === undefined) return;
|
||||
const parsed = evidenceSchema.safeParse(error.partialObservation);
|
||||
if (parsed.success) recordEvidence?.(parsed.data);
|
||||
};
|
||||
|
||||
const remoteConnection = (
|
||||
input:
|
||||
| {
|
||||
readonly address: string;
|
||||
readonly token?: string | undefined;
|
||||
readonly certificate?: string | undefined;
|
||||
readonly origin?: string | undefined;
|
||||
readonly keepalive_interval?: number | undefined;
|
||||
}
|
||||
| undefined,
|
||||
): FridaRemoteConnection | undefined =>
|
||||
input === undefined
|
||||
? undefined
|
||||
: {
|
||||
address: input.address,
|
||||
...(typeof input.token === "string" ? { token: input.token } : {}),
|
||||
...(typeof input.certificate === "string"
|
||||
? { certificate: input.certificate }
|
||||
: {}),
|
||||
...(typeof input.origin === "string" ? { origin: input.origin } : {}),
|
||||
...(typeof input.keepalive_interval === "number"
|
||||
? { keepaliveInterval: input.keepalive_interval }
|
||||
: {}),
|
||||
};
|
||||
|
||||
const sessionOutput = (session: {
|
||||
readonly sessionId: string;
|
||||
readonly deviceId: string;
|
||||
readonly target: string;
|
||||
readonly pid: number;
|
||||
readonly mode: "attach" | "spawn";
|
||||
readonly state: "paused" | "running" | "detached";
|
||||
}) => ({
|
||||
session_id: session.sessionId,
|
||||
device_id: session.deviceId,
|
||||
target: session.target,
|
||||
pid: session.pid,
|
||||
mode: session.mode,
|
||||
state: session.state,
|
||||
});
|
||||
@@ -2,6 +2,10 @@ import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
|
||||
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
|
||||
import { summarizeRetainedAnalysis } from "../application/analysisView/AnalysisViewService.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
import type { Logger } from "pino";
|
||||
import { createEvidenceToolHandler } from "./contractToolHandler.js";
|
||||
@@ -15,11 +19,31 @@ export const registerWasmTools = (
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
evidenceById?: EvidenceLookup,
|
||||
): void => {
|
||||
const contract = wasmArtifactModule.contract;
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.inspect(input, options),
|
||||
async (rawInput, options) => {
|
||||
const parsed = contract.inputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(
|
||||
contract.name,
|
||||
parsed.error.issues,
|
||||
rawInput,
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
);
|
||||
const { detail, ...input } = parsed.data;
|
||||
const inspected = await service.inspect(input, options);
|
||||
return detail === "summary" && inspected.ok
|
||||
? summarizeRetainedAnalysis(inspected.value, {
|
||||
recordEvidence,
|
||||
evidenceById,
|
||||
})
|
||||
: inspected;
|
||||
},
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
|
||||
Reference in New Issue
Block a user