Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(frida): preserve script evidence through cancellation and decoding
morluto048d70755ea9
diff --git a/docs/frida-instrumentation.md b/docs/frida-instrumentation.mdindex 718af30c2..69866fb2e 100644--- a/docs/frida-instrumentation.md+++ b/docs/frida-instrumentation.md@@ -8,6 +8,6 @@ MCP exposes `list_frida_devices`, `list_frida_processes`, `start_frida_session`,Failed startup cleanup retains acquired Frida handles, including a paused spawn that has not attached, for later cleanup retries. Its remote connection stays leased until session detach and target resume complete. CLI commands await provider cleanup before returning; MCP retains these resources for cleanup when its server closes. Server shutdown stops admitting new Frida operations and waits for admitted startup, discovery, and queued work before releasing their resources. A failed cleanup remains reported and can be retried by closing the server again, rather than treating an unregistered session as fully released.-Frida scripts execute inside the selected target with that process's memory, filesystem, and network authority. Message capture is bounded to 16 MiB and reports truncation. Script source is not stored in Evidence; its selected path and SHA-256 digest are. Evidence retains non-authentication target selection such as device or endpoint, mode, program or PID, and spawn arguments. Authentication values remain excluded. Results report the observed session and messages, while unsupported platform metadata remains unknown. A request cancelled before a Frida operation starts has no provider effects. If cancellation arrives during a native Frida call, REA waits for that call to return, then closes any session it created and returns the observed session as a partial observation. A cancelled script load on an existing session releases only its new script before queued operations can run; the session and previously loaded scripts remain available. Once the provider commits a successful load, later request cancellation does not unload that script; use `unload_frida_script` to release it. If script cleanup fails, the script remains owned and a paused target cannot resume until the pending instrumentation is released. Queued script loads, resumes, and unloads check cancellation before dispatching native effects. Cancellation Evidence separately reports whether a target resume was observed, whether instrumentation cleanup completed, and that final target liveness remains unknown. REA does not kill the target. Remote discovery retains its observations and reports a separate cleanup error if the temporary connection cannot be removed.+Frida scripts execute inside the selected target with that process's memory, filesystem, and network authority. Message capture is bounded to 16 MiB and reports truncation. Script source is not stored in Evidence; its selected path and SHA-256 digest are. For a file, `source_sha256` identifies the original selected bytes. Invalid UTF-8 continues to use replacement decoding; Evidence then records that limitation and `raw_result.source_representation` with the encoding, decoding mode, and `loaded_source_sha256` of the UTF-8 string passed to Frida. Valid UTF-8 files and inline scripts do not need this additional representation fact. Evidence retains non-authentication target selection such as device or endpoint, mode, program or PID, and spawn arguments. Authentication values remain excluded. Results report the observed session and messages, while unsupported platform metadata remains unknown. A request cancelled before a Frida operation starts has no provider effects. If cancellation arrives during a native Frida call, REA waits for that call to return, then closes any session it created and returns the observed session as a partial observation. A cancelled script load on an existing session releases only its new script before queued operations can run; the session and previously loaded scripts remain available. If cancellation is observed when the native call returns, partial Evidence retains the source identity and captured messages even if that call rejects, including messages emitted during awaited cleanup. The caller's cancellation reason remains primary and a native rejection is retained as a sanitized diagnostic. A failure already observed before cleanup stays primary if cancellation arrives during cleanup. The cancellation cutoff is REA's observation of native completion, rather than a claim about unobservable native event order. `script_id` is REA's load-attempt identity. When creation rejects without returning a handle, `script_cleanup: "no_handle"` means REA acquired no handle to unload; it does not prove that the engine performed no work. Once the provider commits a successful load, later request cancellation does not unload that script; use `unload_frida_script` to release it. If script cleanup fails, the script remains owned and a paused target cannot resume until the pending instrumentation is released. Queued script loads, resumes, and unloads check cancellation before dispatching native effects. Cancellation Evidence separately reports whether a target resume was observed, whether instrumentation cleanup completed, and that final target liveness remains unknown. REA does not kill the target. Remote discovery retains its observations and reports a separate cleanup error if the temporary connection cannot be removed.The [Frida Core API](https://frida.re/docs/frida-core-api/) documents device management, sessions, and script loading; the [JavaScript API](https://frida.re/docs/javascript-api/) documents target-side instrumentation. [Luma](https://luma.frida.re/) is Frida's standalone GUI; REA does not automate or control it. `npm run verify:frida` requires a Linux host with the optional Frida binding and uses a short-lived local Node.js fixture created by the verifier. Add `-- --address HOST:PORT --pid PID` to run the separate remote attach lane against a caller-selected target. Mock tests do not establish real device/server compatibility.diff --git a/src/application/frida/FridaInstrumentationManager.test.ts b/src/application/frida/FridaInstrumentationManager.test.tsindex 86733cf59..030e8f942 100644--- a/src/application/frida/FridaInstrumentationManager.test.ts+++ b/src/application/frida/FridaInstrumentationManager.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, onTestFinished } from "vitest";+import { createDeferred } from "../../../tests/fixtures/binarySession.js";import type {Device,@@ -9,7 +10,11 @@ import type {Session,Signal,} from "frida";-import { AnalysisInputError } from "../../domain/analysisErrorCore.js";+import { FridaScriptLoadCancelledError } from "./FridaInstrumentationPort.js";+import {+ AnalysisCapabilityUnavailableError,+ AnalysisInputError,+} from "../../domain/analysisErrorCore.js";import { FridaInstrumentationManager } from "../../frida/FridaInstrumentationManager.js";const signal = <Handler extends (...args: never[]) => void>() => {@@ -1345,3 +1350,96 @@ it("names the unknown session or script ID it rejects", async () => {});await manager.closeAll();});++it.each([false, true])(+ "retains messages emitted during cancelled script cleanup after native rejection=%s",+ async (rejectNative) => {+ const { bindings, manager, started } = await startLocalAttachedSession();+ onTestFinished(() => manager.closeAll());+ if (!started.ok) throw started.error;+ const session = bindings.device.session;+ const entered = createDeferred<void>();+ const held = createDeferred<void>();+ onTestFinished(() => held.resolve());+ session.onScriptLoadStarted = entered.resolve;+ session.scriptLoadGate = held.promise;+ const nativeFailure = new Error("native load failed");+ if (rejectNative) session.nextLoadFailure = nativeFailure;+ const controller = new AbortController();+ const reason = new Error("cancel before native completion");+ const loading = manager.loadScript(+ started.value.sessionId,+ { sourceKind: "inline", source: "send('marker')" },+ controller.signal,+ );+ await entered.promise;+ const script = session.scripts[0];+ if (script === undefined) throw new Error("Missing admitted script");+ const unload = script.unload.bind(script);+ script.unload = async () => {+ script.message.emit({ type: "send", payload: "during cleanup" }, null);+ script.message.emit(+ { type: "send", description: "x".repeat(40_000) },+ null,+ );+ await unload();+ };+ controller.abort(reason);+ held.resolve();+ const loaded = await loading;+ if (loaded.ok) throw new Error("Cancelled load succeeded");+ expect(loaded.error).toBeInstanceOf(FridaScriptLoadCancelledError);+ if (!(loaded.error instanceof FridaScriptLoadCancelledError))+ throw loaded.error;+ expect(loaded.error.cause).toBe(reason);+ expect(loaded.error.script.messages).toContainEqual(+ expect.objectContaining({ payload: "during cleanup" }),+ );+ expect(loaded.error.script.messagesTruncated).toBe(true);+ expect(loaded.error.diagnostics).toEqual(+ rejectNative ? { native_failure: nativeFailure.message } : undefined,+ );+ expect(loaded.error.cleanupIncomplete).toBe(false);+ expect(script.isDestroyed).toBe(true);+ expect(manager.status(started.value.sessionId)?.scripts).toEqual([]);+ expect(session.isDetached()).toBe(false);+ },+);++it("preserves a native rejection observed before cancellation during script cleanup", async () => {+ const { bindings, manager, started } = await startLocalAttachedSession();+ onTestFinished(() => manager.closeAll());+ if (!started.ok) throw started.error;+ const session = bindings.device.session;+ const entered = createDeferred<void>();+ const held = createDeferred<void>();+ onTestFinished(() => held.resolve());+ const create = session.createScript.bind(session);+ session.createScript = async () => {+ const script = await create();+ script.unload = async () => {+ entered.resolve();+ await held.promise;+ const owned = session.scripts[0];+ if (owned !== undefined) owned.isDestroyed = true;+ };+ return script;+ };+ const failure = new Error("native rejection first");+ session.nextLoadFailure = failure;+ const controller = new AbortController();+ const loading = manager.loadScript(+ started.value.sessionId,+ { sourceKind: "inline", source: "void 0" },+ controller.signal,+ );+ await entered.promise;+ controller.abort(new Error("late abort during cleanup"));+ held.resolve();+ const result = await loading;+ if (result.ok) throw new Error("Failed load succeeded");+ expect(result.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);+ expect(result.error.cause).toBe(failure);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(manager.status(started.value.sessionId)?.scripts).toEqual([]);+});diff --git a/src/application/frida/FridaInstrumentationPort.ts b/src/application/frida/FridaInstrumentationPort.tsindex 39fa30936..19bf5feab 100644--- a/src/application/frida/FridaInstrumentationPort.ts+++ b/src/application/frida/FridaInstrumentationPort.ts@@ -59,17 +59,28 @@ export interface FridaScriptObservation {readonly scriptId: string;readonly sourceKind: "inline" | "file";readonly sourcePath: string | null;+ /** Digest of selected file bytes, or the inline source encoded as UTF-8. */readonly sourceSha256: string;+ readonly sourceRepresentation?: {+ readonly encoding: "utf8";+ readonly decoding: "replacement";+ readonly loadedSourceSha256: string;+ };readonly messages: readonly JsonValue[];readonly messagesTruncated: boolean;}export class FridaScriptLoadCancelledError extends AnalysisCancelledError {+ readonly scriptHandleAcquired: boolean;+constructor(readonly script: FridaScriptObservation,- options?: AnalysisErrorOptions,+ options?: AnalysisErrorOptions & {+ readonly scriptHandleAcquired?: boolean;+ },) {super("load_frida_script", options);+ this.scriptHandleAcquired = options?.scriptHandleAcquired ?? true;}}diff --git a/src/application/frida/FridaInstrumentationService.test.ts b/src/application/frida/FridaInstrumentationService.test.tsindex dc25bc62b..482b63c7c 100644--- a/src/application/frida/FridaInstrumentationService.test.ts+++ b/src/application/frida/FridaInstrumentationService.test.ts@@ -1,3 +1,4 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";@@ -7,6 +8,7 @@ import { FridaScriptLoadCancelledError } from "./FridaInstrumentationPort.js";import type { FridaInstrumentationPort } from "./FridaInstrumentationPort.js";import { FridaInstrumentationService } from "./FridaInstrumentationService.js";import {+ AnalysisCancelledError,AnalysisCapabilityUnavailableError,AnalysisInputError,} from "../../domain/analysisErrorCore.js";@@ -610,6 +612,155 @@ it("retains a cancelled provider load's source and messages in one-shot Evidence});});+it.each([false, true])(+ "keeps an ordinary provider load failure primary when cancellation is already signaled before cleanup (cleanupFails=%s)",+ async (cleanupFails) => {+ const controller = new AbortController();+ const abortReason = new Error("late caller cancellation");+ const primary = new AnalysisCapabilityUnavailableError(+ "frida",+ "load_frida_script",+ "native script compilation failed",+ { diagnostics: { native_status: "compile_rejected" } },+ );+ let closes = 0;+ const service = new FridaInstrumentationService(+ createProvider({+ async loadScript() {+ controller.abort(abortReason);+ return { ok: false, error: primary };+ },+ async closeSession() {+ closes += 1;+ return cleanupFails+ ? {+ ok: false,+ error: new AnalysisCapabilityUnavailableError(+ "frida",+ "close_frida_session",+ "session cleanup failed",+ ),+ }+ : { ok: true, value: { targetResumeObserved: false } };+ },+ }),+ );++ const result = await service.instrument(+ {+ mode: "spawn",+ program: "/fixture",+ source: { sourceKind: "inline", source: "send('ready');" },+ durationMs: 0,+ },+ controller.signal,+ );++ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.error).not.toBeInstanceOf(AnalysisCancelledError);+ expect(controller.signal.reason).toBe(abortReason);+ if (cleanupFails) {+ expect(result.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);+ expect(result.error.cause).toBe(primary);+ expect(result.error.diagnostics).toEqual({+ native_status: "compile_rejected",+ });+ expect(result.error.cleanup).toMatchObject({+ reason: expect.stringContaining("session cleanup failed"),+ resources: [createSession().sessionId],+ });+ } else {+ expect(result.error).toBe(primary);+ }+ expect(closes).toBe(1);+ },+);++it("preserves typed load cancellation cause, safe diagnostics, and decoded source representation in partial Evidence", async () => {+ const directory = await mkdtemp(+ join(tmpdir(), "rea-frida-cancelled-source-"),+ );+ const path = join(directory, "invalid-utf8.js");+ await writeFile(path, Buffer.from([0x2f, 0x2f, 0x20, 0xff, 0x0a]));+ try {+ const controller = new AbortController();+ const abortReason = new Error("native load cancelled after decoding");+ const diagnostics = {+ native_failure: "script load cancelled; transport_token=<redacted>",+ read_attempt: 1,+ };+ const script = {+ ...createScriptObservation(),+ sourceKind: "file" as const,+ sourcePath: path,+ sourceRepresentation: {+ encoding: "utf8" as const,+ decoding: "replacement" as const,+ loadedSourceSha256: "b".repeat(64),+ },+ messages: [{ type: "send", payload: "retained-before-cancel" }],+ };+ let closes = 0;+ const service = new FridaInstrumentationService(+ createProvider({+ async loadScript() {+ controller.abort(abortReason);+ return {+ ok: false,+ error: new FridaScriptLoadCancelledError(script, {+ cause: abortReason,+ diagnostics,+ }),+ };+ },+ async closeSession() {+ closes += 1;+ return { ok: true, value: { targetResumeObserved: false } };+ },+ }),+ );++ const result = await service.instrument(+ {+ mode: "spawn",+ program: "/fixture",+ source: { sourceKind: "file", path },+ durationMs: 0,+ },+ controller.signal,+ );++ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.error).toBeInstanceOf(AnalysisCancelledError);+ expect(result.error.cause).toBe(abortReason);+ expect(result.error.diagnostics).toEqual(diagnostics);+ expect(result.error.partialObservation).toMatchObject({+ normalized_result: {+ source_kind: "file",+ source_path: path,+ source_sha256: script.sourceSha256,+ messages: script.messages,+ instrumentation_cleanup: "released",+ },+ raw_result: {+ source_representation: {+ encoding: "utf8",+ decoding: "replacement",+ loaded_source_sha256: "b".repeat(64),+ },+ },+ limitations: expect.arrayContaining([+ expect.stringContaining("Invalid UTF-8"),+ ]),+ });+ expect(closes).toBe(1);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});+it("preserves a provider-committed load when cancellation arrives during result delivery", async () => {const controller = new AbortController();let unloads = 0;diff --git a/src/application/frida/FridaInstrumentationService.ts b/src/application/frida/FridaInstrumentationService.tsindex 3cba20d41..d228989d9 100644--- a/src/application/frida/FridaInstrumentationService.ts+++ b/src/application/frida/FridaInstrumentationService.ts@@ -124,8 +124,12 @@ export class FridaInstrumentationService {session: FridaSessionObservation,input: StartFridaSessionInput,cause: unknown,- loaded?: FridaScriptObservation,+ load?: {+ readonly script: FridaScriptObservation;+ readonly diagnostics?: AnalysisError["diagnostics"];+ },): Promise<Result<never, AnalysisError>> {+ const loaded = load?.script;const status = this.#provider.status(session.sessionId);const observation = status ?? {...session,@@ -140,13 +144,7 @@ export class FridaInstrumentationService {operation,{...sessionStatusOutput(observation),- ...(loaded === undefined- ? {}- : {- source_kind: loaded.sourceKind,- source_path: loaded.sourcePath,- source_sha256: loaded.sourceSha256,- }),+ ...(loaded === undefined ? {} : sourceOutput(loaded)),cleanup_error: closed.ok ? null : closed.error.message,target_state_before_cleanup: observation.state,target_resume_observed:@@ -162,10 +160,12 @@ export class FridaInstrumentationService {target_liveness_after_cleanup: "unknown",},fridaParameters(session.sessionId, input, session.deviceId),+ loaded,);return err(new AnalysisCancelledError(operation, {...(cause === undefined ? {} : { cause }),+ diagnostics: load?.diagnostics,partialObservation,...(closed.ok? {}@@ -195,9 +195,14 @@ export class FridaInstrumentationService {return err(cancelledScriptEvidence(sessionId, loaded.error));return loaded.ok? ok(- fridaEvidence("load_frida_script", scriptOutput(loaded.value), {- session_id: sessionId,- }),+ fridaEvidence(+ "load_frida_script",+ scriptOutput(loaded.value),+ {+ session_id: sessionId,+ },+ loaded.value,+ ),): loaded;}@@ -255,17 +260,15 @@ export class FridaInstrumentationService {input.source,signal,);- let scriptObservation: FridaScriptObservation | undefined;- if (loaded.ok) scriptObservation = loaded.value;- else if (loaded.error instanceof FridaScriptLoadCancelledError)- scriptObservation = loaded.error.script;- if (signal?.aborted)+ if (!loaded.ok && loaded.error instanceof AnalysisCancelledError)return this.#cancelSession("instrument_with_frida",started.value,input,- signal.reason,- scriptObservation,+ loaded.error.cause,+ loaded.error instanceof FridaScriptLoadCancelledError+ ? loaded.error+ : undefined,);if (!loaded.ok) {const closed = await this.#provider.closeSession(started.value.sessionId);@@ -279,6 +282,14 @@ export class FridaInstrumentationService {),);}+ if (signal?.aborted)+ return this.#cancelSession(+ "instrument_with_frida",+ started.value,+ input,+ signal.reason,+ { script: loaded.value },+ );if (started.value.mode === "spawn") {const resumed = await this.#provider.resumeSession(started.value.sessionId,@@ -290,7 +301,7 @@ export class FridaInstrumentationService {started.value,input,signal.reason,- loaded.value,+ { script: loaded.value },);if (!resumed.ok) {const closed = await this.#provider.closeSession(@@ -314,8 +325,8 @@ export class FridaInstrumentationService {"instrument_with_frida",started.value,input,- cause,- loaded.value,+ signal?.aborted ? signal.reason : cause,+ { script: loaded.value },);}if (signal?.aborted)@@ -324,7 +335,7 @@ export class FridaInstrumentationService {started.value,input,signal.reason,- loaded.value,+ { script: loaded.value },);const status = this.#provider.status(started.value.sessionId);const observation = status ?? {@@ -340,12 +351,11 @@ export class FridaInstrumentationService {"instrument_with_frida",{...sessionStatusOutput(observation),- source_kind: loaded.value.sourceKind,- source_path: loaded.value.sourcePath,- source_sha256: loaded.value.sourceSha256,+ ...sourceOutput(loaded.value),cleanup_error: cleanupError,},fridaParameters(started.value.sessionId, input, started.value.deviceId),+ loaded.value,);return ok({evidence,@@ -366,6 +376,7 @@ const fridaEvidence = (operation: string,result: unknown,parameters: unknown,+ script?: FridaScriptObservation,): Evidence =>createEvidence(undefined,@@ -375,11 +386,28 @@ const fridaEvidence = (operation,parameters: jsonObjectSchema.parse(parameters),result: jsonValueSchema.parse(result),+ ...(script?.sourceRepresentation === undefined+ ? {}+ : {+ rawResult: {+ source_representation: {+ encoding: script.sourceRepresentation.encoding,+ decoding: script.sourceRepresentation.decoding,+ loaded_source_sha256:+ script.sourceRepresentation.loadedSourceSha256,+ },+ },+ }),confidence: "observed",authority: "external-service",environment: null,limitations: ["The target operating system and architecture were not reported by this observation.",+ ...(script?.sourceRepresentation === undefined+ ? []+ : [+ "Invalid UTF-8 in the selected script file was decoded with replacement characters. source_sha256 identifies the original file bytes; raw_result.source_representation.loaded_source_sha256 identifies the UTF-8 encoding of the string passed to Frida.",+ ]),],},);@@ -424,6 +452,10 @@ const withCleanupFailure = (`${original.message}; cleanup failed: ${cleanupReason}`,{cause: original,+ diagnostics: original.diagnostics,+ ...(original.partialObservation === undefined+ ? {}+ : { partialObservation: original.partialObservation }),cleanup: {reason: cleanupReason,resources: [sessionId],@@ -442,6 +474,7 @@ export const withRecoveredFridaCleanup = (error.reason,{cause: error.cause,+ diagnostics: error.diagnostics,...(error.capturedOutput === undefined? {}: { capturedOutput: error.capturedOutput }),@@ -455,11 +488,15 @@ export const withRecoveredFridaCleanup = (): error;-const scriptOutput = (script: FridaScriptObservation) => ({- script_id: script.scriptId,+const sourceOutput = (script: FridaScriptObservation) => ({source_kind: script.sourceKind,source_path: script.sourcePath,source_sha256: script.sourceSha256,+});++const scriptOutput = (script: FridaScriptObservation) => ({+ script_id: script.scriptId,+ ...sourceOutput(script),messages: script.messages,messages_truncated: script.messagesTruncated,});@@ -485,16 +522,20 @@ const cancelledScriptEvidence = (): AnalysisCancelledError =>new AnalysisCancelledError(error.operation, {cause: error.cause,+ diagnostics: error.diagnostics,cleanup: error.cleanup,partialObservation: fridaEvidence(error.operation,{...scriptOutput(error.script),cleanup_error: error.cleanup?.reason ?? null,- script_cleanup: error.cleanupIncomplete- ? "incomplete_or_unknown"- : "released",+ script_cleanup: !error.scriptHandleAcquired+ ? "no_handle"+ : error.cleanupIncomplete+ ? "incomplete_or_unknown"+ : "released",},{ session_id: sessionId },+ error.script,),});diff --git a/src/frida/FridaInstrumentationManager.ts b/src/frida/FridaInstrumentationManager.tsindex 7ef5d115f..5056c9d46 100644--- a/src/frida/FridaInstrumentationManager.ts+++ b/src/frida/FridaInstrumentationManager.ts@@ -1,3 +1,4 @@+import { isUtf8 } from "node:buffer";import { createHash, randomUUID } from "node:crypto";import { readFile } from "node:fs/promises";@@ -55,6 +56,11 @@ export const FRIDA_PROVIDER_IDENTITY = {version: null,} as const;+interface ScriptMessageCapture {+ readonly messages: MessageFifo<JsonValue>;+ truncated: boolean;+}+interface ManagedScript {readonly id: string;readonly name: string;@@ -86,13 +92,12 @@ interface ManagedSession extends ManagedRemoteConnection {readonly mode: "attach" | "spawn";readonly scripts: Map<string, ManagedScript>;readonly messages: MessageFifo<CapturedMessage>;- readonly messagesByScript: Map<string, MessageFifo<JsonValue>>;+ readonly scriptCaptures: Map<string, ScriptMessageCapture>;state: "paused" | "running" | "detached";targetResumeObserved: boolean;resumeAfterDetachPending: boolean;capturedBytes: number;messagesTruncated: boolean;- readonly truncatedScripts: Set<string>;}export interface FridaInstrumentationManagerOptions {@@ -308,13 +313,12 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {mode: input.mode,scripts: new Map(),messages: new MessageFifo(),- messagesByScript: new Map(),+ scriptCaptures: new Map(),state: input.mode === "spawn" ? "paused" : "running",targetResumeObserved: false,resumeAfterDetachPending: false,capturedBytes: 0,messagesTruncated: false,- truncatedScripts: new Set(),};session.detached.connect(() => {managed.state = "detached";@@ -385,11 +389,26 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {return err(unknownFridaSession("load_frida_script", sessionId));let scriptSource: string;+ let sourceSha256: string;+ let sourceRepresentation: FridaScriptObservation["sourceRepresentation"];try {- scriptSource =+ const selectedSource =source.sourceKind === "inline"? source.source- : await readFile(source.path, "utf8");+ : await readFile(source.path);+ sourceSha256 = createHash("sha256").update(selectedSource).digest("hex");+ scriptSource =+ typeof selectedSource === "string"+ ? selectedSource+ : selectedSource.toString("utf8");+ if (typeof selectedSource !== "string" && !isUtf8(selectedSource))+ sourceRepresentation = {+ encoding: "utf8",+ decoding: "replacement",+ loadedSourceSha256: createHash("sha256")+ .update(scriptSource)+ .digest("hex"),+ };} catch (cause: unknown) {const sourcePath = source.sourceKind === "file" ? source.path : undefined;return err(@@ -414,23 +433,24 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {if (signal?.aborted)return err(cancelledOperation("load_frida_script", signal));- const sourceSha256 = createHash("sha256")- .update(scriptSource)- .digest("hex");const scriptId = randomUUID();- const scriptName = `rea-${scriptId}`;- managed.messagesByScript.set(scriptId, new MessageFifo());- let nativeScript: Script | undefined;+ const capture: ScriptMessageCapture = {+ messages: new MessageFifo(),+ truncated: false,+ };+ managed.scriptCaptures.set(scriptId, capture);const onMessage = (message: FridaMessage, data: Buffer | null): void => {this.#recordMessage(managed, scriptId, message, data);};+ let entry: ManagedScript | undefined;+ let nativeFailure: { readonly cause: unknown } | undefined;try {- nativeScript = await managed.session.createScript(scriptSource, {- name: scriptName,+ const nativeScript = await managed.session.createScript(scriptSource, {+ name: `rea-${scriptId}`,});- const entry: ManagedScript = {+ entry = {id: scriptId,- name: scriptName,+ name: `rea-${scriptId}`,script: nativeScript,onMessage,state: "active",@@ -438,47 +458,64 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {managed.scripts.set(scriptId, entry);nativeScript.message.connect(onMessage);if (!signal?.aborted) await nativeScript.load();- const observation: FridaScriptObservation = {- scriptId,- sourceKind: source.sourceKind,- sourcePath: source.sourceKind === "file" ? source.path : null,- sourceSha256,- messages: managed.messagesByScript.get(scriptId)?.toArray() ?? [],- messagesTruncated: managed.truncatedScripts.has(scriptId),- };- if (signal?.aborted) {- const cleanupReason = await this.#releaseScript(managed, entry);- return err(- new FridaScriptLoadCancelledError(observation, {- cause: signal.reason,- ...(cleanupReason === undefined- ? {}- : {- cleanup: {- reason: cleanupReason,- resources: [sessionId, scriptId],- },- }),- }),- );- }- return ok(observation);} catch (cause: unknown) {- const entry = managed.scripts.get(scriptId);- const cleanupReason =- entry === undefined- ? undefined- : await this.#releaseScript(managed, entry);- managed.messagesByScript.delete(scriptId);+ nativeFailure = { cause };+ }+ // Settle the primary outcome before cleanup: a later abort cannot replace+ // an already observed native failure. Keep the capture through cleanup,+ // including callbacks emitted while unload/disconnect are completing.+ const cancellation = signal?.aborted+ ? { reason: signal.reason }+ : undefined;+ let cleanupReason: string | undefined;+ if (nativeFailure !== undefined || cancellation !== undefined) {+ if (entry === undefined) managed.scriptCaptures.delete(scriptId);+ else cleanupReason = await this.#releaseScript(managed, entry);+ }+ if (nativeFailure !== undefined && cancellation === undefined)return err(providerError("load_frida_script",- cause,+ nativeFailure.cause,managed.remote,cleanupReason,),);- }+ const observation: FridaScriptObservation = {+ scriptId,+ sourceKind: source.sourceKind,+ sourcePath: source.sourceKind === "file" ? source.path : null,+ sourceSha256,+ ...(sourceRepresentation === undefined ? {} : { sourceRepresentation }),+ messages: capture.messages.toArray(),+ messagesTruncated: capture.truncated,+ };+ if (cancellation !== undefined)+ return err(+ new FridaScriptLoadCancelledError(observation, {+ cause: cancellation.reason,+ scriptHandleAcquired: entry !== undefined,+ ...(nativeFailure === undefined+ ? {}+ : {+ diagnostics: {+ native_failure: sanitizeError(+ nativeFailure.cause,+ managed.remote,+ ),+ },+ }),+ ...(cleanupReason === undefined+ ? {}+ : {+ cleanup: {+ reason: cleanupReason,+ resources: [sessionId, scriptId],+ },+ }),+ }),+ );+ return ok(observation);}resumeSession(@@ -609,8 +646,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {return sanitizeError(cause, managed.remote);}managed.scripts.delete(entry.id);- managed.messagesByScript.delete(entry.id);- managed.truncatedScripts.delete(entry.id);+ managed.scriptCaptures.delete(entry.id);return undefined;}@@ -1043,14 +1079,16 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {managed.capturedBytes -= removed.charge;// Both queues are in arrival order, so the globally oldest message is// also the oldest one retained for its script.- const scriptMessages = managed.messagesByScript.get(removed.scriptId);+ const scriptMessages = managed.scriptCaptures.get(+ removed.scriptId,+ )?.messages;if (scriptMessages?.peek() === removed.observation)scriptMessages.shift();markMessageTruncated(managed, removed.scriptId);}}managed.messages.push({ observation, scriptId, charge });- managed.messagesByScript.get(scriptId)?.push(observation);+ managed.scriptCaptures.get(scriptId)?.messages.push(observation);managed.capturedBytes += charge;}@@ -1463,8 +1501,8 @@ const markMessageTruncated = (scriptId: string,): void => {managed.messagesTruncated = true;- if (managed.messagesByScript.has(scriptId))- managed.truncatedScripts.add(scriptId);+ const capture = managed.scriptCaptures.get(scriptId);+ if (capture !== undefined) capture.truncated = true;};/**diff --git a/tests/boundary/cli/fridaCli.test.ts b/tests/boundary/cli/fridaCli.test.tsindex 0751e28d4..52770b81b 100644--- a/tests/boundary/cli/fridaCli.test.ts+++ b/tests/boundary/cli/fridaCli.test.ts@@ -1,4 +1,9 @@+import { createHash } from "node:crypto";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import { expect, it } from "vitest";+import type { DeviceManager } from "frida";import { createCli } from "../../../src/cli.js";import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";@@ -151,6 +156,135 @@ it("maps one-shot Frida CLI target, script, duration, and remote options", asyncexpect(stdout).not.toContain("synthetic-secret-token");});+it("keeps Frida script-file identity in original bytes when UTF-8 decoding replaces invalid bytes", async () => {+ const directory = await mkdtemp(join(tmpdir(), "rea-frida-script-identity-"));+ const files = [+ {+ name: "ff.js",+ bytes: Buffer.from([+ 0x2f, 0x2f, 0x20, 0xff, 0x0a, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x31, 0x29,+ 0x3b,+ ]),+ },+ {+ name: "fe.js",+ bytes: Buffer.from([+ 0x2f, 0x2f, 0x20, 0xfe, 0x0a, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x31, 0x29,+ 0x3b,+ ]),+ },+ { name: "replacement.js", bytes: Buffer.from("// �\nsend(1);", "utf8") },+ {+ name: "ascii.js",+ bytes: Buffer.from("// ordinary ASCII\nsend(1);", "ascii"),+ },+ ];+ try {+ await Promise.all(+ files.map(({ name, bytes }) => writeFile(join(directory, name), bytes)),+ );+ const loadedSources: string[] = [];+ const deviceManager = {+ async getDeviceById() {+ return {+ id: "local",+ name: "Fixture device",+ type: "local",+ async getProcessByPid(pid: number) {+ return { pid, name: "fixture" };+ },+ async attach() {+ let detached = false;+ return {+ pid: 71,+ detached: { connect() {}, disconnect() {} },+ isDetached: () => detached,+ async detach() {+ detached = true;+ },+ async createScript(source: string) {+ loadedSources.push(source);+ return {+ message: { connect() {}, disconnect() {} },+ async load() {},+ async unload() {},+ };+ },+ };+ },+ };+ },+ } as unknown as DeviceManager;++ for (const { name } of files) {+ const provider = new FridaInstrumentationManager({ deviceManager });+ let stdout = "";+ let exitCode = 0;+ await createCli({}, undefined, provider).serve(+ [+ "instrument-with-frida",+ "attach",+ "71",+ "--script-file",+ join(directory, name),+ "--duration-ms",+ "0",+ "--json",+ ],+ {+ env: {},+ exit: (code) => {+ exitCode = code;+ },+ stdout: (text) => {+ stdout += text;+ },+ },+ );+ expect(exitCode).toBe(0);+ const output: unknown = JSON.parse(stdout);+ const bytes = files.find((file) => file.name === name)?.bytes;+ if (bytes === undefined) throw new Error(`Missing fixture ${name}`);+ const decodedSource = bytes.toString("utf8");+ expect(loadedSources.at(-1)).toBe(decodedSource);+ const rawDigest = createHash("sha256").update(bytes).digest("hex");+ const loadedSourceDigest = createHash("sha256")+ .update(decodedSource, "utf8")+ .digest("hex");+ const outputText = JSON.stringify(output);+ expect(outputText).toContain(rawDigest);+ if (name === "ff.js" || name === "fe.js") {+ expect(rawDigest).not.toBe(loadedSourceDigest);+ expect(output).toMatchObject({+ evidence: {+ normalized_result: { source_sha256: rawDigest },+ raw_result: {+ source_representation: {+ encoding: "utf8",+ decoding: "replacement",+ loaded_source_sha256: loadedSourceDigest,+ },+ },+ },+ });+ expect(outputText).toMatch(+ /limitations.*(?:replacement|original bytes)/iu,+ );+ } else {+ expect(output).toMatchObject({+ evidence: {+ normalized_result: { source_sha256: rawDigest },+ },+ });+ expect(outputText).not.toContain("source_representation");+ }+ await provider.closeAll();+ }+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});+it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {for (const cleanupFails of [false, true]) {const calls: string[] = [];diff --git a/tests/boundary/mcp/fridaLifecycleMcp.test.ts b/tests/boundary/mcp/fridaLifecycleMcp.test.tsindex 9ea654161..74c0c629e 100644--- a/tests/boundary/mcp/fridaLifecycleMcp.test.ts+++ b/tests/boundary/mcp/fridaLifecycleMcp.test.ts@@ -1,3 +1,6 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import { createHash } from "node:crypto";import { setImmediate } from "node:timers/promises";@@ -701,6 +704,188 @@ it.each(["create", "load"] as const)(},);+it("retains cancellation source facts without claiming native creation when no script handle returns", async () => {+ const { fixture, id, held } = await scriptLoadFixture("create");+ fixture.controls.create = async () => {+ await held.wait();+ throw new Error("native create rejected");+ };+ const controller = new AbortController();+ const loading = fixture+ .load(id, "no-returned-handle", controller.signal)+ .catch((cause: unknown) => cause);+ await held.entered;+ controller.abort(new Error("cancel while creating"));+ await fixture.client.ping();+ held.release();+ await loading;+ fixture.controls.create = async () => {};+ await fixture.load(id, "barrier");+ await fixture.client.ping();+ const observation = await retainedScriptObservation(+ fixture,+ id,+ "no-returned-handle",+ );+ expect(observation).toMatchObject({+ messages: [],+ script_cleanup: "no_handle",+ cleanup_error: null,+ });+ expect(fixture.unloaded).toEqual([]);+ expect(fixture.scripts).toHaveLength(2);+ expect(fixture.controls.detachCalls).toBe(0);+ expect(fixture.controls.resumes).toBe(0);+});++it("retains original malformed file identity and decoded representation through a rejected cancelled MCP load", async () => {+ const { fixture, id, held } = await scriptLoadFixture();+ const directory = await mkdtemp(join(tmpdir(), "rea-frida-file-cancel-"));+ onTestFinished(() => rm(directory, { recursive: true, force: true }));+ const path = join(directory, "script.js");+ const bytes = Buffer.from([0x2f, 0x2f, 0xff, 0x0a]);+ await writeFile(path, bytes);+ const decodedSource = bytes.toString("utf8");+ fixture.controls.afterLoad = () => {+ if (fixture.loaded.at(-1) === decodedSource)+ throw new Error("native rejection after message");+ };+ const controller = new AbortController();+ const loading = fixture.client+ .callTool(+ {+ name: "load_frida_script",+ arguments: { session_id: id, source_kind: "file", path },+ },+ { signal: controller.signal },+ )+ .catch((cause: unknown) => cause);+ await held.entered;+ controller.abort(new Error("cancel file load"));+ await fixture.client.ping();+ held.release();+ await loading;+ await fixture.load(id, "barrier");+ await fixture.client.ping();+ const response = await fixture.client.callTool({+ name: "get_evidence_bundle",+ arguments: {},+ });+ const bundle = evidenceBundleSchema.parse(+ toolContract("get_evidence_bundle").outputSchema.parse(+ response.structuredContent,+ ).result,+ );+ const records = bundle.records.filter(+ (record) =>+ record.operation === "load_frida_script" &&+ JSON.stringify(record.normalized_result).includes(path),+ );+ expect(records).toHaveLength(1);+ expect(records[0]).toMatchObject({+ normalized_result: {+ source_kind: "file",+ source_path: path,+ source_sha256: createHash("sha256").update(bytes).digest("hex"),+ messages: [expect.objectContaining({ payload: decodedSource })],+ script_cleanup: "released",+ cleanup_error: null,+ },+ raw_result: {+ source_representation: {+ encoding: "utf8",+ decoding: "replacement",+ loaded_source_sha256: createHash("sha256")+ .update(decodedSource)+ .digest("hex"),+ },+ },+ limitations: expect.arrayContaining([+ expect.stringContaining("Invalid UTF-8"),+ ]),+ });+ expect(fixture.scripts[0]?.isDestroyed).toBe(false);+ expect(fixture.scripts[1]?.isDestroyed).toBe(true);+ expect(fixture.controls.detachCalls).toBe(0);+});++it.each([+ { cancel: true, unloadFailures: 0 },+ { cancel: true, unloadFailures: 1 },+ { cancel: false, unloadFailures: 0 },+])(+ "retains rejected native-load observations through cancellation=$cancel and unload failures=$unloadFailures",+ async ({ cancel, unloadFailures }) => {+ const { fixture, id, held } = await scriptLoadFixture();+ const source = "rejecting-native";+ fixture.controls.afterLoad = () => {+ if (fixture.loaded.at(-1) === source)+ throw new Error("native load rejected after its message");+ };+ fixture.controls.unloadFailures = unloadFailures;+ const controller = new AbortController();+ const loading = fixture.load(id, source, controller.signal);+ const outcome = loading.then(+ (value) => ({ kind: "result" as const, value }),+ (cause: unknown) => ({ kind: "rejected" as const, cause }),+ );+ await held.entered;+ if (cancel) {+ controller.abort(new Error("cancel before native rejection"));+ await fixture.client.ping();+ }+ held.release();+ const result = await outcome;+ await fixture.load(id, "barrier");+ await fixture.client.ping();+ expect(fixture.controls.detachCalls).toBe(0);+ expect(fixture.controls.resumes).toBe(0);+ expect(fixture.scripts[0]?.isDestroyed).toBe(false);+ expect(fixture.scripts[1]?.isDestroyed).toBe(unloadFailures === 0);+ if (!cancel) {+ expect(result.kind).toBe("result");+ if (result.kind !== "result") throw result.cause;+ expect(parseMcpToolError(result.value).error.code).toBe(+ "capability_unavailable",+ );+ expect(+ fixture.session+ .exportEvidenceBundle()+ .records.filter(+ (record) =>+ record.operation === "load_frida_script" &&+ JSON.stringify(record.normalized_result).includes(source),+ ),+ ).toEqual([]);+ return;+ }+ expect(result.kind).toBe("rejected");+ const observation = await retainedScriptObservation(fixture, id, source);+ expect(observation).toMatchObject({+ messages: [expect.objectContaining({ payload: source })],+ script_cleanup:+ unloadFailures === 0 ? "released" : "incomplete_or_unknown",+ cleanup_error:+ unloadFailures === 0 ? null : expect.stringContaining("unload"),+ });+ if (unloadFailures > 0) {+ if (typeof observation.script_id !== "string")+ throw new Error("Missing candidate script identity");+ await retryCancelledScriptUnload(fixture, id, observation.script_id);+ }+ expect(fixture.scripts[1]?.isDestroyed).toBe(true);+ expect(fixture.manager.status(id)?.scripts).toHaveLength(2);+ expect(+ (+ await fixture.client.callTool({+ name: "frida_session_status",+ arguments: { session_id: id },+ })+ ).isError,+ ).not.toBe(true);+ },+);+it("awaits an admitted attach on server shutdown and retries failed native cleanup", async () => {const fixture = await connectedFixture();const held = gate();