fix: reconcile captured main and owned findings for PR #1603

This commit is contained in:
morluto
2026-10-13 23:02:19 +08:00
433 changed files with 23739 additions and 3277 deletions
+304
View File
@@ -0,0 +1,304 @@
import { expect, it } from "vitest";
import {
analyzeJadxRequest,
type JadxToolPort,
} from "../../../src/android/JadxAnalysis.js";
import { androidInputSchemas } from "../../../src/domain/android/androidAnalysis.js";
const summary = {
full_name: "fixture.Target",
name: "Target",
method_count: 2,
field_count: 0,
inner_class_count: 0,
methods: [
{
name: "choose",
signature: "choose(String): void",
dex_descriptor: "(Ljava/lang/String;)V",
is_constructor: false,
def_pos: 0,
},
{
name: "choose",
signature: "choose(int): void",
dex_descriptor: "(I)V",
is_constructor: false,
def_pos: 0,
},
],
fields: [],
inner_classes: [],
};
const engine = {
name: "jadx",
version: "0.7.1",
artifact_sha256: "a".repeat(64),
source_revision: null,
worker_count: 1,
heap_limit_mib: null,
};
it("publishes exact DEX prototypes instead of discarding bridge metadata", async () => {
const tools: JadxToolPort = {
json: () => Promise.resolve(summary),
text: () => Promise.reject(new Error("unexpected text call")),
};
const result = await analyzeJadxRequest(
tools,
{
operation: "inspect_android_class",
input: androidInputSchemas.inspect_android_class.parse({
path: "/fixture.apk",
class_name: "fixture.Target",
}),
},
{} as never,
engine,
);
expect(result).toMatchObject({
methods: [
{ name: "choose", dex_descriptor: "(Ljava/lang/String;)V" },
{ name: "choose", dex_descriptor: "(I)V" },
],
});
});
it("traces only the selected overloaded method and checks the producer identity", async () => {
const calls: Record<string, unknown>[] = [];
const tools: JadxToolPort = {
json: (name, input) => {
calls.push({ name, ...input });
if (name === "get_class_summary") return Promise.resolve(summary);
return Promise.resolve({
target: "fixture.Target.choose",
overload_index: 1,
reported_signature: "choose(int): void",
total: 1,
count: 1,
resolve_line: false,
items: [
{
kind: "method",
name: "caller",
full_name: "fixture.Other.caller",
containing_class: "fixture.Other",
top_class: "fixture.Other",
def_pos: 0,
direct_invokes: [
{
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 0,
dex_method_index: 1,
opcode: "INVOKE_STATIC",
},
{
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 3,
dex_method_index: 1,
opcode: "INVOKE_STATIC",
},
],
},
],
});
},
text: () => Promise.reject(new Error("unexpected text call")),
};
const request = {
operation: "trace_android_references",
input: androidInputSchemas.trace_android_references.parse({
path: "/fixture.apk",
class_name: "fixture.Target",
method_name: "choose",
overload_index: 1,
}),
} as const;
const result = await analyzeJadxRequest(tools, request, {} as never, engine);
expect(result).toMatchObject({
method_name: "choose",
overload_index: 1,
reported_signature: "choose(int): void",
dex_descriptor: "(I)V",
total: 1,
reference_unit: "using_node",
references: [
{
direct_invokes: [
{ dex_code_unit_offset: 0 },
{ dex_code_unit_offset: 3 },
],
},
],
});
expect(calls[1]).toMatchObject({
name: "get_xrefs_to_method",
overload_index: 1,
});
});
it("rejects an ambiguous method and a producer response for a different overload", async () => {
const xrefs = {
target: "fixture.Target.choose",
overload_index: 0,
reported_signature: "choose(String): void",
total: 0,
count: 0,
resolve_line: false,
items: [],
};
const tools: JadxToolPort = {
json: (name) =>
Promise.resolve(name === "get_class_summary" ? summary : xrefs),
text: () => Promise.reject(new Error("unexpected text call")),
};
const input = {
path: "/fixture.apk",
class_name: "fixture.Target",
method_name: "choose",
};
await expect(
analyzeJadxRequest(
tools,
{
operation: "trace_android_references",
input,
},
{} as never,
engine,
),
).rejects.toMatchObject({
_tag: "AnalysisInputError",
});
await expect(
analyzeJadxRequest(
tools,
{
operation: "trace_android_references",
input: { ...input, overload_index: 1 },
},
{} as never,
engine,
),
).rejects.toMatchObject({
_tag: "AnalysisOutputError",
});
});
const invokeSite = {
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 0,
dex_method_index: 1,
opcode: "INVOKE_STATIC",
};
const traceWithReference = (fields: Record<string, unknown>) =>
analyzeJadxRequest(
{
json: (name) =>
Promise.resolve(
name === "get_class_summary"
? summary
: {
target: "fixture.Target.choose",
overload_index: 0,
reported_signature: "choose(String): void",
total: 1,
count: 1,
resolve_line: false,
items: [
{
kind: "method",
name: "caller",
full_name: "fixture.Other.caller",
containing_class: "fixture.Other",
top_class: "fixture.Other",
def_pos: 0,
...fields,
},
],
},
),
text: () => Promise.reject(new Error("unexpected text call")),
},
{
operation: "trace_android_references",
input: {
path: "/fixture.apk",
class_name: "fixture.Target",
method_name: "choose",
overload_index: 0,
},
},
{} as never,
engine,
);
it.each([
[{}, null],
[{ direct_invokes: [] }, []],
])(
"preserves unavailable versus observed-empty invoke sites: %j",
async (fields, expected) => {
const result = await traceWithReference(fields as Record<string, unknown>);
expect(result).toMatchObject({
references: [{ direct_invokes: expected }],
});
},
);
it.each([
{ ...invokeSite, dex_code_unit_offset: -1 },
{
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 0,
dex_method_index: 1,
},
])("rejects malformed direct invoke producer evidence: %j", async (site) => {
await expect(
traceWithReference({ direct_invokes: [site] }),
).rejects.toThrow();
});
it("preserves bounded instruction coverage separately from using-node coverage", async () => {
const result = await traceWithReference({
direct_invokes: [invokeSite],
direct_invokes_exhaustive: false,
});
expect(result).toMatchObject({
coverage: "complete",
reference_unit: "using_node",
references: [
{ direct_invokes: [invokeSite], direct_invokes_exhaustive: false },
],
});
});
it("rejects malformed method descriptors at the Android adapter boundary", async () => {
const invalidSummary = {
...summary,
methods: summary.methods.map((method) => ({
...method,
dex_descriptor: "not-a-dex-descriptor",
})),
};
await expect(
analyzeJadxRequest(
{
json: () => Promise.resolve(invalidSummary),
text: () => Promise.reject(new Error("unexpected text call")),
},
{
operation: "inspect_android_class",
input: { path: "/fixture.apk", class_name: "fixture.Target" },
},
{} as never,
engine,
),
).rejects.toThrow();
});
@@ -0,0 +1,60 @@
import { spawn } from "node:child_process";
import { readFile } from "node:fs/promises";
import { expect, it } from "vitest";
it.skipIf(process.platform !== "win32")(
"retains guardian cleanup ownership through more than 100 transient failures",
async () => {
const guardian = await readFile(
new URL(
"../../../scripts/rea-android-workspace-guardian.mjs",
import.meta.url,
),
"utf8",
);
const withoutTimer = guardian
.replace(/^#!.*\r?\n/u, "")
.replace(
'import { setTimeout as delay } from "node:timers/promises";',
"const delay = async () => {};",
);
const injected = withoutTimer.replace(
'import { WindowsPrivateRuntime } from "../dist/windows/WindowsPrivateRuntime.js";',
`let attempts = 0;
const WindowsPrivateRuntime = {
create: () => ({
observation: { path: "synthetic-root", volumeSerial: "0", fileId: "0", privateDacl: true },
close: async () => { if (++attempts <= 101) throw new Error("transient cleanup failure"); },
}),
};`,
);
expect(withoutTimer).not.toBe(guardian);
expect(injected).not.toBe(withoutTimer);
const child = spawn(
process.execPath,
[
"--input-type=module",
"-e",
'process.argv.splice(1, 0, "guardian.mjs");\n' + injected,
"synthetic-parent",
],
{ signal: AbortSignal.timeout(3000) },
);
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
child.stdin.end();
const code = await new Promise<number | null>((resolve, reject) => {
child.once("close", resolve);
child.once("error", reject);
});
expect(code, stderr).toBe(0);
expect(JSON.parse(stdout.trim())).toMatchObject({ path: "synthetic-root" });
},
);
@@ -0,0 +1,89 @@
import { open } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { PwntoolsLayoutProvider } from "../../../src/native/pwntools/PwntoolsLayoutProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const unsupportedHost = process.platform !== "linux" || process.arch !== "x64";
const DEFAULT_INPUT_BYTES = 33_554_432;
// One byte above the shipped bound, so the admission decision is the only
// difference between the first two cases.
const ARTIFACT_BYTES = DEFAULT_INPUT_BYTES + 1;
/** Sparse regular file just larger than the shipped input bound. */
const oversizedArtifact = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-pwntools-input-bound-");
const path = join(root, "recorded-core");
const handle = await open(path, "w");
await handle.truncate(ARTIFACT_BYTES);
await handle.close();
return path;
};
/** One admission attempt, reported as the projected caller-visible failure. */
const inspect = async (override?: string) => {
const path = await oversizedArtifact();
const provider = new PwntoolsLayoutProvider(
{
REA_PWNTOOLS_PYTHON: process.execPath,
...(override === undefined
? {}
: { REA_PWNTOOLS_MAX_INPUT_BYTES: override }),
},
async (spawn) =>
spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", "process.stdout.write('no reply')"],
}),
);
onTestFinished(async () => {
await provider.close();
});
const result = await provider.inspect({ path });
if (result.ok) throw new Error("Expected the bounded decoder to fail");
const projected = projectAnalysisError(result.error);
return { projected, text: JSON.stringify(projected) };
};
it.runIf(!unsupportedHost)(
"refuses an artifact above the shipped bound when no override is set",
async () => {
const { projected, text } = await inspect();
expect(projected.code).toBe("invalid_request");
expect(text).toContain(
`Selected artifact exceeds ${String(DEFAULT_INPUT_BYTES)} bytes`,
);
},
);
it.runIf(!unsupportedHost)(
"admits the same artifact once the override widens the bound",
async () => {
const { projected, text } = await inspect(String(ARTIFACT_BYTES));
// Admission passed, so the only remaining failure is that the owned decoder
// never wrote a reply, which also proves the process really ran.
expect(text).not.toContain("Selected artifact exceeds");
expect(projected.code).toBe("unreadable_output");
expect(text).toContain("no reply");
},
);
it.runIf(!unsupportedHost)(
"refuses an unusable override before reading the artifact",
async () => {
const { projected, text } = await inspect("0");
expect(projected.code).toBe("provider_unavailable");
expect(projected.details).toMatchObject({
rejections: [
{ diagnostics: { configuration_key: "REA_PWNTOOLS_MAX_INPUT_BYTES" } },
],
});
expect(text).toContain("REA_PWNTOOLS_MAX_INPUT_BYTES must be a decimal");
expect(text).not.toContain("Selected artifact exceeds");
},
);
@@ -1,3 +1,4 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
@@ -9,6 +10,7 @@ import {
} from "../../support/process/processFixture.js";
import {
BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS,
BrowserStartupError,
waitForBrowserDevtoolsPort,
} from "../../../src/browser/BrowserProcessStartup.js";
@@ -86,15 +88,68 @@ describe("browser process startup", () => {
failure: "timeout",
exitCode: null,
signalCode: null,
startupTimeoutMs: 20,
});
expect(String(failure)).toContain("stderr=<empty>");
expect(String(failure)).toContain("startup_timeout_ms=20");
} finally {
child.kill("SIGKILL");
expect(await waitForExit(child, 5_000)).toBe(true);
}
});
it("names the owner's deadline when a caller omits one", async ({
processes,
}) => {
const root = await temporaryRoot();
const child = processes.spawn(process.execPath, [
"-e",
"setTimeout(() => process.exit(3), 10)",
]);
const failure = await waitForBrowserDevtoolsPort({
child,
executable: process.execPath,
activePortPath: join(root, "DevToolsActivePort"),
stderr: () => "owner default fixture",
pollIntervalMs: 5,
}).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(BrowserStartupError);
expect(failure).toMatchObject({
failure: "exited",
startupTimeoutMs: BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS,
});
expect(String(failure)).toContain(
`startup_timeout_ms=${String(BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS)}`,
);
});
it("keeps one owner for the DevToolsActivePort deadline", async () => {
expect(BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS).toBe(60_000);
const callers = [
"../../../scripts/verify-real-browser.mjs",
"../../../scripts/lib/browser-runtime-fixture-lifecycle.mjs",
];
for (const caller of callers) {
const source = await readFile(new URL(caller, import.meta.url), "utf8");
expect(devtoolsPortDeadlines(source)).toEqual([
["BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS"],
]);
}
});
});
const temporaryRoot = async (): Promise<string> => {
return createTestTempDirectory("rea-browser-startup-");
};
const devtoolsPortDeadlines = (source: string): string[][] => {
const calls = /waitForBrowserDevtoolsPort\(\{(?<body>[\s\S]*?)\}\)/gu;
const deadlines = /\btimeoutMs:\s*(?<value>[^\n,]+)/gu;
return [...source.matchAll(calls)].map((call) =>
[...String(call.groups?.body).matchAll(deadlines)].map((deadline) =>
String(deadline.groups?.value).trim(),
),
);
};
@@ -0,0 +1,315 @@
import { describe, expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
type FakeOptions,
} from "../../fixtures/fakeCdpBrowser.js";
import { trackBrowser } from "./cdpBrowserProvider.support.js";
const startBrowser = async (options: FakeOptions = {}) => {
const browser = await startFakeCdpBrowser({
...options,
commandResult(command, origin, frameReads) {
const override = options.commandResult?.(command, origin, frameReads);
if (override !== undefined) return override;
if (command.method === "DOMSnapshot.captureSnapshot") {
const nodes = {
nodeType: [9, 1, 1, 1, 1],
nodeName: [1, 2, 3, 3, 3],
nodeValue: [4, 4, 4, 4, 4],
parentIndex: [-1, 0, 1, 1, 1],
backendNodeId: [1, 2, 3, 4, 5],
attributes: [[], [], [5, 6], [5, 7], [5, 6, 8, 9]],
};
return {
strings: [
`${origin}/app`,
"#document",
"HTML",
"a",
"",
"xlink:href",
"/first",
"/second",
"href",
"/ordinary",
"https://excluded.example/page",
],
documents: [
{ documentURL: 0, nodes },
{
documentURL: 10,
nodes: { ...nodes, backendNodeId: [11, 12, 13, 14, 15] },
},
],
};
}
if (command.method === "DOM.describeNode")
return {
node: {
backendNodeId: command.params.backendNodeId,
nodeType: 1,
nodeName: "a",
isSVG: true,
},
};
return undefined;
},
});
trackBrowser(browser);
return browser;
};
const inspect = (browser: FakeCdpBrowser, signal?: AbortSignal) =>
new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
target_id: "allowed-page",
allowed_origins: [browser.allowedOrigin],
observation_ms: 0,
}),
signal === undefined ? undefined : { signal },
);
describe("CDP SVG identity at the snapshot boundary", () => {
it("describes only in-scope XLink candidates without a winning href", async () => {
const browser = await startBrowser();
const result = await inspect(browser);
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls.map(({ url }) => url)).toEqual(
["/first", "/second", "/ordinary"].map(
(path) => browser.allowedOrigin + path,
),
);
expect(
browser.commands
.filter(({ method }) => method === "DOM.describeNode")
.map(({ params }) => params),
).toEqual([
{ backendNodeId: 3, depth: 0 },
{ backendNodeId: 4, depth: 0 },
]);
});
it.each(["removed", "mismatched"])(
"retains partial metadata when a candidate is %s",
async (failure) => {
const browser = await startBrowser({
commandError: (command) =>
failure === "removed" &&
command.method === "DOM.describeNode" &&
command.params.backendNodeId === 3
? { code: -32_000, message: "No node found for given backend id" }
: undefined,
commandResult: (command) =>
failure === "mismatched" &&
command.method === "DOM.describeNode" &&
command.params.backendNodeId === 3
? {
node: {
backendNodeId: 99,
nodeType: 1,
nodeName: "a",
isSVG: true,
},
}
: undefined,
});
const result = await inspect(browser);
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls.map(({ url }) => url)).toEqual(
["/second", "/ordinary"].map((path) => browser.allowedOrigin + path),
);
expect(result.value.completeness.excluded).toContainEqual({
section: "metadata",
reason: "provider_unavailable",
count: 1,
});
expect(result.value.limitations).toContain(
"SVG identity was unavailable for 1 snapshotted XLink candidate nodes; their URL destinations remain unknown.",
);
},
);
it("stops querying after the first batch reports an unsupported method", async () => {
const browser = await startBrowser({
commandResult: manyCandidates,
unsupportedMethods: ["DOM.describeNode"],
});
const result = await inspect(browser);
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls).toEqual([]);
expect(result.value.completeness.excluded).toContainEqual({
section: "metadata",
reason: "provider_unavailable",
count: 25,
});
expect(descriptions(browser).length).toBeGreaterThan(0);
expect(descriptions(browser).length).toBeLessThanOrEqual(8);
});
it.each([
{ options: { closeOnMethod: "DOM.describeNode" }, reason: "disconnected" },
{
options: {
commandError: (command: { method: string }) =>
command.method === "DOM.describeNode"
? { code: -32_602, message: "Invalid parameters" }
: undefined,
},
reason: "protocol_error",
},
])(
"propagates $reason during node description",
async ({ options, reason }) => {
const browser = await startBrowser(options);
expect(await inspect(browser)).toMatchObject({
ok: false,
error: { _tag: "BrowserObservationError", reason },
});
},
);
it("cancels a pending description and detaches without closing the target", async () => {
const browser = await startBrowser({ hangOnMethod: "DOM.describeNode" });
const controller = new AbortController();
const pending = inspect(browser, controller.signal);
await expect.poll(() => descriptions(browser).length).toBeGreaterThan(1);
controller.abort();
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "inspect_web_page" },
});
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("Target.detachFromTarget");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
});
});
const manyCandidates: NonNullable<FakeOptions["commandResult"]> = (
command,
origin,
) => {
if (command.method !== "DOMSnapshot.captureSnapshot") return undefined;
const count = 25;
return {
strings: [
origin,
"#document",
"HTML",
"a",
"",
"xlink:href",
...Array.from({ length: count }, (_, index) => `/link-${String(index)}`),
],
documents: [
{
documentURL: 0,
nodes: {
nodeType: [9, 1, ...Array<number>(count).fill(1)],
nodeName: [1, 2, ...Array<number>(count).fill(3)],
nodeValue: Array<number>(count + 2).fill(4),
parentIndex: [-1, 0, ...Array<number>(count).fill(1)],
backendNodeId: Array.from(
{ length: count + 2 },
(_, index) => index + 1,
),
attributes: [
[],
[],
...Array.from({ length: count }, (_, index) => [5, index + 6]),
],
},
},
],
};
};
const descriptions = (browser: FakeCdpBrowser) =>
browser.commands.filter(({ method }) => method === "DOM.describeNode");
describe("CDP SVG query concurrency", () => {
it("bounds in-flight reads and preserves metadata order across reversed replies", async () => {
const browser = await startBrowser({
commandResult: manyCandidates,
hangOnMethod: "DOM.describeNode",
});
const controller = new AbortController();
const pending = inspect(browser, controller.signal);
try {
await expect.poll(() => descriptions(browser).length).toBeGreaterThan(1);
let replied = 0;
while (replied < 25) {
await expect
.poll(() => descriptions(browser).length)
.toBeGreaterThan(replied);
const batch = descriptions(browser).slice(replied);
expect(batch.length).toBeLessThanOrEqual(8);
for (const command of [...batch].reverse()) {
const id = Number(command.params.backendNodeId);
browser.emitRawMessage(
JSON.stringify({
id: command.id,
result: {
node: {
backendNodeId: id,
nodeType: 1,
nodeName: "a",
isSVG: id % 2 === 1,
},
},
}),
);
}
replied += batch.length;
}
const result = await pending;
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls.map(({ url }) => url)).toEqual(
Array.from(
{ length: 13 },
(_, index) => `${browser.allowedOrigin}/link-${String(index * 2)}`,
),
);
expect(descriptions(browser)).toHaveLength(25);
} finally {
controller.abort();
await pending;
}
});
it("cancels sibling reads on a fatal reply without waiting for hung nodes", async () => {
const browser = await startBrowser({
commandResult: manyCandidates,
hangOnMethod: "DOM.describeNode",
});
const controller = new AbortController();
const pending = inspect(browser, controller.signal);
try {
await expect.poll(() => descriptions(browser).length).toBeGreaterThan(1);
const batch = descriptions(browser);
browser.emitRawMessage(
JSON.stringify({
id: batch.at(-1)?.id,
error: { code: -32_602, message: "Invalid parameters" },
}),
);
await expect(pending).resolves.toMatchObject({
ok: false,
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
});
expect(descriptions(browser)).toHaveLength(batch.length);
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("Target.detachFromTarget");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
} finally {
controller.abort();
await pending;
}
});
});
@@ -0,0 +1,255 @@
import { describe, expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import type { WebPageInspection } from "../../../src/domain/browserObservationSchemas.js";
import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";
import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";
import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
import {
startHttpComparisonBrowser,
type HttpRequestObservation,
} from "../../fixtures/httpComparisonBrowser.js";
import { trackBrowser } from "./cdpBrowserProvider.support.js";
const inspect = async (browser: FakeCdpBrowser): Promise<WebPageInspection> => {
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
return result.value;
};
const capturePair = async (
before: readonly HttpRequestObservation[],
after: readonly HttpRequestObservation[],
): Promise<readonly [WebPageInspection, WebPageInspection]> => {
const fixture = await startHttpComparisonBrowser(before);
trackBrowser(fixture.browser);
const left = await inspect(fixture.browser);
fixture.setRequests(after);
return [left, await inspect(fixture.browser)];
};
const compareNetwork = (before: WebPageInspection, after: WebPageInspection) =>
compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: before },
after: { inspection: after },
}),
).dimensions.network;
const response = {
requestId: "request-before",
status: 200,
mimeType: "application/json",
} as const;
describe("HTTP comparison response coverage", () => {
it("does not compare an unavailable byte count with a completed response", async () => {
const [before, after] = await capturePair(
[response],
[{ ...response, requestId: "request-after", encodedDataLength: 100 }],
);
expect(before.network.requests[0]?.encoded_data_length).toBeNull();
expect(after.network.requests[0]?.encoded_data_length).toBe(100);
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
});
it("does not treat an unobserved response as a changed response", async () => {
const [before, after] = await capturePair(
[{ requestId: "request-before" }],
[{ ...response, encodedDataLength: 100 }],
);
expect(before.network.requests).toEqual([
expect.objectContaining({
status: null,
mime_type: null,
encoded_data_length: null,
}),
]);
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("retains observed status changes when response bytes are unavailable", async () => {
const [before, after] = await capturePair(
[response],
[{ ...response, status: 500 }],
);
expect(compareNetwork(before, after)).toMatchObject({
status: "changed",
changes: [expect.objectContaining({ change: "modified" })],
});
});
it.each([
{ mimeType: "text/plain", encodedDataLength: 100 },
{ mimeType: "application/json", encodedDataLength: 200 },
])("retains observed response changes: %j", async (change) => {
const [before, after] = await capturePair(
[{ ...response, encodedDataLength: 100 }],
[{ ...response, ...change }],
);
expect(compareNetwork(before, after).status).toBe("changed");
});
});
describe("HTTP comparison repeated request coverage", () => {
it("does not assign missing evidence by request order or transient ID", async () => {
const [before, after] = await capturePair(
[
{ ...response, encodedDataLength: 100 },
{ ...response, requestId: "second-before" },
],
[
{ ...response, requestId: "second-after", encodedDataLength: 200 },
{ ...response, requestId: "first-after", encodedDataLength: 100 },
],
);
expect(before.network.requests).toHaveLength(2);
expect(after.network.requests).toHaveLength(2);
expect(compareNetwork(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("compares complete byte counts even when another field is incomplete", async () => {
const [before, after] = await capturePair(
[
{ ...response, encodedDataLength: 100 },
{ requestId: "second-before", encodedDataLength: 200 },
],
[
{ requestId: "second-after", encodedDataLength: 300 },
{ ...response, requestId: "first-after", encodedDataLength: 100 },
],
);
expect(compareNetwork(before, after).status).toBe("changed");
});
it("preserves the association between complete response fields", async () => {
const [before, after] = await capturePair(
[
{ ...response, encodedDataLength: 100 },
{
...response,
requestId: "second-before",
status: 201,
encodedDataLength: 200,
},
],
[
{ ...response, requestId: "first-after", encodedDataLength: 200 },
{
...response,
requestId: "second-after",
status: 201,
encodedDataLength: 100,
},
],
);
expect(compareNetwork(before, after).status).toBe("changed");
});
});
it.each([
{
name: "a pending request in an empty inventory",
before: [],
after: [{ requestId: "pending" }],
},
{
name: "a known request beside an existing pending request",
before: [{ requestId: "pending" }],
after: [
{ requestId: "pending" },
{
...response,
requestId: "new",
path: "/api/new",
encodedDataLength: 100,
},
],
},
])("preserves additions and removals of $name", async (observations) => {
const [before, after] = await capturePair(
observations.before,
observations.after,
);
// Live CDP observations have attach-limited inventories. Their absence
// remains unknown even when a request is seen in the other capture.
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
// Project explicitly complete inventory coverage without changing the
// producer's request facts; response fields remain independently unknown.
markNetworkInventoriesComplete(before, after);
for (const [left, right, change] of [
[before, after, "added"],
[after, before, "removed"],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change })],
});
});
it("requires response field coverage even when capture sections are complete", async () => {
const [before, after] = await capturePair(
[response],
[{ ...response, encodedDataLength: 100 }],
);
markNetworkInventoriesComplete(before, after);
expect(compareNetwork(before, before).status).toBe("unknown");
expect(compareNetwork(before, after).status).toBe("unknown");
expect(compareNetwork(after, after).status).toBe("unchanged");
});
const markNetworkInventoriesComplete = (
...inspections: WebPageInspection[]
): void => {
const sections = new Set([
"network_requests",
"websocket_connections",
"websocket_frames",
]);
for (const inspection of inspections)
for (const key of [
"policy_filtered_sections",
"attach_limited_sections",
"truncated_sections",
"unavailable_sections",
] as const)
inspection.completeness[key] = inspection.completeness[key].filter(
(section) => !sections.has(section),
);
};
+55 -2
View File
@@ -45,8 +45,38 @@ const pageHtml = `<!doctype html><title>x</title>
<image id="img" xlink:href="/xl-image" />
<use id="use" xlink:href="/xl-use" />
<a id="out" xlink:href="https://cdn.example.test/out"><text>out</text></a>
<a id="move-desc" xlink:href="/xl-moved-desc"><text>move desc</text></a>
<a id="move-title" xlink:href="/xl-moved-title"><text>move title</text></a>
<desc id="desc-container">
<a xlink:href="/xl-html-desc">not an SVG link</a>
<a href="/html-desc">HTML link</a>
<svg><a xlink:href="/xl-nested-desc"><text>nested</text></a></svg>
</desc>
<title id="title-container">
<a xlink:href="/xl-html-title">not an SVG link</a>
<a href="/html-title">HTML link</a>
<svg><a xlink:href="/xl-nested-title"><text>nested</text></a></svg>
</title>
</svg>
<a id="html" xlink:href="/xl-html">html</a>
<script>
for (const kind of ['desc', 'title']) {
const container = document.getElementById(kind + '-container');
container.append(document.getElementById('move-' + kind));
for (const nested of [false, true]) {
const anchor = document.createElementNS('http://www.w3.org/2000/svg', 'a');
anchor.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',
'/xl-created-' + (nested ? 'nested-' : '') + kind);
const parent = nested
? container.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'g'))
: container;
parent.append(anchor);
}
const math = document.createElementNS('http://www.w3.org/1998/Math/MathML', 'a');
math.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '/xl-math-' + kind);
container.append(math);
}
</script>
`;
it.skipIf(chromeExecutable === undefined)(
@@ -143,17 +173,36 @@ it.skipIf(chromeExecutable === undefined)(
url: null,
destination_scope: "outside_policy",
}),
...[
"/html-desc",
"/html-title",
"/xl-nested-desc",
"/xl-nested-title",
"/xl-moved-desc",
"/xl-moved-title",
"/xl-created-desc",
"/xl-created-title",
"/xl-created-nested-desc",
"/xl-created-nested-title",
].map((path) =>
expect.objectContaining({
attribute: "href",
url: `${origin}${path}`,
destination_scope: "approved",
}),
),
]),
);
expect(
urls.some(
(url) =>
url.url?.endsWith("/xl-html") === true ||
url.url?.includes("/xl-html") === true ||
url.url?.includes("/xl-math") === true ||
url.url?.endsWith("/xlink-loses") === true,
),
).toBe(false);
expect(urls.every((url) => url.attribute === "href")).toBe(true);
expect(urls).toHaveLength(5);
expect(urls).toHaveLength(15);
} finally {
child.kill("SIGTERM");
if (!(await waitForExit(child, 2_000))) child.kill("SIGKILL");
@@ -173,6 +222,8 @@ const xhtmlPage = `<?xml version="1.0" encoding="UTF-8"?>
<svg:svg width="10" height="10">
<svg:a id="pa1" xlink:href="/xl-pa1"><svg:text>p</svg:text></svg:a>
<svg:image id="img" xlink:href="/xl-image"/>
<svg:desc><svg:a xlink:href="/xl-xml-desc"><svg:text>desc</svg:text></svg:a></svg:desc>
<svg:title><svg:a xlink:href="/xl-xml-title"><svg:text>title</svg:text></svg:a></svg:title>
<svg:foreignObject width="10" height="10">
<a id="fo-a" xlink:href="/xl-html-fo">no</a>
<h:a xmlns:h="http://www.w3.org/1999/xhtml" id="fo-h" xlink:href="/xl-h">no</h:a>
@@ -202,6 +253,8 @@ for (const { format, page, contentType, nodeNames, link, destinations } of [
destinations: [
"/xl-pa1",
"/xl-image",
"/xl-xml-desc",
"/xl-xml-title",
"/xl-fo-svg",
"/xl-orphan",
"/xl-custom",
+42 -83
View File
@@ -446,91 +446,50 @@ describe("web capture WebSocket payload byte coverage", () => {
});
describe("web capture diff", () => {
it("treats unavailable HTTP response facts as unknown while retaining observed changes", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const before = structuredClone(captured.value);
const request = before.network.requests[0];
if (request === undefined) throw new Error("Missing network request");
request.status = null;
request.mime_type = null;
request.encoded_data_length = null;
markSectionsComplete(before, [
"network_requests",
"websocket_connections",
"websocket_frames",
"json_body_shapes",
]);
for (const item of before.network.requests)
item.body_shapes.status = "not_approved";
it.each(["status", "mime_type"] as const)(
"keeps an independently unavailable HTTP %s unknown",
async (field) => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const observed = structuredClone(captured.value);
const request = observed.network.requests[0];
if (request === undefined) throw new Error("Missing network request");
request.status = 200;
request.mime_type = "application/json";
request.encoded_data_length = 100;
markSectionsComplete(observed, [
"network_requests",
"websocket_connections",
"websocket_frames",
"json_body_shapes",
]);
for (const item of observed.network.requests)
item.body_shapes.status = "not_approved";
expect(compareNetwork(observed, observed).status).toBe("unchanged");
const after = structuredClone(before);
const responseObserved = after.network.requests[0];
if (responseObserved === undefined)
throw new Error("Missing network request");
responseObserved.status = 200;
responseObserved.mime_type = "application/json";
responseObserved.encoded_data_length = 100;
expect(compareNetwork(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
expect(compareNetwork(after, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
expect(compareNetwork(before, before).status).toBe("unknown");
for (const field of [
"status",
"mime_type",
"encoded_data_length",
] as const) {
const partial = structuredClone(after);
const partial = structuredClone(observed);
partial.network.requests[0]![field] = null;
expect(compareNetwork(partial, after).status).toBe("unknown");
expect(compareNetwork(after, partial).status).toBe("unknown");
}
const inventoryBefore = structuredClone(before);
inventoryBefore.network.requests = [];
expect(compareNetwork(inventoryBefore, before)).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change: "added" })],
});
const statusChanged = structuredClone(after);
statusChanged.network.requests[0]!.status = 500;
expect(compareNetwork(after, statusChanged)).toMatchObject({
status: "changed",
changes: [expect.objectContaining({ change: "modified" })],
});
after.network.requests[0]!.encoded_data_length = null;
expect(compareNetwork(after, statusChanged).status).toBe("changed");
const repeated = structuredClone(statusChanged);
const duplicate = structuredClone(repeated.network.requests[0]!);
duplicate.status = 200;
duplicate.mime_type = "text/plain";
repeated.network.requests.push(duplicate);
const reassociated = structuredClone(repeated);
reassociated.network.requests[0]!.mime_type = "text/plain";
reassociated.network.requests.at(-1)!.mime_type = "application/json";
expect(compareNetwork(repeated, reassociated).status).toBe("changed");
repeated.network.requests[0]!.status = null;
expect(compareNetwork(repeated, reassociated).status).toBe("unknown");
});
for (const [left, right] of [
[partial, observed],
[observed, partial],
[partial, partial],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
},
);
it("ignores transient request IDs and capture-approval state", async () => {
const browser = await startFakeCdpBrowser();
@@ -29,6 +29,104 @@ const expectInvalidIncludedSourceMaps = (result: WebSourceMaps): void => {
expectInvalidSourceMaps({ ...result, status: "unavailable" });
};
it.each(["regular", "indexed"])(
"collects an HTTP %s source map with omitted names without accepting invalid names",
async (format) => {
const leaf = {
version: 3,
sources: ["src/main.ts"],
sourcesContent: ["import './dependency.ts';"],
mappings: "AAAA",
};
const texts = [
leaf,
{ ...leaf, names: [] },
{ ...leaf, names: null },
{ ...leaf, names: 42 },
{ ...leaf, names: [42] },
{ ...leaf, mappings: "AAAAA" },
].map((map) =>
JSON.stringify(
format === "indexed"
? {
version: 3,
sections: [{ offset: { line: 2, column: 5 }, map }],
}
: map,
),
);
const server = createServer((incoming, response) => {
response.setHeader("content-type", "application/source-map+json");
response.end(texts[Number(incoming.url?.slice(1))]);
});
try {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string")
throw new TypeError("Expected a TCP listener address");
const localOrigin = `http://127.0.0.1:${String(address.port)}`;
const result = await fetchWebSourceMaps(
texts.map((_, index) => ({
...request,
fetchUrl: `${localOrigin}/${index}`,
declaredUrl: `${localOrigin}/${index}`,
})),
input({ allowed_origins: [localOrigin] }),
);
expect(result.items.map(({ status }) => status)).toEqual([
"included",
"included",
"invalid",
"invalid",
"invalid",
"invalid",
]);
for (const [index, text] of texts.slice(0, 2).entries())
expect(result.items[index]).toMatchObject({
artifact: {
text,
bytes: Buffer.byteLength(text),
sha256: createHash("sha256").update(text).digest("hex"),
},
original_sources: [{ source: `${localOrigin}/src/main.ts` }],
mappings: [
{
generated_line: format === "indexed" ? 3 : 1,
generated_column: format === "indexed" ? 5 : 0,
source: `${localOrigin}/src/main.ts`,
original_line: 1,
original_column: 0,
name: null,
},
],
original_module_edges: [
{
from_source: `${localOrigin}/src/main.ts`,
resolved_source: `${localOrigin}/src/dependency.ts`,
},
],
});
for (const item of result.items.slice(2))
expect(item).toMatchObject({
artifact: null,
mappings: [],
original_sources: [],
});
} finally {
server.closeAllConnections();
if (server.listening)
await new Promise<void>((resolve, reject) => {
server.close((error) =>
error === undefined ? resolve() : reject(error),
);
});
}
},
);
it("parses ECMA-426 HTTP source-map prefixes while retaining exact response evidence", async () => {
const map = JSON.stringify({
version: 3,
@@ -1,3 +1,7 @@
import {
descriptorFailurePath,
expectRetainedDescriptor,
} from "../../fixtures/descriptorCloseFailure.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { writeFile } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
@@ -15,27 +19,22 @@ const cleanup = vi.hoisted(() => ({
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
return {
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (args[0] === cleanup.path) {
cleanup.handles.push(handle);
const close = handle.close.bind(handle);
handle.close = async () => {
if (cleanup.denied && handle.fd >= 0)
throw new Error("Descriptor close deliberately denied");
await close();
};
}
return handle;
},
};
const { withDescriptorCloseFailure } =
await import("../../fixtures/descriptorCloseFailure.js");
return withDescriptorCloseFailure(filesystem, cleanup);
});
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-capture-descriptor-");
@@ -67,14 +66,16 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
cleanup.path =
member === "capture"
? path
: member === "tool"
? command
: member === "limiter"
? limiter
: "/proc/self/limits";
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_packet_fields"
: "inspect_packet_capture";
cleanup.path = descriptorFailurePath(resource, {
capture: path,
tool: command,
limiter,
});
cleanup.denied = true;
cleanup.handles = [];
onTestFinished(async () => {
@@ -84,24 +85,45 @@ it
cleanup.path = "";
});
const service = new PacketCaptureService(provider);
const first = await service.inspect({ path, fields: ["frame.number"] });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const first = discovery
? await service.inspectFields({ query: "usb" })
: await service.inspect({ path, fields: ["frame.number"] });
expectRetainedDescriptor(first, cleanup, operation);
const launchCount = launches;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
let closingOperation = operation;
if (discovery) {
cleanup.denied = false;
const recovered = await service.inspect({
path,
fields: ["frame.number"],
});
expect(recovered.ok).toBe(true);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
expect(launches).toBeGreaterThan(launchCount);
cleanup.denied = true;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation: "inspect_packet_capture" },
});
expect(cleanup.handles.at(-1)?.fd).toBeGreaterThanOrEqual(0);
closingOperation = "inspect_packet_capture";
}
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation: closingOperation,
});
cleanup.denied = false;
await provider.close();
expect(cleanup.handles[0]?.fd).toBe(-1);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
},
);
@@ -11,6 +11,9 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createDeferred } from "../../fixtures/binarySession.js";
import { Cli } from "incur";
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
import { silentLogger } from "../../../src/logger.js";
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
const fixture = async (mode = "ok", failCleanup = false) => {
@@ -625,3 +628,34 @@ it("retains completed discovery on late cancellation and cleanup failure", async
await f.service.close();
}
});
it("preserves discovery resource ownership through CLI shutdown retries", async () => {
const f = await fixture("cleanup", true);
const cli = Cli.create("discovery-cleanup", { sync: false });
registerCaptureCommands(cli, silentLogger, {}, f.service);
let stdout = "";
try {
await cli.serve(
["inspect-packet-fields", "--query", "usb", "--format", "json"],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(JSON.parse(stdout)).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
cleanup_error: {
details: { operation: "inspect_packet_fields" },
},
},
},
});
} finally {
f.allowCleanup();
await f.service.close();
}
});
+10 -6
View File
@@ -180,14 +180,17 @@ describe("trace-dylib-resolution CLI", () => {
// A root below a symlinked directory that points outside the bundle.
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
await symlink(outside, join(app, "Contents/Linked"), "dir");
for (const [root, reason, message] of [
["../outside", "invalid_format", "Use a normalized path"],
["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
[
"Contents/Linked/Tool",
"invalid_value",
"resolves outside the analyzed root",
// Windows link text is outside the POSIX dyld path representation.
process.platform === "win32"
? "is not a regular file in the analyzed root"
: "resolves outside the analyzed root",
],
] as const) {
await expectRootInputError(cli, { app, root, reason, message });
@@ -378,7 +381,8 @@ cliTest(
},
);
describe.skipIf(process.getuid?.() === 0)(
// This permission fixture requires POSIX mode bits and a non-root caller.
describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
cliTest(
@@ -510,6 +514,8 @@ cliTest(
app,
"--root",
"Contents/MacOS/App",
"--architecture",
"arm64e",
"--json",
],
environment: ENVIRONMENT,
@@ -518,9 +524,7 @@ cliTest(
const trace = dylibResolutionResultSchema.parse(
parseEvidence(result.json).normalized_result,
);
expect(
trace.roots.filter(({ architecture }) => architecture === "arm64e"),
).toHaveLength(2);
expect(trace.roots).toHaveLength(2);
const environments = trace.findings
.filter(({ kind }) => kind === "dyld-environment-present")
.map(({ explanation }) =>
@@ -23,7 +23,7 @@ const analyze = async (cli: TestCli, extra = "") => {
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
expect(output.exitCode, output.stderr).toBe(0);
const { normalized_result: result } = z
.object({
normalized_result: javascriptApplicationAnalysisResultSchema,
@@ -122,6 +122,190 @@ cliTest(
},
);
cliTest(
"traces a nested contextBridge member through a unique IPC channel",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-nested-bridge-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
nested: { write: (value) => ipcRenderer.invoke("nested:write", value) }
});`,
"main.js": `const { ipcMain, clipboard } = require("electron");
ipcMain.handle("nested:write", (event, value) => clipboard.writeText(value));`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode, output.stderr).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
const paths = graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) =>
observation.properties.entry === "api.nested.write" &&
observation.properties.entry_kind === "bridge-member",
);
expect(
paths.some(
(observation) => observation.properties.step_kind === "exposure",
),
).toBe(true);
expect(
paths.some(
(observation) => observation.properties.step_kind === "terminal",
),
).toBe(true);
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel)).toEqual([
"nested:write",
]);
const traceInput = join(root, "trace-nested-input.json");
await writeFile(
traceInput,
JSON.stringify({
application: output.json,
seed: { kind: "api", value: "api.nested.write", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", traceInput, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({ normalized_result: applicationFeatureTraceResultSchema })
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(trace.paths.some((path) => path.contains_inference)).toBe(true);
},
);
cliTest(
"preserves exact bridge member segments through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-bridge-segments-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
const write = () => ipcRenderer.send("write");
contextBridge.exposeInMainWorld("desktop", {
"nested.write": write,
nested: { write },
__proto__: { inherited: write },
["__proto__"]: { own: write },
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.on("write", (event) => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const observations = application.graph.nodes.flatMap((node) =>
node.observations.filter(
(observation) =>
observation.properties.entry_kind === "bridge-member" &&
observation.properties.step_kind === "exposure",
),
);
const bridge = application.graph.nodes
.filter((node) => node.kind === "context-bridge-api")
.flatMap((node) => node.observations)
.find((observation) => observation.properties.api_key === "desktop");
expect(bridge?.properties.members).not.toContain("__proto__.inherited");
expect(bridge?.properties.members).toContain("__proto__.own");
const paths = observations.map(
(observation) => observation.properties.entry_path,
);
expect(paths).toEqual(
expect.arrayContaining([
["desktop", "nested.write"],
["desktop", "nested", "write"],
["desktop", "__proto__", "own"],
]),
);
expect(paths).not.toContainEqual(["desktop", "__proto__", "inherited"]);
const handlerPaths = application.graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) => observation.properties.entry_kind === "ipc-handler",
);
expect(handlerPaths.length).toBeGreaterThan(0);
expect(
handlerPaths.every(
(observation) => !("entry_path" in observation.properties),
),
).toBe(true);
},
);
cliTest(
"retains a nested bridge path when its IPC handler has no external terminal",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-nested-return-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
nested: { write: (value) => ipcRenderer.invoke("nested:write", value) }
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.handle("nested:write", (event, value) => value);`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
expect(
graph.nodes.some((node) =>
node.observations.some(
(observation) =>
observation.properties.entry === "api.nested.write" &&
observation.properties.step_kind === "exposure",
),
),
).toBe(true);
expect(
graph.edges.some(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
),
).toBe(false);
const traceInput = join(root, "trace-nested-input.json");
await writeFile(
traceInput,
JSON.stringify({
application: output.json,
seed: { kind: "api", value: "api.nested.write", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", traceInput, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({ normalized_result: applicationFeatureTraceResultSchema })
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(trace.graph?.nodes.length).toBeGreaterThan(1);
},
);
for (const surface of ["CLI", "stdio MCP"] as const) {
cliTest(
`preserves handler ambiguity and short-circuit factory paths through ${surface}`,
@@ -225,3 +409,89 @@ cliTest(
expect(joins.map((e) => e.properties.channel)).toEqual(["test:cut"]);
},
);
cliTest(
"keeps shallow bridge members when a sibling exceeds the nesting limit",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-deep-bridge-");
let deepMember = '() => e.ipcRenderer.send("deep:run")';
for (let index = 0; index < 129; index += 1)
deepMember = `{ level${index}: ${deepMember} }`;
await writeFixtureFiles(root, {
"preload.js": `const e=require("electron");
e.contextBridge.exposeInMainWorld("desktop", {
deep: ${deepMember},
shallow: () => e.ipcRenderer.send("shallow:run")
});`,
"main.js": `const e=require("electron");
e.ipcMain.on("shallow:run", event => event.sender.copy());
e.ipcMain.on("deep:run", event => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel)).toEqual([
"shallow:run",
]);
expect(
graph.nodes
.flatMap((node) => node.observations)
.some(
(observation) =>
observation.properties.entry === "desktop.shallow" &&
observation.properties.step_kind === "exposure",
),
).toBe(true);
},
);
cliTest(
"preserves empty bridge member segments in nested paths",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-electron-empty-bridge-key-",
);
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("desktop", {
"": { nested: { call: () => ipcRenderer.send("empty:key") } }
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.on("empty:key", event => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const observations = application.graph.nodes.flatMap(
(node) => node.observations,
);
expect(
observations.some(
(observation) =>
observation.properties.entry === "desktop..nested.call" &&
observation.properties.step_kind === "exposure",
),
).toBe(true);
expect(
application.graph.edges
.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
)
.map((edge) => edge.properties.channel),
).toEqual(["empty:key"]);
},
);
@@ -0,0 +1,77 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { webPageInspectionSchema } from "../../../src/domain/browserObservationSchemas.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
import { startHttpComparisonBrowser } from "../../fixtures/httpComparisonBrowser.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("CLI compares incomplete HTTP responses without inventing changes", async () => {
const root = await createTestTempDirectory("rea-http-comparison-");
const response = {
requestId: "request-1",
status: 200,
mimeType: "application/json",
};
const fixture = await startHttpComparisonBrowser([response]);
try {
const inspect = async () =>
webPageInspectionSchema.parse(
parseEvidence(
await runCliJson([
"inspect-web-page",
fixture.browser.endpoint,
"allowed-page",
"--observation-ms",
"0",
"--json",
]),
).normalized_result,
);
const pending = await inspect();
fixture.setRequests([{ ...response, encodedDataLength: 100 }]);
const finished = await inspect();
fixture.setRequests([{ ...response, status: 500, encodedDataLength: 100 }]);
const changed = await inspect();
expect(pending.network.requests).toMatchObject([
{ status: 200, mime_type: "application/json", encoded_data_length: null },
]);
expect(finished.network.requests).toMatchObject([
{ status: 200, mime_type: "application/json", encoded_data_length: 100 },
]);
const paths = [pending, finished, changed].map((_, index) =>
join(root, `capture-${String(index)}.json`),
);
await Promise.all(
[pending, finished, changed].map((inspection, index) =>
writeFile(paths[index]!, JSON.stringify({ inspection })),
),
);
for (const [left, right, status, count] of [
[0, 1, "unknown", 0],
[1, 0, "unknown", 0],
[0, 2, "changed", 1],
] as const) {
const compared = await runCliJson([
"compare-web-captures",
paths[left]!,
paths[right]!,
"--json",
]);
expect(compared).toMatchObject({
operation: "compare_web_captures",
normalized_result: {
overall_status: status,
dimensions: {
network: { status, total_changes: count },
},
},
});
}
} finally {
await fixture.browser.close();
}
}, 60_000);
@@ -0,0 +1,93 @@
import { describe, expect } from "vitest";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
import { elf } from "../../../src/domain/binaryTarget.fixture.js";
/**
* A headless IDA supervisor that completes the MCP handshake and then leaves
* every tool call unanswered, as an `idb_open` still running auto-analysis
* would. It exits when REA closes its input.
*/
const UNRESPONSIVE_SUPERVISOR = `import { createInterface } from "node:readline";
const tools = ["idb_open", "idb_list", "idb_close", "server_health", "list_funcs",
"lookup_funcs", "find_regex", "decompile", "disasm", "callees", "xrefs_to"];
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
for await (const line of createInterface({ input: process.stdin })) {
const request = JSON.parse(line);
if (request.method === "initialize")
send({ id: request.id, result: {
protocolVersion: request.params.protocolVersion,
capabilities: { tools: {} },
serverInfo: { name: "unresponsive-ida-fixture", version: "1" },
} });
else if (request.method === "tools/list")
send({ id: request.id, result: {
tools: tools.map((name) => ({ name, inputSchema: { type: "object" } })),
} });
}
`;
describe("headless IDA timeout through the one-shot CLI", () => {
workspaceCliTest(
"exits after a retained-cleanup failure instead of waiting on the supervisor",
async ({ cli, workspace }) => {
const supervisor = await workspace.write(
"supervisor.mjs",
UNRESPONSIVE_SUPERVISOR,
);
const workspaceRoot = await workspace.mkdir("ida-workspaces");
const registration = await workspace.write(
"ida-mcp.json",
JSON.stringify({
command: process.execPath,
args: [supervisor],
mode: "headless",
timeoutMs: 500,
workspaceRoot,
}),
);
const target = await workspace.write("target.elf", elf(2, 1, 62));
const result = await cli.run({
arguments: ["decompile", target, "main", "--json"],
environment: {
...workspace.environment,
REA_ANALYSIS_PROVIDER: "ida",
REA_IDA_MCP_CONFIG: registration,
REA_LOG_LEVEL: "silent",
},
timeoutMs: 30_000,
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "ida",
cleanup: "incomplete",
resources: [expect.stringContaining(workspaceRoot)],
cleanup_error: {
details: {
diagnostics: {
upstream_sessions: {
state: "unverified",
sessions: [
{
session_id: expect.stringMatching(/^rea-/),
backend: "worker",
owned: null,
input_path: null,
is_active: null,
},
],
},
},
},
},
},
});
},
);
});
+32
View File
@@ -561,3 +561,35 @@ describe("CLI result output surface", () => {
});
}, 60_000);
});
describe("streamed CLI filtered selections", () => {
it.each([
["raw_result", "json", "null\n"],
["raw_result", "jsonl", "null\n"],
["nested.value", "json", '{"nested":{"value":null}}\n'],
["missing", "json", "{}\n"],
["count", "json", "0\n"],
["enabled", "json", "false\n"],
] as const)(
"keeps the selected value of --filter-output %s in %s",
async (filter, format, expected) => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const output = createCliResultOutput(
["--format", format, "--filter-output", filter],
destination,
);
if (output === undefined) throw new Error("Missing JSON output surface");
await output.write(
{ raw_result: null, nested: { value: null }, count: 0, enabled: false },
{ command: "fixture", duration: "1ms", format },
);
expect(Buffer.concat(chunks).toString("utf8")).toBe(expected);
},
);
});
@@ -1,9 +1,13 @@
import { copyFile } from "node:fs/promises";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import {
inspectMachoSchema,
listArchitecturesSchema,
} from "../../../src/domain/native/nativeInspection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -34,27 +38,68 @@ const resultSchema = z.object({
describe.skipIf(process.platform !== "darwin")(
"native Mach-O CLI with echoed path text",
() => {
cliTest(
"does not read load commands or symbols from the file name",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-macho-echo-");
const inspect = async (name: string) => {
const path = join(directory, name);
await copyFile("/usr/bin/true", path);
const result = await cli.run({
arguments: ["inspect-macho", path, "--json"],
environment,
});
expect(result.exitCode).toBe(0);
const { provenance: _provenance, ...facts } = resultSchema.parse(
result.json,
).normalized_result;
return facts;
};
const forged = await inspect(FORGED_NAME);
expect(forged).toEqual(await inspect("tool"));
expect(JSON.stringify(forged)).not.toMatch(/forged|4242/u);
},
);
const lipoName = "tool\narchitecture forged\n offset 123\n size 32";
for (const [facts, command, filename] of [
["load commands or symbols", "inspect-macho", FORGED_NAME],
["FAT architecture records", "inspect-macho", lipoName],
["FAT architecture inventory", "list-architectures", lipoName],
["thin-file framing", "inspect-macho", "tool\nNon-fat file: forged"],
] as const) {
cliTest(
`does not read ${facts} from the file name`,
async ({ cli, processes }) => {
const directory = await createTestTempDirectory(
"rea-native-cli-echo-",
);
const fixture = join(directory, "fat-fixture");
const compiled = await processes.run(
"/usr/bin/xcrun",
[
"clang",
"-arch",
"arm64",
"-arch",
"x86_64",
resolve("tests/conformance/c/fixture.c"),
"-o",
fixture,
],
{ timeoutMs: 30_000 },
);
expect(compiled.exitCode, compiled.stderr).toBe(0);
const inspect = async (name: string) => {
const path = join(directory, name);
await copyFile(fixture, path);
const result = await cli.run({
arguments: [command, path, "--json"],
environment,
});
expect(result.exitCode).toBe(0);
const { provenance: _provenance, ...facts } = resultSchema.parse(
result.json,
).normalized_result;
return facts;
};
const ordinary = await inspect("tool");
// Prove this comparison exercised FAT framing, independent of host binaries.
const architectures =
listArchitecturesSchema.shape.architectures.parse(
ordinary.architectures,
);
expect(architectures.total).toBeGreaterThan(1);
if (command === "inspect-macho") {
const selected =
inspectMachoSchema.shape.selected_architecture.parse(
ordinary.selected_architecture,
);
expect(selected.container_file_offset).toBeGreaterThan(0);
}
const forged = await inspect(filename);
expect(forged).toEqual(ordinary);
expect(JSON.stringify(forged)).not.toMatch(/forged|4242/u);
},
60_000,
);
}
},
);
@@ -71,4 +71,27 @@ describe("native UI scenario CLI input", () => {
});
},
);
cliTest(
"refuses scenario steps on passive observation instead of dropping them",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"observe-native-ui",
"/provider-must-not-be-invoked",
"--pid",
"1",
"--window-id",
"1",
"--steps",
'[{"kind":"wait","milliseconds":0}]',
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.stdout).toContain("Unknown flag: --steps");
},
);
});
+30
View File
@@ -38,6 +38,36 @@ cliTest(
},
);
cliTest(
"rejects a 6502 image crossing the 16-bit boundary before provider startup",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-6502-cli-overflow-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
const result = await cli.run({
arguments: [
"inspect",
path,
"--target-format",
"raw-binary",
"--architecture",
"6502",
"--entry-point",
"0xffff",
"--provider",
"ghidra",
"--json",
],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { reason: expect.stringContaining("6502 address width") },
});
},
);
cliTest(
"rejects an unaligned AArch64 entry before provider startup",
async ({ cli }) => {
@@ -1,3 +1,5 @@
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -62,3 +64,42 @@ describe("scenario CLI schema diagnostics", () => {
});
});
});
for (const field of [
"executable_path",
"application_path",
"application_root",
] as const) {
cliTest(`names the unresolved Electron ${field}`, async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-path-");
const missing = join(root, "missing");
const result = await cli.run({
arguments: [
"capture-electron-scenario",
JSON.stringify({
executable_path: process.execPath,
application_path: root,
application_root: root,
actions: [],
[field]: missing,
}),
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: [field],
reason: "invalid_value",
message: expect.stringContaining("ENOENT"),
},
],
},
});
expect(JSON.stringify(result.json)).toContain(missing);
});
}
@@ -0,0 +1,75 @@
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { solidityMetadataSchema } from "../../../src/domain/evm/solidityMetadata.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
/** Real compiled worker and unchanged WASM engine; no Linux provider-admission claim. */
it.each([
["compiler", "00a164736f6c634300081e000a", "decoded"],
["integer", "00a1011bffffffffffffffff000b", "decoded"],
["BOM text", "00a1617864efbbbf610008", "decoded"],
["nested value", "00a1617881000005", "partial"],
["unavailable trailer", "00", "unavailable"],
["unsupported tag", "00a16178c0000005", "not-decoded"],
["floating point", "00a16178fa3f8000000008", "not-decoded"],
["invalid UTF-8", "00a1617861ff0005", "not-decoded"],
])(
"retains independent %s metadata through the actual worker",
async (kind, hex, status) => {
const directory = await createTestTempDirectory("rea-solidity-worker-");
const snapshot = join(directory, "selected.hex");
const reply = join(directory, "reply.json");
const request = join(directory, "request.json");
await writeFile(snapshot, hex);
await writeFile(
request,
JSON.stringify({
snapshot_path: snapshot,
reply_path: reply,
failure_marker_path: join(directory, "resource.failure"),
encoding: "hex",
}),
);
await promisify(execFile)(
process.execPath,
[
"--max-old-space-size=256",
"--disable-wasm-trap-handler",
new URL("../../../dist/evm/EvmoleInterfaceWorker.js", import.meta.url)
.pathname,
request,
],
{ timeout: 30_000, maxBuffer: 1024 * 1024 },
);
const value = JSON.parse(await readFile(reply, "utf8"));
expect(value.ok, JSON.stringify(value)).toBe(true);
expect(value.bytecode.hex).toBe(hex);
const metadata = solidityMetadataSchema.parse(value.bytecode.metadata);
expect(metadata.status).toBe(status);
if (kind === "integer")
expect(metadata.entries[0]?.value).toEqual({
kind: "integer",
value: "18446744073709551615",
});
if (kind === "compiler")
expect(metadata.compiler_version?.value).toBe("0.8.30");
if (kind === "BOM text")
expect(metadata.entries[0]?.value).toEqual({
kind: "text",
value: "\ufeffa",
});
if (kind === "nested value")
expect(metadata.entries[0]?.value).toEqual({
kind: "uninterpreted",
container: "array",
});
if (kind === "unavailable trailer") {
expect(metadata.bytecode_offset).toBeNull();
expect(metadata.entries).toEqual([]);
expect(metadata.compiler_version).toBeNull();
}
},
);
@@ -118,14 +118,21 @@ it("reuses only scheduled qualification and preserves every explicit full reques
).toBe("fast");
});
it("keeps every translated root README and authored guide on the documentation lane", async () => {
it("keeps every translated README and authored guide on the documentation lane", async () => {
const { directory, base } = await fixture();
const readmes = (await readdir(new URL("../../../", import.meta.url))).filter(
(name) => /^README(?:_.*)?\.md$/u.test(name),
);
const translated = (
await readdir(new URL("../../../docs/readme/", import.meta.url))
)
.filter((name) => /^README_.*\.md$/u.test(name))
.map((name) => `docs/readme/${name}`);
expect(readmes).toContain("README.md");
expect(translated.length).toBeGreaterThan(0);
const head = await change(directory, [
...readmes,
...translated,
"docs/guide.md",
"AGENTS.md",
"CONTRIBUTING.md",
@@ -198,7 +205,7 @@ it("emits an observational owner proposal without changing ordinary or full port
it("does not charge a documentation PR for unrelated implementation updates on main", async () => {
const { directory, base } = await fixture();
await git(directory, ["switch", "-c", "docs/change"]);
const head = await change(directory, ["README_zh-TW.md"]);
const head = await change(directory, ["docs/readme/README_zh-TW.md"]);
await git(directory, ["switch", "main"]);
const advancedBase = await change(directory, ["src/anotherProvider.ts"]);
expect(advancedBase).not.toBe(base);
@@ -240,7 +247,7 @@ it("retains complete checks when implementation is renamed into documentation",
it("keeps main pushes scoped when a successful ancestor baseline is available", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["README_ja.md"]);
const head = await change(directory, ["docs/readme/README_ja.md"]);
expect(await classify(directory, base, head, "push")).toMatchObject({
tier: "fast",
code: false,
@@ -449,6 +456,10 @@ it.each([
sqlite: false,
},
],
[
"scripts/verify-solidity-metadata.mjs",
{ code: true, evm: true, browser: false, package: false },
],
[
"src/browser/execution/evaluate.ts",
{
@@ -470,7 +481,10 @@ it.each([
{ code: false, website: true, package: false },
],
["scripts/website_i18n.py", { code: false, website: true, package: false }],
["README_ja.md", { code: false, docs: true, website: true, package: false }],
[
"docs/readme/README_ja.md",
{ code: false, docs: true, website: true, package: false },
],
[
".github/workflows/website-pages.yml",
{ code: false, website: true, package: false },
@@ -515,6 +529,10 @@ it.each([
"src/windows/Example.ts",
{ code: true, runtime: true, package: true, apple: false, evm: false },
],
[
"src/domain/javascript/javascriptRuntimeStaticCandidates.ts",
{ code: true, runtime: true, package: true, javascript_recovery: true },
],
["install.sh", { code: true, runtime: true, package: true, evm: false }],
[
".agents/skills/reverse-engineer-anything/SKILL.md",
@@ -920,7 +938,7 @@ it.each(["workflow_dispatch", "schedule"])(
it("honors ci:full for successive PR revisions", async () => {
const { directory, base } = await fixture();
const first = await change(directory, ["README.md"]);
const second = await change(directory, ["README_ja.md"]);
const second = await change(directory, ["docs/readme/README_ja.md"]);
for (const head of [first, second]) {
expect(
await classify(directory, base, head, "pull_request", true),
@@ -262,8 +262,8 @@ it("binds provider build reuse to the current run while keeping standalone dispa
),
),
);
const download = action.runs.steps.find(
(step) => step.uses === "actions/download-artifact@v4",
const download = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/download-artifact@"),
);
expect(download?.with).toEqual({
name: "${{ inputs.build_cache_artifact }}",
@@ -0,0 +1,412 @@
import {
access,
mkdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CLAUDE_DESKTOP_PACKAGE_FAMILY } from "../../../src/application/ClaudeDesktopConfigLocation.js";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { detectClients } from "../../../src/application/SetupHost.js";
import {
supportedClients,
type SetupClient,
} from "../../../src/application/SupportedClients.js";
import {
runUninstall,
systemUninstallHost,
} from "../../../src/application/Uninstall.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
/** The Windows registration setup writes, independent of the test host. */
const command = npxRegistrationCommand("win32");
const CONFIG = "claude_desktop_config.json";
const roots: string[] = [];
beforeEach(clearClientLocationEnvironment);
afterEach(async () => {
vi.unstubAllEnvs();
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
/** A Windows profile with separate roaming and local AppData roots. */
const windowsProfile = async () => {
const home = await createTestTempDirectory("rea-claude-desktop-");
roots.push(home);
const env = {
APPDATA: join(home, "AppData", "Roaming"),
LOCALAPPDATA: join(home, "AppData", "Local"),
};
const appDataConfig = join(env.APPDATA, "Claude", CONFIG);
const container = join(
env.LOCALAPPDATA,
"Packages",
CLAUDE_DESKTOP_PACKAGE_FAMILY,
);
const privateConfig = join(
container,
"LocalCache",
"Roaming",
"Claude",
CONFIG,
);
return { home, env, appDataConfig, container, privateConfig };
};
const claudeDesktop = (
home: string,
env: Readonly<Record<string, string>>,
): SetupClient => {
const client = supportedClients(home, "win32", env).find(
({ name }) => name === "claude_desktop",
);
if (client === undefined) throw new Error("claude_desktop is not supported");
return client;
};
const writeJson = async (path: string, value: unknown): Promise<void> => {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
};
const readJson = async (path: string): Promise<Record<string, unknown>> =>
JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
const reaEntry = { command: command[0], args: command.slice(1) };
describe("Windows Claude Desktop configuration location", () => {
it("uses AppData when no MSIX package storage exists", async () => {
const { home, env, appDataConfig } = await windowsProfile();
await mkdir(
join(env.LOCALAPPDATA, "Packages", "Contoso.App_8wekyb3d8bbwe"),
{
recursive: true,
},
);
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
expect(client.markerPath).toBe(dirname(appDataConfig));
expect(client.msixPackage).toBeUndefined();
expect(client.quitBeforeSetup).toBe(true);
});
it("uses the package-private copy that the MSIX package reads", async () => {
const { home, env, appDataConfig, container, privateConfig } =
await windowsProfile();
await writeJson(privateConfig, { preferences: { theme: "dark" } });
await writeJson(appDataConfig, { mcpServers: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(privateConfig);
expect(client.markerPath).toBe(container);
expect(client.msixPackage).toEqual({
packageFamilyName: CLAUDE_DESKTOP_PACKAGE_FAMILY,
privateConfigPath: privateConfig,
appDataConfigPath: appDataConfig,
virtualizedRoots: [env.APPDATA, env.LOCALAPPDATA],
processView: "direct",
});
expect(
(await detectClients(home, "win32", env)).map(({ name }) => name),
).toContain("claude_desktop");
});
it("uses AppData while the MSIX package has no private copy", async () => {
const { home, env, appDataConfig, container, privateConfig } =
await windowsProfile();
await mkdir(container, { recursive: true });
await writeJson(appDataConfig, { preferences: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
expect(client.msixPackage).toMatchObject({
privateConfigPath: privateConfig,
processView: "unknown",
});
// No private file shows whether the running package started this process.
const inspection = await inspectClientConfiguration(client, {}, command);
expect(inspection.status).toBe("invalid");
expect(inspection.status === "invalid" && inspection.remediation).toContain(
"Open Claude Desktop once if it has never run, quit it fully, then rerun setup",
);
});
it("creates the private copy when the MSIX package has no configuration", async () => {
const { home, env, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Local State"), {});
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(privateConfig);
expect(client.msixPackage?.processView).toBe("direct");
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "create" });
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "configured" });
expect(await readJson(privateConfig)).toEqual({
mcpServers: { rea: reaEntry },
});
});
it("reports an unrecognized Claude package instead of falling back to AppData", async () => {
const { home, env, appDataConfig } = await windowsProfile();
const foreign = join(env.LOCALAPPDATA, "Packages", "Claude_abcdefghjkmnp");
await mkdir(foreign, { recursive: true });
await writeJson(appDataConfig, { mcpServers: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(foreign);
expect(client.configPathError).toContain("unrecognized publisher");
expect(client.configPathError).toContain(CLAUDE_DESKTOP_PACKAGE_FAMILY);
expect(
(await detectClients(home, "win32", env)).map(({ name }) => name),
).not.toContain("claude_desktop");
const status = (
await readClientRegistrationStatuses(home, "unused", {
platform: "win32",
environment: env,
})
).find(({ client: name }) => name === "claude_desktop");
expect(status).toMatchObject({ state: "invalid", config_path: foreign });
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toMatchObject({ status: "invalid" });
});
});
describe("MSIX Claude Desktop registration lifecycle", () => {
it("registers in the private copy and reports an AppData-only entry as missing", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
const privateOriginal = {
coworkUserFilesPath: "C:\\Users\\a\\Claude",
preferences: { menuBarEnabled: false },
mcpServers: { other: { command: "other", args: ["serve"] } },
};
await writeJson(privateConfig, privateOriginal);
// Earlier setups wrote AppData, which the package never reads.
await writeJson(appDataConfig, { mcpServers: { rea: reaEntry } });
const appDataOriginal = await readFile(appDataConfig, "utf8");
const status = async () =>
(
await readClientRegistrationStatuses(home, "unused", {
platform: "win32",
environment: env,
})
).find(({ client }) => client === "claude_desktop");
expect(await status()).toMatchObject({
state: "missing",
config_path: privateConfig,
});
expect((await status())?.remediation).toContain(
"Quit Claude Desktop fully",
);
const client = claudeDesktop(home, env);
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toEqual({
status: "update",
backupPath: `${privateConfig}.rea.backup`,
});
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({
status: "configured",
backupPath: `${privateConfig}.rea.backup`,
});
expect(await readJson(privateConfig)).toEqual({
...privateOriginal,
mcpServers: {
...privateOriginal.mcpServers,
rea: reaEntry,
},
});
expect(await readJson(`${privateConfig}.rea.backup`)).toEqual(
privateOriginal,
);
expect(await readFile(appDataConfig, "utf8")).toBe(appDataOriginal);
expect(await status()).toMatchObject({
state: "aligned",
config_path: privateConfig,
});
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "unchanged" });
});
it("refuses to write from a process the running package started", async () => {
const { home, env, privateConfig } = await windowsProfile();
await writeJson(privateConfig, { preferences: {} });
const resolved = claudeDesktop(home, env);
if (resolved.msixPackage === undefined)
throw new Error("expected MSIX package storage");
// Only a packaged process sees AppData redirected; model that observation.
const client: SetupClient = {
...resolved,
msixPackage: { ...resolved.msixPackage, processView: "redirected" },
};
const inspection = await inspectClientConfiguration(client, {}, command);
expect(inspection.status).toBe("invalid");
expect(inspection.status === "invalid" && inspection.remediation).toContain(
"Quit Claude Desktop fully, then rerun setup from a terminal that Claude Desktop did not start",
);
expect(await readJson(privateConfig)).toEqual({ preferences: {} });
await configureClientConfiguration(resolved, {}, command);
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "already_current" });
});
it("refuses a write once the package reads a newer private copy", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Preferences"), {});
await writeJson(appDataConfig, { preferences: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
// Quitting the app after the plan was shown can save its private copy.
await writeJson(privateConfig, { preferences: {} });
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "failed", reason: "target_changed" });
expect(await readJson(appDataConfig)).toEqual({ preferences: {} });
expect(await readJson(privateConfig)).toEqual({ preferences: {} });
});
it("registers in AppData while the package has no private copy", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Preferences"), {});
await writeJson(appDataConfig, { preferences: { theme: "light" } });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
expect(client.msixPackage?.processView).toBe("direct");
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toMatchObject({ status: "configured" });
expect(await readJson(appDataConfig)).toEqual({
preferences: { theme: "light" },
mcpServers: { rea: reaEntry },
});
await expect(access(privateConfig)).rejects.toMatchObject({
code: "ENOENT",
});
});
});
describe("MSIX Claude Desktop uninstall", () => {
it("refuses uninstall when the package view is unknown", async () => {
const { home, env, appDataConfig, container } = await windowsProfile();
await mkdir(container, { recursive: true });
await writeJson(appDataConfig, { mcpServers: { rea: reaEntry } });
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, env, "win32"),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "claude_desktop",
status: "failed",
detail: expect.stringContaining("rerun uninstall"),
}),
);
expect(await readJson(appDataConfig)).toEqual({
mcpServers: { rea: reaEntry },
});
});
it("retains an unrelated rea-named entry when the package view is unknown", async () => {
const { home, env, appDataConfig, container } = await windowsProfile();
await mkdir(container, { recursive: true });
const unrelated = { mcpServers: { rea: { command: "unrelated-server" } } };
await writeJson(appDataConfig, unrelated);
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, env, "win32"),
);
expect(result.status).toBe("complete");
expect(await readJson(appDataConfig)).toEqual(unrelated);
});
it("blocks managed skill removal through redirected AppData before any removal", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Preferences"), {});
await mkdir(dirname(dirname(appDataConfig)), { recursive: true });
await symlink(dirname(privateConfig), dirname(appDataConfig), "dir");
const agents = join(env.APPDATA, "dsh", "agents");
const manifest = join(
agents,
"skills",
"reverse-engineer-anything",
"SKILL.md",
);
await mkdir(dirname(manifest), { recursive: true });
await writeFile(
manifest,
"---\nname: reverse-engineer-anything\n---\nmanaged fixture\n",
);
const environment = { ...env, DSH_AGENTS_HOME: agents };
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, environment, "win32"),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "skill",
status: "failed",
detail: expect.stringContaining("redirects its writes"),
}),
);
expect(await readFile(manifest, "utf8")).toContain("managed fixture");
});
it("removes REA from both the private copy and AppData on uninstall", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(privateConfig, {
preferences: {},
mcpServers: { other: { command: "other" }, rea: reaEntry },
});
await writeJson(appDataConfig, { mcpServers: { rea: reaEntry } });
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, env, "win32"),
);
expect(result.status).toBe("complete");
expect(await readJson(privateConfig)).toEqual({
preferences: {},
mcpServers: { other: { command: "other" } },
});
expect(await readJson(appDataConfig)).toEqual({ mcpServers: {} });
});
});
@@ -71,6 +71,7 @@ describe("client configuration filesystem lifecycle", () => {
"pi",
"hermes",
"qoder",
"droid",
"zcode",
"dsh",
"grok_bot",
@@ -1,5 +1,5 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { symlink, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it, vi } from "vitest";
@@ -14,7 +14,7 @@ import type {
import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
import { err, ok } from "../../../src/domain/result.js";
import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
@@ -40,6 +40,7 @@ import {
} from "../../fixtures/binarySession.js";
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
CAPABILITIES as GHIDRA_CAPABILITIES,
@@ -396,7 +397,85 @@ describe("snapshot output cleanup lifecycle", () => {
});
});
const verifyWindowsSnapshotAdmission = async (
selectedPath: "direct" | "junction",
): Promise<void> => {
const fixture = await createSnapshotReplayFixture(
"rea-direct-snapshot-junction-",
);
const rawPath = join(dirname(fixture.path), "image.bin");
await writeFile(rawPath, Buffer.from("a92a60", "hex"));
const linked = join(dirname(fixture.path), "linked");
const linkedPath = join(linked, basename(rawPath));
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, {
fixture: true,
});
const baseProvider = fixture.createProvider({
identity,
profile,
supportedOperations: ["search_strings"],
});
let rejectAdmission = false;
const provider: AnalysisProvider = {
...baseProvider,
createClient: (target, profile, context) => {
const client = baseProvider.createClient(target, profile, context);
return {
...client,
execute: (operation, parameters, options) =>
rejectAdmission && operation === "search_strings"
? Promise.resolve(
err(new ProviderAdapterError("ghidra", operation)),
)
: client.execute(operation, parameters, options),
};
},
};
const dependencies = fixture.dependencies(provider);
const arguments_ = { pattern: "fixture", document: "fixture" };
const options = {
snapshotPath: fixture.snapshotPath,
formatHint: "raw-binary" as const,
architecture: "6502" as const,
entryPoint: "0x8001",
};
const first = await runDirectAnalysis(
dependencies,
rawPath,
"search_strings",
arguments_,
options,
);
expect(first).toMatchObject({ operation: "search_strings" });
expect(fixture.starts).toHaveLength(1);
if (selectedPath === "junction")
await symlink(dirname(fixture.path), linked, "junction");
rejectAdmission = true;
const second = await runDirectAnalysis(
dependencies,
selectedPath === "junction" ? linkedPath : rawPath,
"search_strings",
arguments_,
options,
);
expect(second).toMatchObject({ error: "Analysis failed" });
expect(fixture.starts).toHaveLength(2);
expect(
fixture.calls.filter((call) => call === "search_strings"),
).toHaveLength(1);
};
describe("direct analysis composed snapshot replay", () => {
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot through a Windows junction",
() => verifyWindowsSnapshotAdmission("junction"),
);
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot before native admission on a canonical path",
() => verifyWindowsSnapshotAdmission("direct"),
);
it.each([
{
tool: "search_strings",
@@ -516,7 +595,7 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ tool: "inspect_native_api", arguments: { procedure: "0x1000" } },
{ tool: "trace_feature", arguments: { query: "fixture" } },
] as const)(
"persists and replays $tool with production Ghidra capability policies",
"persists $tool with production Ghidra capability policies",
async ({ tool, arguments: parameters }) => {
const fixture = await createSnapshotReplayFixture("rea-ghidra-workflow-");
const profile = createAnalysisProfile(
@@ -554,8 +633,14 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ snapshotPath: fixture.snapshotPath },
);
expect(replay).toEqual(first);
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
if (process.platform === "win32") {
// The first provider call in a new CLI session admits its source.
expect(fixture.starts).toHaveLength(2);
expect(fixture.calls.length).toBeGreaterThan(initialCalls.length);
} else {
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
}
},
);
});
@@ -0,0 +1,167 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { skillDestinations } from "../../../src/application/SetupSkill.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
/**
* The registration command setup writes on the host running the tests. Windows
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
*/
const command = npxRegistrationCommand(process.platform);
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const droidPath = (
home: string,
platform: NodeJS.Platform = "linux",
env: Parameters<typeof supportedClients>[2] = {},
) => supportedClients(home, platform, env).find(({ name }) => name === "droid");
describe("Factory Droid configuration paths", () => {
it("resolves the user MCP config file and marker directory", () => {
expect(droidPath("/home/a")).toEqual({
name: "droid",
displayName: "Factory Droid",
configPath: join("/home/a", ".factory", "mcp.json"),
markerPath: join("/home/a", ".factory"),
format: "json",
});
expect(droidPath("/Users/a", "darwin")?.configPath).toBe(
join("/Users/a", ".factory", "mcp.json"),
);
expect(droidPath("C:\\Users\\a", "win32")?.configPath).toBe(
join("C:\\Users\\a", ".factory", "mcp.json"),
);
});
it("resolves the personal skills directory beside the config root", () => {
expect(
skillDestinations("/home/a", ["droid"]).map(({ path }) => path),
).toEqual([
join("/home/a", ".factory", "skills", "reverse-engineer-anything"),
]);
});
});
describe("Factory Droid JSON registration", () => {
const droidClient = async () => {
const home = await createTestTempDirectory("rea-droid-");
const client = droidPath(home, process.platform);
if (client?.markerPath === undefined)
throw new Error("missing Factory Droid client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("upserts rea into mcpServers while preserving unrelated servers and permissions", async () => {
const { home, client } = await droidClient();
await writeFile(
client.configPath,
`{
"mcpServers": {
"other": {
"type": "stdio",
"command": "other",
"args": [],
"disabled": false
}
},
"persistentPermissions": {
"servers": {
"other": { "approvedAt": "2026-01-01T00:00:00.000Z" }
}
}
}`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({
type: "stdio",
command: "other",
args: [],
disabled: false,
});
expect(parsed.persistentPermissions).toEqual({
servers: { other: { approvedAt: "2026-01-01T00:00:00.000Z" } },
});
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client }) => client === "droid"),
).toMatchObject({ state: "aligned", command });
});
it("creates the mcpServers table in an existing config file without servers", async () => {
const { client } = await droidClient();
await writeFile(
client.configPath,
JSON.stringify({ persistentPermissions: { servers: {} } }, null, 2),
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.persistentPermissions).toEqual({ servers: {} });
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("registers into an empty config file", async () => {
const { client } = await droidClient();
await writeFile(client.configPath, "");
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("removes only the rea entry on uninstall", async () => {
const { home, client } = await droidClient();
await writeFile(
client.configPath,
JSON.stringify(
{ mcpServers: { other: { command: "other-server" } } },
null,
2,
),
);
await configureClientConfiguration(client, {}, command);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
expect(parsed.mcpServers.rea).toBeUndefined();
});
});
@@ -1,5 +1,6 @@
import { createReadStream } from "node:fs";
import { open, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join } from "node:path";
import { Readable } from "node:stream";
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
@@ -1122,11 +1123,16 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
if (result.ok) throw new Error("Duplicate libraries must be refused");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
message: expect.stringContaining(
`duplicate Flutter library members: ${path}:`,
),
},
],
},
});
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
"duplicate Flutter library members",
);
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(path);
expect(extract).not.toHaveBeenCalled();
},
);
@@ -1171,6 +1177,69 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
},
);
const expectSelectionIssue = async (
provider: FlutterBuildProvider,
path: string,
message: string,
): Promise<void> => {
for (const operation of [
"identify_flutter_build",
"inspect_dart_aot",
] as const) {
const result = await provider.execute({ operation, input: { path } });
if (result.ok) throw new Error("A non-file APK selection must fail");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["path"],
reason: "invalid_format",
message: `${message}: ${path}`,
},
],
},
});
}
};
it("names a missing or non-file APK selection instead of blaming package bytes", async () => {
const root = await createTestTempDirectory("rea-flutter-selection-");
const provider = new FlutterBuildProvider();
onTestFinished(() => provider.close());
await expectSelectionIssue(
provider,
join(root, "absent.apk"),
"Selected APK does not exist",
);
await expectSelectionIssue(
provider,
root,
"Selected APK is not a regular file",
);
});
// Windows listens on named pipes rather than filesystem sockets.
it.skipIf(process.platform === "win32")(
"names an unopenable Unix socket APK selection as a non-file",
async () => {
const root = await createTestTempDirectory("rea-flutter-socket-");
const socketPath = join(root, "s.sock");
const socket = createServer();
await new Promise<void>((resolve) => socket.listen(socketPath, resolve));
onTestFinished(
() => new Promise<void>((resolve) => socket.close(() => resolve())),
);
const provider = new FlutterBuildProvider();
onTestFinished(() => provider.close());
await expectSelectionIssue(
provider,
socketPath,
"Selected APK is not a regular file",
);
},
);
it.each(["EACCES", "EPERM"] as const)(
"preserves %s at the shared source admission boundary",
async (code) => {
@@ -0,0 +1,79 @@
import { open, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { readElfBuildIds } from "../../../src/flutter/ElfBuildId.js";
import {
appendElfRanges,
engineFixtureImage,
} from "../../../src/flutter/FlutterBuild.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const note = Buffer.from(
"040000000800000003000000474e55000123456789abcdef",
"hex",
);
it.each([
{ bits: 32, table: "program" },
{ bits: 64, table: "section" },
] as const)(
"bounds dense $bits-bit $table note ranges while retaining examined IDs",
async ({ bits, table }) => {
const count = 30_000;
const image = appendElfRanges(
engineFixtureImage({
bits,
notes: Buffer.concat([note, Buffer.alloc(count)]),
ownership: "both",
}),
table,
Array.from({ length: count }, (_, index) => ({
type: table === "program" ? 4 : 7,
offset: 0x400 + note.length + index,
size: 1,
})),
);
const root = await createTestTempDirectory("rea-flutter-notes-");
const path = join(root, "engine.so");
await writeFile(path, image);
const file = await open(path, "r");
const read = vi.spyOn(file, "read");
try {
const result = await readElfBuildIds(file, image.length, undefined);
expect(result.candidates).toEqual(["0123456789abcdef"]);
expect(result.failures).toContainEqual({
reason: expect.stringContaining("note-range"),
});
expect(read.mock.calls.length).toBeLessThanOrEqual(1027);
} finally {
await file.close();
}
},
);
it("deduplicates shared program/section notes and skips empty ranges before charging inventory", async () => {
const ranges = Array.from({ length: 2000 }, (_, index) => ({
type: 7,
offset: index % 2 === 0 ? 0x400 : index,
size: index % 2 === 0 ? note.length : 0,
}));
const image = appendElfRanges(
engineFixtureImage({ notes: note, ownership: "both" }),
"section",
ranges,
);
const root = await createTestTempDirectory("rea-flutter-notes-");
const path = join(root, "engine.so");
await writeFile(path, image);
const file = await open(path, "r");
const read = vi.spyOn(file, "read");
try {
expect(await readElfBuildIds(file, image.length, undefined)).toEqual({
candidates: ["0123456789abcdef"],
failures: [],
});
expect(read.mock.calls.length).toBe(4);
} finally {
await file.close();
}
});
@@ -87,3 +87,43 @@ it.each([
);
},
);
it("bounds the Java version probe and reports an over-budget probe as a failed Java check", async () => {
const root = await createTestTempDirectory("rea-java-probe-bound-");
const configuredHome = join(root, "selected-jdk");
const installDir = join(root, "ghidra");
await mkdir(join(installDir, "Ghidra"), { recursive: true });
await writeFile(
join(installDir, "Ghidra", "application.properties"),
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
);
// A chatty or hostile JVM that overruns the capture budget: spawnSync reports
// ENOBUFS, which the probe already treats as a failed observation.
mockSpawnSync.mockReturnValue({
stdout: "",
stderr: "java.version = 21.0.11\n",
status: null,
error: Object.assign(new Error("spawnSync /java ENOBUFS"), {
code: "ENOBUFS",
}),
});
const inspection = inspectGhidraInstallation({
environment: {},
installDir,
javaHome: configuredHome,
});
const [, , options] = mockSpawnSync.mock.calls[0] as [
string,
readonly string[],
{ readonly maxBuffer?: number },
];
expect(options.maxBuffer).toBe(1024 * 1024);
expect(inspection.javaVersion).toBeNull();
expect(inspection.javaHome).toBe(configuredHome);
expect(inspection.checks.find(({ name }) => name === "java")).toMatchObject({
status: "failed",
code: "runtime_missing",
});
});
@@ -237,6 +237,38 @@ mcp_servers:
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
it("keeps unrelated numbers as written, including Discord IDs", async () => {
const { home, client } = await hermesClient();
// Hermes reads these exactly: two IDs one apart, an octal mode, a float.
const original = `discord:
free_response_channels:
- 1187654321098765432
channel_prompts:
1187654321098765433: Build questions.
1187654321098765434: Release questions.
mode: 0600
min_score: 0.0000001
mcp_servers:
other:
command: other-server
`;
await writeFile(client.configPath, original);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text.startsWith(original)).toBe(true);
expect(parseYaml(text, { intAsBigInt: true })).toMatchObject({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
it("creates config.yaml when Hermes has no configuration yet", async () => {
const { client } = await hermesClient();
expect(
@@ -696,6 +696,49 @@ describe("NIB projection byte amplification", () => {
});
});
cliTest(
"compiled CLI preserves distinct NIB keys and class identity",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-nib-name-identity-");
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await mkdir(join(bundle, "Contents", "MacOS"), { recursive: true });
await writeFile(
join(bundle, "Contents", "MacOS", "App"),
thinMach(0xfeedfacf, 0x0100000c),
);
await writeFile(
join(bundle, "Contents", "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
await writeFile(
join(resources, "Identity.nib"),
encodeNibArchiveFixture({
classes: ["\uFEFFWidget"],
objects: [{ classIndex: 0, values: { count: 1, "\uFEFFcount": 2 } }],
}),
);
const output = await cli.run({
arguments: ["decode-interface-builder", bundle, "--json"],
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
});
expect(output.exitCode, output.stderr).toBe(0);
const result = interfaceBuilderAnalysisSchema.parse(
parseEvidence(output.json).normalized_result,
);
expect(result.graph.nodes).toContainEqual(
expect.objectContaining({
attributes: expect.objectContaining({
class_name: "\uFEFFWidget",
nibValues: { count: 1, "\uFEFFcount": 2 },
}),
}),
);
expect(JSON.stringify(result)).toContain("\uFEFFWidget");
},
);
cliTest(
"compiled CLI preserves a good archive and reports repeated key and data omissions",
async ({ cli }) => {
@@ -1060,6 +1103,142 @@ describe("NIBArchive UIKit event connections", () => {
"UIRuntimeEventConnection",
);
});
it("reports a runtime connection with no resolvable owner as an omission", async () => {
const root = await createTestTempDirectory("rea-ib-ownerless-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
// The connector is recognized by class, but carries no UISource reference,
// so no connection can be projected from it.
await writeFile(
join(bundle, "Cell.nib"),
encodeNibArchiveFixture({
classes: [
"UIProxyObject",
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"NSString",
],
objects: [
{ classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } },
{ classIndex: 1, values: { UIClassName: { ref: 6 } } },
{ classIndex: 2, values: {} },
{
classIndex: 3,
values: { UIDestination: { ref: 1 }, UIEventMask: 64 },
},
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
],
}),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
});
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Cell.nib",
status: "partial",
reason: "connection_unresolved",
examined: 0,
omitted: 1,
}),
);
// The keyed-archive producer counts a recognized connector it cannot emit,
// so this producer has to report the same document total for the same
// connector rather than zero.
expect(analysis.documents).toContainEqual(
expect.objectContaining({
relative_path: "Cell.nib",
connection_count: 1,
}),
);
expect(analysis.graph.truncated).toBe(true);
expect(analysis.limitations).toContain(
"Some recognized NIBArchive connectors declare no resolvable owner; they carry no connection evidence and are reported as omissions.",
);
});
});
describe("NIBArchive ownerless connector accounting", () => {
it("keeps a connection dropped by the limit reported as a limit", async () => {
const root = await createTestTempDirectory("rea-ib-ownerless-limit-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
// Two resolvable connectors and one ownerless connector with the limit
// below the resolvable count, so this facet has both causes at once. Only a
// higher limit recovers the dropped connection, so that is the reason the
// caller needs, exactly as the keyed-archive producer reports it.
await writeFile(
join(bundle, "Cell.nib"),
encodeNibArchiveFixture({
classes: [
"UIProxyObject",
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"NSString",
],
objects: [
{ classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } },
{ classIndex: 1, values: { UIClassName: { ref: 6 } } },
{ classIndex: 2, values: {} },
{
classIndex: 3,
values: {
UISource: { ref: 2 },
UIDestination: { ref: 1 },
UILabel: { ref: 7 },
UIEventMask: 64,
},
},
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
{ classIndex: 4, values: { "NS.bytes": "buildTapped:" } },
{
classIndex: 3,
values: {
UISource: { ref: 4 },
UIDestination: { ref: 1 },
UILabel: { ref: 7 },
},
},
{
classIndex: 3,
values: { UIDestination: { ref: 1 }, UIEventMask: 64 },
},
],
}),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
limits: { max_connections: 1 },
});
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Cell.nib",
status: "partial",
reason: "connection_limit_reached",
examined: 1,
omitted: 2,
}),
);
expect(analysis.documents).toContainEqual(
expect.objectContaining({
relative_path: "Cell.nib",
connection_count: 3,
}),
);
});
});
// This exact file is already selected by the unchanged native Apple CI lane.
@@ -9,7 +9,10 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { matchJavaScriptApplicationVersions } from "../../../../src/domain/javascript/javascriptApplicationVersionKeys.js";
import { findApplicationFeatureSeeds } from "../../../../src/domain/javascript/javascriptFeatureSeed.js";
import { traceApplicationFeatureInputSchema } from "../../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
import {
applicationFeatureSeedSchema,
traceApplicationFeatureInputSchema,
} from "../../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
const analyzeSource = async (
@@ -76,6 +79,59 @@ it("retains empty literal evidence across the application boundary surfaces", as
);
});
it("keeps bridge entry paths stable through worker validation and API seed matching", async () => {
const output = await analyzeSource(`
const { contextBridge, ipcRenderer } = require("electron");
const literal = () => ipcRenderer.send("literal");
const nested = () => ipcRenderer.send("nested");
contextBridge.exposeInMainWorld("desktop", {
"nested.write": literal,
nested: { write: nested },
});
`);
const semanticPathIds = new Set(
(output.semantic_graph?.nodes ?? [])
.map(({ properties }) => properties.path_id)
.filter((pathId): pathId is string => typeof pathId === "string"),
);
const applicationPathIds = new Set(
output.graph.nodes.flatMap(({ observations }) =>
observations
.map(({ properties }) => properties.path_id)
.filter((pathId): pathId is string => typeof pathId === "string"),
),
);
expect(semanticPathIds).toEqual(applicationPathIds);
const matches = findApplicationFeatureSeeds(
output.graph.nodes,
applicationFeatureSeedSchema.parse({
kind: "api",
value: "desktop.nested.write",
entry_path: ["desktop", "nested.write"],
}),
);
expect(matches).toHaveLength(1);
expect(
output.graph.nodes
.find(({ node_id: nodeId }) => nodeId === matches[0]?.node_id)
?.observations.some(
({ properties }) =>
Array.isArray(properties.entry_path) &&
properties.entry_path.join("\0") === "desktop\0nested.write",
),
).toBe(true);
expect(
findApplicationFeatureSeeds(
output.graph.nodes,
applicationFeatureSeedSchema.parse({
kind: "api",
value: "desktop.nested.write",
}),
),
).toHaveLength(2);
});
it("analyzes a plain long-line loader without package metadata", async () => {
const output = await analyzeSource(
`var Module = {}; fetch(""); new Worker(""); var payload = "${"x".repeat(65_536)}";`,
@@ -240,8 +296,18 @@ it.each([
[{ kind: "channel", value: "" }, false],
[{ kind: "channel", value: "", match: "contains" }, false],
[{ kind: "node-id", value: "", match: "exact" }, false],
[{ kind: "api", value: "desktop.nested.write" }, true],
[
{
kind: "api",
value: "desktop.nested.write",
entry_path: ["desktop", "nested.write"],
},
true,
],
[{ kind: "channel", value: "channel", entry_path: ["channel"] }, false],
] as const)(
"validates empty seed %j at runtime and in the advertised schema",
"validates seed %j at runtime and in the advertised schema",
(seed, accepted) => {
expect(seedSchema.safeParse(seed).success).toBe(accepted);
expect(validateAdvertisedSeed(seed)).toBe(accepted);
@@ -388,7 +388,7 @@ it("produces deterministic ASAR graphs with unpacked native linkage and complete
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
const first = await reconstructJavaScriptArtifact({
input_path: archive,
@@ -487,7 +487,7 @@ it("keeps ASAR analysis usable when unpacked native companion bytes are absent",
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const snapshot = await scanArtifactInventory(archive);
@@ -515,7 +515,7 @@ it("recurses into filesystem-backed ASAR containers without losing container-rel
const resources = join(outer, "resources");
await mkdir(resources, { recursive: true });
await createPackageWithOptions(source, join(resources, "app.asar"), {
unpack: "**/*.node",
unpack: "*.node",
});
const result = await reconstructJavaScriptArtifact({
@@ -444,73 +444,97 @@ describe("JavaScript application workflow error diagnostics", () => {
});
});
const RUNTIME_PATH_CASES = [
{
name: "case-sensitive POSIX input root",
root: null,
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
status: "unknown",
basis: "none",
},
{
name: "case-sensitive POSIX mapping root",
root: "/runtime/App",
path: "/runtime/app/renderer.js",
status: "unknown",
basis: "none",
},
{
name: "matching POSIX mapping root",
root: "/runtime/App",
path: "/runtime/App/renderer.js",
status: "matched",
basis: "operator-file-mapping",
},
{
name: "case-insensitive Windows mapping root",
root: String.raw`C:\runtime\App`,
path: String.raw`c:\runtime\app\renderer.js`,
status: "matched",
basis: "operator-file-mapping",
},
] as const;
describe("JavaScript runtime reconciliation local paths", () => {
it.each([
{
name: "case-sensitive POSIX input root",
root: null,
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
status: "unknown",
},
{
name: "case-sensitive POSIX mapping root",
root: "/runtime/App",
path: "/runtime/app/renderer.js",
status: "unknown",
},
{
name: "matching POSIX mapping root",
root: "/runtime/App",
path: "/runtime/App/renderer.js",
status: "matched",
},
{
name: "case-insensitive Windows mapping root",
root: String.raw`C:\runtime\App`,
path: String.raw`c:\runtime\app\renderer.js`,
status: "matched",
},
])("uses $name on every host", ({ root, path, status }) => {
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const original = base.runtime_observations[0]!;
const inspection = electronPageInspectionSchema.parse(
original.normalized_result,
);
const runtime = createEvidence(undefined, original.provider, {
predicateType: original.predicate_type,
operation: original.operation,
parameters: { ...original.parameters, include_script_sources: false },
result: {
...inspection,
scripts: {
...inspection.scripts,
items: inspection.scripts.items.map((script) => ({
...script,
file_path: path,
source: { included: false, reason: "not-requested" },
})),
it.each(RUNTIME_PATH_CASES)(
"uses $name on every host",
({ root, path, status, basis }) => {
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const original = base.runtime_observations[0]!;
const inspection = electronPageInspectionSchema.parse(
original.normalized_result,
);
// Keep target and script coordinates consistent so an unrelated target
// cannot activate the static layer after its script mapping was rejected.
const runtime = createEvidence(undefined, original.provider, {
predicateType: original.predicate_type,
operation: original.operation,
parameters: { ...original.parameters, include_script_sources: false },
result: {
...inspection,
target: { ...inspection.target, file_path: path },
scripts: {
...inspection.scripts,
items: inspection.scripts.items.map((script) => ({
...script,
file_path: path,
source: { included: false, reason: "not-requested" },
})),
},
},
},
confidence: original.confidence,
authority: original.authority,
});
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: base.static_layers.map((layer) => ({
...layer,
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
})),
runtime_observations: [runtime],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
);
expect(
result.reconciliations.find(
({ entity_kind }) => entity_kind === "script",
),
).toMatchObject({ status });
});
confidence: original.confidence,
authority: original.authority,
});
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: base.static_layers.map((layer) => ({
...layer,
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
})),
runtime_observations: [runtime],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
);
expect(
result.reconciliations.find(
({ entity_kind }) => entity_kind === "script",
),
).toMatchObject({ status, basis });
expect(
result.static_load_states.find(
({ kind }) => kind === "javascript-asset",
),
).toMatchObject(
status === "matched"
? { status: "loaded", reason: "runtime-script-correspondence" }
: { status: "unknown", reason: "layer-outside-runtime-scope" },
);
expect(result.static_layers[0]?.runtime_mappings).toEqual(
root === null ? [] : [{ kind: "file-root", root, artifact_prefix: "" }],
);
},
);
it("resolves relative file mapping roots before deriving result Evidence", () => {
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
@@ -105,6 +105,34 @@ it("keeps a contradicted nested ASAR opaque during JavaScript reconstruction", a
expect(result.graph.coverage.omitted_count).toBeNull();
});
it("keeps an ASAR-named file without an ASAR header opaque during JavaScript reconstruction", async () => {
const root = await createTestTempDirectory("rea-opaque-asar-name-");
await writeFile(join(root, "main.js"), "export const outer = true;\n");
// Inventory records this file as ordinary bytes and does not expand it.
await writeFile(join(root, "ordinary.asar"), "ordinary bytes");
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
try {
const read = await readJavaScriptArtifactFiles(reader, snapshot);
expect(read.files.map(({ path }) => path)).toEqual(["main.js"]);
expect(read.containers).toEqual([]);
} finally {
await reader.close();
}
const analyzed = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!analyzed.ok) throw analyzed.error;
const result = javascriptApplicationAnalysisResultSchema.parse(
analyzed.value.normalized_result,
);
expect(result.statistics.nested_asar_containers).toBe(0);
expect(result.integrity_contradictions).toEqual([]);
});
it("retains semantic resource limits alongside recorded integrity contradictions", async () => {
const { archive } = await createStrippedAsarAddon([
{ path: "app.js", contents: primitiveCandidateExpansionSource() },
@@ -37,6 +37,53 @@ import {
const root = fileURLToPath(new URL("../../..", import.meta.url));
const temporaryRoots: string[] = [];
const README_FACT_FIXTURE_PATHS = [
"README.md",
"docs/readme/README_zh.md",
"docs/readme/README_ja.md",
"docs/readme/README_ko.md",
"docs/readme/README_ar.md",
"website/locales/languages.json",
"docs/installation.md",
"AGENTS.md",
".github/pull_request_template.md",
] as const;
const README_LINK_DRIFT_MUTATIONS = [
[
"(../installation.md#supported-agents)",
"(../installation.md#missing-agents)",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-CN/missing/",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-TW/guides/native/",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-CN/guides/native/?other=1",
],
[
'src="../assets/rea-hopper-analysis.png"',
'src="../assets/missing-hopper.png"',
],
['href="https://discord.gg/GkcryMnJDM"', 'href="https://discord.gg/missing"'],
] as const;
const seedReadmeFactFixture = async (directory: string) => {
for (const path of README_FACT_FIXTURE_PATHS) {
const destination = join(directory, path);
await mkdir(dirname(destination), { recursive: true });
await copyFile(join(root, path), destination);
}
await mkdir(join(directory, "skills/reverse-engineer-anything"), {
recursive: true,
});
};
afterEach(async () => {
await Promise.all(
temporaryRoots
@@ -176,49 +223,14 @@ describe("canonical product catalog drift", () => {
it("keeps translated readmes linked to canonical setup and tool details", async () => {
const directory = await createTestTempDirectory("rea-readme-facts-");
temporaryRoots.push(directory);
const paths = [
"README.md",
"README_zh.md",
"README_ja.md",
"README_ko.md",
"README_ar.md",
"website/locales/languages.json",
"docs/installation.md",
"AGENTS.md",
".github/pull_request_template.md",
];
for (const path of paths) {
const destination = join(directory, path);
await mkdir(dirname(destination), { recursive: true });
await copyFile(join(root, path), destination);
}
await mkdir(join(directory, "skills/reverse-engineer-anything"), {
recursive: true,
});
const translatedPath = join(directory, "README_zh.md");
await seedReadmeFactFixture(directory);
const translatedPath = join(directory, "docs/readme/README_zh.md");
const translated = await readFile(translatedPath, "utf8");
const catalog = await createProductCatalog(root);
await expect(documentationFactIssues(directory, catalog)).resolves.toEqual(
[],
);
for (const [original, changed] of [
[
"(docs/installation.md#supported-agents)",
"(docs/installation.md#missing-agents)",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-CN/missing/",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-TW/guides/native/",
],
[
"https://rea.tools/zh-CN/guides/native/",
"https://rea.tools/zh-CN/guides/native/?other=1",
],
] as const) {
for (const [original, changed] of README_LINK_DRIFT_MUTATIONS) {
expect(translated).toContain(original);
await writeFile(
translatedPath,
@@ -228,11 +240,10 @@ describe("canonical product catalog drift", () => {
await expect(
documentationFactIssues(directory, catalog),
).resolves.toEqual([
"README_zh.md: documentation links differ from README.md",
"docs/readme/README_zh.md: documentation links differ from README.md",
]);
}
});
it("fails check mode without rewriting a stale generated artifact", async () => {
const directory = await createTestTempDirectory("rea-generated-check-");
temporaryRoots.push(directory);
@@ -1,5 +1,11 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import {
mkdir,
readFile,
realpath,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -7,6 +13,37 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("raw-binary admission", () => {
it("preserves the requested raw path for Windows reparse admission", async () => {
const directory = await createTestTempDirectory("rea-raw-linked-");
const actual = join(directory, "actual");
const linked = join(directory, "linked");
await mkdir(actual);
const bytes = Buffer.from("a90160", "hex");
await writeFile(join(actual, "fixture.bin"), bytes);
await symlink(
actual,
linked,
process.platform === "win32" ? "junction" : "dir",
);
const requested = join(linked, "fixture.bin");
const canonical = await realpath(requested);
const target = await parseBinaryTarget("linked/fixture.bin", {
cwd: directory,
formatHint: "raw-binary",
architecture: "6502",
entryPoint: "0x8000",
});
expect(target).toMatchObject({
ok: true,
value: {
path: canonical,
sourcePath: process.platform === "win32" ? requested : canonical,
sha256: createHash("sha256").update(bytes).digest("hex"),
format: "raw-binary",
architecture: "6502",
},
});
});
it("requires explicit architecture and entry even with a misleading suffix", async () => {
const directory = await createTestTempDirectory("rea-raw-target-");
const path = join(directory, "fixture.js");
@@ -4,9 +4,35 @@ import { describe, expect, it } from "vitest";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { pe } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("executable format refusal diagnostics", () => {
it.each([
[0x01a6, "0x01a6"],
[0x0000, "0x0000"],
[0xffff, "0xffff"],
] as const)(
"retains unsupported PE machine %i in the refusal",
async (machine, expectedMachine) => {
const directory = await createTestTempDirectory("rea-target-pe-machine-");
const path = join(directory, "unsupported.exe");
const bytes = pe(0x014c);
bytes.writeUInt16LE(machine, 0x44);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("unsupported PE target was admitted");
const reason = `unsupported PE architecture (COFF machine ${expectedMachine})`;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
message: `Cannot open artifact: ${reason}.`,
details: { reason, constraint: "file_format_rejected" },
});
},
);
it.each(["NE", "LE", "LX"] as const)(
"reports unsupported %s executables without path advice",
async (signature) => {
+35
View File
@@ -1,4 +1,10 @@
import { expect, it } from "vitest";
import { javaClassFile } from "../../fixtures/javaClassFile.js";
import {
CPU,
fatImage,
machoImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { readGoBinaryImage } from "../../../src/go/GoBinaryImage.js";
import {
createGoBinaryFixture,
@@ -221,6 +227,35 @@ it("distinguishes unsupported containers from malformed recognized images", () =
expect(() => readGoBinaryImage(pe.bytes)).toThrowError(/range|truncated/i);
});
it("reports JVM class files as unsupported images instead of fat Mach-O containers", () => {
expect(() => readGoBinaryImage(javaClassFile())).toThrowError(
/Only ELF, PE, and thin Mach-O native images are supported/,
);
expect(() => readGoBinaryImage(javaClassFile(4000))).toThrowError(
/Only ELF, PE, and thin Mach-O native images are supported/,
);
expect(() => readGoBinaryImage(javaClassFile(4000, true))).toThrowError(
/Only ELF, PE, and thin Mach-O native images are supported/,
);
});
it("keeps the thin-slice failure for confirmed universal Mach-O containers", () => {
const slices = [
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) },
];
for (const universal of [
fatImage(slices),
fatImage(slices, true),
fatImage(slices, false, true),
fatImage(slices, true, true),
]) {
expect(() => readGoBinaryImage(Buffer.from(universal))).toThrowError(
/fat Mach-O containers require selecting a thin slice/,
);
}
});
it("rejects ELF header tables overlapping the native header", () => {
const fixture = createGoBinaryFixture({ sectionless: true });
fixture.bytes.writeBigUInt64LE(0n, 32);
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import { createIdaMcpConnection } from "../../src/ida/IdaMcpConnection.js";
describe("IDA startup diagnostics", () => {
it("preserves the failing launcher's stderr instead of reporting only a closed transport", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
'process.stderr.write("FATAL: IDA runtime initialization failed\\n", () => process.exit(2));',
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
await expect(connection.connect()).rejects.toMatchObject({
_tag: "ProviderAdapterError",
capturedOutput: {
stderr: expect.stringContaining("IDA runtime initialization failed"),
truncated: false,
},
});
} finally {
await connection.close();
}
});
it("retains only the bounded stderr tail and reports the original byte count", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
'process.stderr.write("x".repeat(20000) + "FATAL-END", () => process.exit(2));',
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
await expect(connection.connect()).rejects.toMatchObject({
_tag: "ProviderAdapterError",
capturedOutput: {
stderr: "x".repeat(16384 - "FATAL-END".length) + "FATAL-END",
stderr_bytes: 20000 + "FATAL-END".length,
truncated: true,
},
});
} finally {
await connection.close();
}
});
});
it("drops a leading partial UTF-8 character from the bounded stderr tail", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
'process.stderr.write("€".repeat(6000), () => process.exit(2));',
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
await expect(connection.connect()).rejects.toMatchObject({
capturedOutput: {
stderr: "€".repeat(Math.floor(16384 / 3)),
stderr_bytes: 18000,
truncated: true,
},
});
} finally {
await connection.close();
}
});
it("retains an in-budget undecodable leading byte without claiming tail truncation", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
"process.stderr.write(Buffer.from([0x80, 0x61, 0x62]), () => process.exit(2));",
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
const failure = await connection.connect().catch((cause: unknown) => cause);
expect(failure).toMatchObject({
capturedOutput: { stderr: "�ab", stderr_bytes: 3, truncated: false },
});
expect(failure).not.toHaveProperty("diagnostics.upstream_stderr");
} finally {
await connection.close();
}
});
@@ -1,7 +1,13 @@
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import type { OwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
@@ -151,6 +157,121 @@ it("preserves a failed owned cleanup retry when the next caller cancels before a
}
});
it("ends worker stdin and unreferences process handles when cleanup reports inspection uncertainty", async () => {
let stdinEnded = false;
let unreferenced = false;
let permitCleanup = false;
let childStdin: typeof process.stdin | undefined;
const worker = new JavaScriptAnalysisWorker(
{ heapMb: 128, timeoutMs: 30_000 },
async (request) => {
const launched = await spawnOwnedProviderProcess(request);
const originalUnref = launched.process.unref;
launched.process.unref = () => {
unreferenced = true;
originalUnref?.call(launched.process);
};
childStdin = launched.process.stdin as unknown as typeof process.stdin;
launched.process.stdin?.once("finish", () => {
stdinEnded = true;
});
return {
...launched,
cleanup: async () =>
permitCleanup
? launched.cleanup === undefined
? cleanupOwnedProcessGroup(launched.ownership)
: launched.cleanup()
: {
cleaned: false,
reason: "process table could not be inspected: spawn EPERM",
},
};
},
);
try {
const file = source("app.mjs", "export const observed = 7;");
const result = await worker.analyze(file, 100);
if (!result.ok) throw result.error.error;
const closing = worker.close();
await expect(closing).rejects.toBeInstanceOf(ProviderCleanupError);
await expect(closing).rejects.toMatchObject({
cause: {
message: "process table could not be inspected: spawn EPERM",
},
});
expect(childStdin?.writableEnded || stdinEnded).toBe(true);
expect(unreferenced).toBe(true);
const errorListeners = childStdin?.listenerCount("error");
for (let retry = 0; retry < 3; retry++)
await expect(worker.close()).rejects.toBeInstanceOf(ProviderCleanupError);
expect(childStdin?.listenerCount("error")).toBeLessThanOrEqual(
errorListeners ?? 0,
);
permitCleanup = true;
await worker.close();
} finally {
permitCleanup = true;
await worker.close().catch(() => {});
}
});
it("lets a separate host exit while its live worker cleanup remains incomplete", async () => {
const root = await createTestTempDirectory("rea-worker-incomplete-host-");
const ownershipPath = join(root, "ownership.json");
const workerUrl = new URL(
"../../../dist/javascript/analysis/JavaScriptAnalysisWorker.js",
import.meta.url,
).href;
const launcherUrl = new URL(
"../../../dist/process/ProviderProcess.js",
import.meta.url,
).href;
const script = `
import { writeFile } from "node:fs/promises";
import { pathToFileURL } from "node:url";
import { JavaScriptAnalysisWorker } from ${JSON.stringify(workerUrl)};
import { spawnOwnedProviderProcess } from ${JSON.stringify(launcherUrl)};
const worker = new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 10000 }, async request => {
const entry = pathToFileURL(request.arguments.at(-1)).href;
const launched = await spawnOwnedProviderProcess({ ...request, arguments: [
...request.arguments.slice(0, -1), "--input-type=module", "-e",
"const interval = setInterval(() => {}, 1000); setTimeout(() => clearInterval(interval), 60000); await import(" + JSON.stringify(entry) + ");"
] });
// The launcher is deliberately orphaned when this host exits; cleanup still
// requires its run token and executable identity, rather than its old parent.
const { expectedParentPid, ...ownership } = launched.ownership;
await writeFile(${JSON.stringify(ownershipPath)}, JSON.stringify(ownership));
return { ...launched, cleanup: async () => ({ cleaned: false, reason: "fixture inspection unavailable" }) };
});
const analyzed = await worker.analyze(${JSON.stringify(source("app.mjs", "export const value = 1;"))}, 100);
if (!analyzed.ok) throw analyzed.error.error;
try { await worker.close(); throw new Error("cleanup unexpectedly completed"); }
catch (error) {
if (error.cleanupIncomplete !== true) throw error;
process.stdout.write(JSON.stringify({ code: "cleanup_incomplete", reason: error.cause.message }) + "\\n");
}
`;
try {
const result = await promisify(execFile)(
process.execPath,
["--input-type=module", "-e", script],
{ timeout: 10_000 },
);
expect(JSON.parse(result.stdout)).toMatchObject({
code: "cleanup_incomplete",
reason: "fixture inspection unavailable",
});
} finally {
const ownership = JSON.parse(
await readFile(ownershipPath, "utf8"),
) as OwnedProcessGroup;
expect(await cleanupOwnedProcessGroup(ownership)).toMatchObject({
cleaned: true,
});
}
});
// The handshake mirrors the real server: only Node.js reports an enforced V8 heap limit.
const resourceFailureWorker = (heapLimit: string) =>
new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 30_000 }, (request) =>
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import type {
CallToolResult,
ServerContext,
} from "@modelcontextprotocol/server";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import type { Evidence } from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createEvidenceToolHandler } from "../../../src/server/contractToolHandler.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
const UNTRUSTED_TARGET_CONTENT = {
provenance: { untrusted_content: true, source: "analysis_target" },
};
const context = {
mcpReq: { signal: new AbortController().signal },
} as ServerContext;
/**
* Deliver one retained partial-observation failure through the shared Evidence
* handler. The handler is the producer of the result: `EvidenceMcpServer` only
* adds the marker later for results that bypass `ToolResultDelivery`, so a
* missing marker here also undercounts the wire budget by the marker's bytes.
*/
const deliverPartialFailure = async (): Promise<{
readonly result: CallToolResult;
readonly evidence: Evidence;
}> => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Completed capture fixture", version: "1" },
{
operation: "inspect_packet_capture",
parameters: { path: "recording.pcap" },
result: { packets: [{ "frame.number": ["1"] }] },
confidence: "observed",
},
);
const failure = new AnalysisCancelledError("inspect_packet_capture", {
partialObservation: evidence,
});
const writer = { recordEvidence: () => ok("added" as const) };
const server = new EvidenceMcpServer(
{ name: "partial-error-framing-test", version: "1" },
{ capabilities: {} },
writer.recordEvidence,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
const contract = toolContract("inspect_packet_capture");
const handler = createEvidenceToolHandler(
server,
async () => err(failure),
silentLogger,
writer.recordEvidence,
);
return {
result: await handler(contract)({ path: "recording.pcap" }, context),
evidence,
};
};
describe("shared Evidence handler target-content framing", () => {
it("marks a retained partial-observation error as untrusted target content", async () => {
const { result, evidence } = await deliverPartialFailure();
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({
error: {
details: {
partial_observation: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
},
},
});
expect(result._meta).toEqual(UNTRUSTED_TARGET_CONTENT);
});
});
+46
View File
@@ -471,3 +471,49 @@ it("exposes the target-free static JavaScript application workflow", async () =>
const evidenceFor = (value: unknown) => {
return parseEvidence(value);
};
it("reports every unresolved Electron path without starting a provider", async () => {
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
const capture = vi.fn();
const session = createTestBinarySession(() => {
throw new Error("must not start");
});
const server = createServer(
{ kind: "session", session },
{
electronActiveObservation: {
capture,
identity: () => ({ id: "test", name: "test", version: "1" }),
},
},
);
const client = new Client({ name: "electron-path-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const fields = ["executable_path", "application_path", "application_root"];
const result = await client.callTool({
name: "capture_electron_scenario",
arguments: {
...Object.fromEntries(fields.map((field) => [field, join(root, field)])),
actions: [],
},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: fields.map((field) => ({
path: [field],
reason: "invalid_value",
message: expect.stringContaining("ENOENT"),
})),
},
},
});
expect(capture).not.toHaveBeenCalled();
await client.ping();
});
@@ -0,0 +1,249 @@
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js";
import { err, ok } from "../../../src/domain/result.js";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
afterEach(closeEnhancedToolResources);
const PROVIDER = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
type Coverage = boolean | undefined;
interface Behavior {
/** What the provider reports for the references of each match address. */
readonly coverage?: Readonly<Record<string, Coverage>>;
readonly limitations?: readonly string[];
/** Also report the first string match as a procedure match. */
readonly duplicateProcedure?: boolean;
/** Fail the references read of this address. */
readonly failXrefsOf?: string;
readonly calls?: string[];
}
const containing = (address: string) => ({
query_address: address,
found: false,
procedure: null,
reason: "not_in_procedure",
});
/**
* A provider with two string matches (0x10 and 0x11), each referenced from
* one address (0x20 and 0x21).
*/
const provider = (behavior: Behavior = {}): AnalysisOperationPort => ({
execute: async (name, arguments_) => {
const address = String(arguments_.address);
behavior.calls?.push(`${name}:${address}`);
switch (name) {
case "search_strings":
return ok(
createAnalysisExecution(
[
{ address: "0x10", value: "hello" },
{ address: "0x11", value: "hello again" },
],
PROVIDER,
),
);
case "search_procedures":
return ok(
createAnalysisExecution(
behavior.duplicateProcedure === true
? [{ address: "0x10", value: "hello" }]
: [],
PROVIDER,
),
);
case "xrefs": {
if (address === behavior.failXrefsOf)
return err(new AnalysisOutputError("xrefs", "provider failed"));
const reported = behavior.coverage?.[address];
return ok(
createAnalysisExecution(
[address === "0x10" ? "0x20" : "0x21"],
PROVIDER,
{
limitations: behavior.limitations ?? [],
...(reported === undefined
? {}
: { referencesTruncated: reported }),
},
),
);
}
case "resolve_containing_procedure":
return ok(createAnalysisExecution(containing(address), PROVIDER));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
const expectedTrace = (
residual: readonly string[],
extraMatches: readonly object[] = [],
) => ({
query: "hello",
search_mode: "literal",
matches: [
{ type: "string", address: "0x10", value: "hello" },
{ type: "string", address: "0x11", value: "hello again" },
...extraMatches,
],
references: [
{
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
},
{
target_address: "0x11",
source_address: "0x21",
containing_procedure: containing("0x21"),
},
...extraMatches.map(() => ({
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
})),
],
truncated: residual.length > 0,
residual_unknowns: residual,
});
const unknownFor = (address: string) =>
`References to ${address} were truncated by the provider; additional references may exist.`;
const trace = async (analysis: AnalysisOperationPort) => {
const client = await connect(analysis);
const result = await client.callTool({
name: "trace_feature",
arguments: { query: "hello" },
});
expect(result.isError).not.toBe(true);
return result.structuredContent as { normalized_result: unknown };
};
describe("trace_feature reference coverage", () => {
it("marks the trace truncated for the target whose references the provider capped", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(
output.normalized_result,
"the received references are kept and only the capped target is a residual unknown",
).toEqual(expectedTrace([unknownFor("0x10")]));
});
it("does not carry a truncation over to the next target that reports nothing", async () => {
const output = await trace(provider({ coverage: { "0x10": true } }));
expect(output.normalized_result).toEqual(
expectedTrace([unknownFor("0x10")]),
);
});
it("reports a capped target once when it is matched twice", async () => {
const output = await trace(
provider({ coverage: { "0x10": true }, duplicateProcedure: true }),
);
expect(output.normalized_result).toEqual(
expectedTrace(
[unknownFor("0x10")],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("resolves the containing procedure of a repeated reference source once", async () => {
const calls: string[] = [];
const output = await trace(provider({ duplicateProcedure: true, calls }));
expect(
calls.filter((call) => call.startsWith("resolve_containing_procedure:")),
"the source 0x20 is referenced by two matches of the same address and resolved once",
).toEqual([
"resolve_containing_procedure:0x20",
"resolve_containing_procedure:0x21",
]);
expect(
output.normalized_result,
"every reference is still reported with its containing procedure",
).toEqual(
expectedTrace(
[],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("keeps the trace complete when the provider explicitly reports no cap", async () => {
const output = await trace(
provider({ coverage: { "0x10": false, "0x11": false } }),
);
expect(output.normalized_result).toEqual(expectedTrace([]));
});
it("does not change the trace of a provider that reports no coverage", async () => {
const output = await trace(
provider({
limitations: ["Upstream xrefs_to capped results at 1000 references."],
}),
);
expect(
output.normalized_result,
"a limitation text alone never truncates, and an absent field keeps the previous result",
).toEqual(expectedTrace([]));
});
it("never exposes the coverage field in the tool output", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(JSON.stringify(output)).not.toMatch(
/referencesTruncated|references_truncated/,
);
});
it("fails the trace when a references read fails and reads nothing further", async () => {
const calls: string[] = [];
const result = await new EnhancedTools(
provider({ failXrefsOf: "0x10", calls }),
).execute("trace_feature", { query: "hello" });
expect(result.ok).toBe(false);
expect(
calls.filter((call) => call.startsWith("xrefs:")),
"the next target is not read after the failure",
).toEqual(["xrefs:0x10"]);
});
it("stops without reading references when the trace is cancelled", async () => {
const calls: string[] = [];
const controller = new AbortController();
controller.abort();
const result = await new EnhancedTools(provider({ calls })).execute(
"trace_feature",
{ query: "hello" },
controller.signal,
);
expect(result.ok).toBe(false);
expect(calls.filter((call) => call.startsWith("xrefs:"))).toEqual([]);
});
});
+21 -3
View File
@@ -1,4 +1,5 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createHash } from "node:crypto";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js";
@@ -10,6 +11,7 @@ import {
} from "../../../src/domain/analysisErrorCore.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { evmInterfaceSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import { inspectSolidityMetadata } from "../../../src/evm/SolidityMetadata.js";
import { err, ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
@@ -26,8 +28,21 @@ import {
evmInterfaceExecution,
} from "../../fixtures/evm/interface.js";
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const decodedMetadataFixture = () => {
const bytes = Buffer.from("00a1011bffffffffffffffff000b", "hex");
const value = evmInterfaceFixture();
value.bytecode = {
...value.bytecode,
hex: bytes.toString("hex"),
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
metadata: inspectSolidityMetadata(bytes),
};
return value;
};
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const value = decodedMetadataFixture();
const inspect = vi.fn(() =>
Promise.resolve(ok(evmInterfaceExecution(value))),
);
@@ -280,7 +295,8 @@ it("settles the admitted EVM operation after SDK cancellation and accepts a subs
});
it("returns the exact inferred interface summary while preserving complete defaults and retained source", async () => {
const value = evmInterfaceFixture();
const value = decodedMetadataFixture();
expect(value.bytecode.metadata?.status).toBe("decoded");
value.functions = [
{
selector: "0x11223344",
@@ -419,6 +435,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
"preserves historical portable EVM Evidence and rejects incompatible identity: %s",
async (scenario) => {
const value = evmInterfaceFixture();
const { metadata: _metadata, ...historicalBytecode } = value.bytecode;
const source = createEvidence(
scenario === "no-subject"
? undefined
@@ -434,7 +451,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
{
operation: "inspect_evm_interface",
parameters: { path: value.artifact.path, encoding: "hex" },
result: value,
result: { ...value, bytecode: historicalBytecode },
confidence: "inferred",
rawResult: { original: true },
},
@@ -463,6 +480,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
expect(view.parent_evidence_id).toBe(source.evidence_id);
expect(view.summary.functions).toEqual([]);
expect(view.summary.discovery_completeness).toBe("unknown");
expect(view.summary.bytecode.metadata).toBeNull();
expect(view.coverage).toMatchObject({
total: 0,
examined: 0,
@@ -1,6 +1,14 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { compareFunctions } from "../../../src/domain/functionComparison.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
@@ -271,3 +279,130 @@ describe("function comparison MCP integration", () => {
}
});
});
it.each([
{ status: "changed", expected: "fail" },
{ status: "unknown", expected: "unknown" },
{ status: "unchanged", expected: "pass" },
] as const)(
"checks the aggregate status of imported $status function comparisons",
async ({ status, expected }) => {
const left = FUNCTION_COMPARISON_EXAMPLE.left;
const right =
status === "changed"
? FUNCTION_COMPARISON_EXAMPLE.right
: createEvidence(
{
path: "/fixture/function-right",
sha256: "3".repeat(64),
format: "mach-o",
},
status === "unknown"
? { ...left.provider, id: "other-provider" }
: left.provider,
{
operation: left.operation,
parameters: left.parameters,
result: left.normalized_result,
confidence: left.confidence,
authority: left.authority,
relationshipCoverage: { status: "complete" },
},
);
const result = compareFunctions(left, right);
expect(result.status).toBe(status);
const provider = {
id: "rea-function-comparison",
name: "REA function comparison",
version: "1",
};
const observation = {
operation: "compare_functions",
predicateType: "rea.function-comparison",
parameters: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
},
confidence: "derived" as const,
authority: "analyst-inference" as const,
evidenceLinks: [left.evidence_id, right.evidence_id],
};
const consistent = createEvidence(undefined, provider, {
...observation,
result: jsonValueSchema.parse(result),
});
const inconsistent =
status === "unchanged"
? null
: createEvidence(undefined, provider, {
...observation,
result: jsonValueSchema.parse({ ...result, status: "unchanged" }),
});
const directory = await createTestTempDirectory("rea-function-status-");
const path = join(directory, "bundle.json");
await writeFile(
path,
JSON.stringify(
createEvidenceBundle([
left,
right,
consistent,
...(inconsistent === null ? [] : [inconsistent]),
]),
),
);
const session = createTestBinarySession(() => {
throw new Error("Imported comparison must not launch a provider");
});
const harness = await createApplicationMcpHarness({ session });
onTestFinished(harness.close);
const imported = await harness.client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
expect(imported.isError).not.toBe(true);
const verification = (evidence_id: string) =>
harness.client.callTool({
name: "verify_reconstruction",
arguments: {
specification: {
name: "Function aggregate",
claims: [
{
kind: "structural-function",
claim_id: "overall",
title: "Function agrees",
comparison_evidence_id: evidence_id,
dimension: "overall",
},
],
},
},
});
if (inconsistent !== null) {
const rejected = await verification(inconsistent.evidence_id);
expect(parseMcpToolError(rejected).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
reason: "invalid_value",
message: expect.stringContaining(
"Function comparison status contradicts its dimensions or function match",
),
},
],
},
});
expect(harness.session.evidenceById(inconsistent.evidence_id)).toEqual(
inconsistent,
);
}
const verified = await verification(consistent.evidence_id);
expect(verified.isError).not.toBe(true);
expect(
parseEvidence(verified.structuredContent).normalized_result,
).toMatchObject({ status: expected });
await harness.client.ping();
},
);
+3 -1
View File
@@ -46,6 +46,8 @@ it("retains terminal-call qualifications across function views and snapshot repl
limitations: [limitation],
},
],
["procedure_callees", ["0x402000"]],
["procedure_callers", [identity.address]],
["analyze_function", jsonValueSchema.parse(dossier)],
]);
const harness = await connectGhidraMcp(
@@ -81,7 +83,7 @@ it("retains terminal-call qualifications across function views and snapshot repl
});
expect(evidence.limitations, name).toContain(limitation);
expect(evidence.analysis_profile?.parameters).toMatchObject({
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
function_boundary_observations: "ghidra-terminal-call-limitations-v2",
});
const replay = await harness.session.execute(name, evidence.parameters);
if (!replay.ok) throw replay.error;
@@ -1,10 +1,86 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import { ghidraFunctionIdentity } from "../../../src/domain/ghidraValues.fixture.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
it("retains missing PDB coverage in empty PE name-search Evidence and snapshot replay", async () => {
const root = await createTestTempDirectory("rea-pdb-evidence-");
const targetPath = join(root, "fixture.exe");
await writeFile(targetPath, nativeAotPeFixture());
// Synthetic post-analysis facts at the real provider boundary; no engine is simulated as verified.
const pdb = {
file: "C:\\build\\fixture.pdb",
guid: "01234567-89AB-CDEF-0123-456789ABCDEF",
age: "a",
signature: null,
version: "RSDS",
loaded: false,
};
const harness = await connectGhidraMcp(
"ghidra-pdb-coverage",
(operation) =>
Promise.resolve(
ok(
operation === "procedure_pseudo_code"
? {
value: "int FUN_140001000(void) { return 0; }",
limitations: [],
}
: [],
),
),
{
targetPath,
pdb,
},
);
try {
const reply = await harness.mcp.callTool({
name: "search_procedures",
arguments: { pattern: "add_numbers" },
});
expect(reply.isError).not.toBe(true);
const evidence = sessionEvidence(harness.session, reply.structuredContent);
expect(evidence.normalized_result).toEqual([]);
expect(evidence.analysis_profile?.parameters.pdb_observations).toBe(
"program-info-v1",
);
const limitation = evidence.limitations.find((value) =>
value.includes(pdb.file),
);
expect(limitation).toContain(pdb.guid);
expect(limitation).toContain("age (hex) a");
expect(limitation).toContain("not loaded");
const decompiled = await harness.mcp.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "0x140001000", document: "fixture" },
});
expect(decompiled.isError).not.toBe(true);
const functionEvidence = sessionEvidence(
harness.session,
decompiled.structuredContent,
);
expect(functionEvidence.limitations).toContain(limitation);
const replay = await harness.session.execute(
"procedure_pseudo_code",
functionEvidence.parameters,
);
if (!replay.ok) throw replay.error;
expect(replay.value.limitations).toContain(limitation);
expect(replay.value.limitations).toContainEqual(
expect.stringContaining("Loaded from a local REA analysis snapshot"),
);
} finally {
await harness.close();
}
});
it("retains defined-string coverage in empty and matching search Evidence", async () => {
let output = jsonValueSchema.parse([]);
const harness = await connectGhidraMcp("ghidra-string-coverage", () =>
+12 -2
View File
@@ -12,6 +12,7 @@ import type { GhidraOperation } from "../../../src/ghidra/GhidraClient.js";
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
import type { GhidraProviderClientFactory } from "../../../src/ghidra/GhidraProviderClient.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionValues.js";
import type { GhidraSessionInfo } from "../../../src/ghidra/GhidraSessionValues.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
@@ -26,12 +27,19 @@ const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
export const connectGhidraMcp = async (
name: string,
execute?: ReturnType<GhidraProviderClientFactory>["callTool"],
observations: {
readonly targetPath?: string;
readonly pdb?: GhidraSessionInfo["pdb"];
} = {},
) => {
const calls: GhidraOperation[] = [];
const factory: GhidraProviderClientFactory = (options) => ({
start: () =>
Promise.resolve(
ok(sessionInfo(options.profileDigest, options.targetSha256)),
ok({
...sessionInfo(options.profileDigest, options.targetSha256),
...(observations.pdb === undefined ? {} : { pdb: observations.pdb }),
}),
),
callTool: (operation, input, options) => {
calls.push(operation);
@@ -68,7 +76,7 @@ export const connectGhidraMcp = async (
await mcp.connect(clientTransport);
const opened = await mcp.callTool({
name: "open_binary",
arguments: { path: process.execPath },
arguments: { path: observations.targetPath ?? process.execPath },
});
if (opened.isError === true)
throw new Error(
@@ -263,6 +271,8 @@ const resultFor = (
const functionObservationOperations: ReadonlySet<GhidraOperation> = new Set([
"analyze_function",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
+208 -23
View File
@@ -1,4 +1,4 @@
import { writeFile } from "node:fs/promises";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -10,7 +10,8 @@ import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok } from "../../../src/domain/result.js";
import { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { err, ok } from "../../../src/domain/result.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createCacheProvider,
@@ -18,6 +19,7 @@ import {
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { silentLogger } from "../../../src/logger.js";
import { GHIDRA_PROVIDER_IDENTITY } from "../../../src/ghidra/GhidraProviderCapabilities.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
const connect = async (
@@ -50,29 +52,97 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
it("opens a headerless image when architecture and entry are supplied", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
const withGhidraFixtureIdentity = (
provider: AnalysisProvider,
): AnalysisProvider => {
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, { fixture: true });
return {
...provider,
identity: () => identity,
capabilities: () =>
provider.capabilities().map((capability) => ({
...capability,
provider: identity,
})),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
createClient: (target, _profile, context) => {
const client = provider.createClient(target, profile, context);
return {
...client,
execute: async (operation, parameters, options) => {
const result = await client.execute(operation, parameters, options);
return result.ok
? ok({
...result.value,
provider: identity,
analysisProfile: profile,
})
: result;
},
};
},
};
};
it("keeps 6502 out of detected lifecycle output contracts", () => {
const schema = toolContract("open_binary").outputSchema;
const result = {
path: "/fixture/image.bin",
kind: "executable",
sha256: "a".repeat(64),
architecture: "6502",
};
expect(
schema.safeParse({ result: { ...result, format: "pe" } }).success,
).toBe(false);
expect(
schema.safeParse({
result: { ...result, format: "raw-binary", entry_point: "0x8001" },
}).success,
).toBe(true);
const validateAdvertised = new Ajv2020({ strict: false }).compile(
z.toJSONSchema(schema),
);
expect(validateAdvertised({ result: { ...result, format: "pe" } })).toBe(
false,
);
expect(
validateAdvertised({
result: { ...result, format: "raw-binary", entry_point: "0x8001" },
}),
).toBe(true);
});
it.each([
["arm", "0x08000000", "0x8000000", "1eff2fe1"],
["6502", "0x008001", "0x8001", "a92a60"],
])(
"opens a headerless %s image when architecture and entry are supplied",
async (architecture, entryPoint, canonical, bytes) => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from(bytes, "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture,
entry_point: entryPoint,
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
path,
format: "raw-binary",
architecture: "arm",
entry_point: "0x08000000",
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
path,
format: "raw-binary",
kind: "executable",
architecture: "arm",
entry_point: "0x8000000",
});
});
kind: "executable",
architecture,
entry_point: canonical,
});
},
);
it("rejects an unaligned AArch64 entry before selecting or starting a provider", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-alignment-");
@@ -217,3 +287,118 @@ it("reuses a canonical raw entry and replaces the session when the entry changes
expect(created).toEqual(["0x8000000", "0x9000000"]);
expect(closed).toEqual(["0x8000000"]);
});
it.skipIf(process.platform !== "win32")(
"does not replay a saved read after switching to a Windows junction",
async () => {
const root = await createTestTempDirectory("rea-raw-mcp-linked-reopen-");
const actual = join(root, "actual");
const linked = join(root, "linked");
await mkdir(actual);
const path = join(actual, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
await symlink(actual, linked, "junction");
const created: string[] = [];
const executed: string[] = [];
const fixture = createCacheProvider([]);
const { client } = await connect(
withGhidraFixtureIdentity({
...fixture,
createClient: (target) => {
created.push(target.sourcePath ?? target.path);
return {
execute: (operation) => {
if (operation === "address_name")
executed.push(target.sourcePath ?? target.path);
if (
operation === "address_name" &&
target.sourcePath === join(linked, "image.bin")
)
return Promise.resolve(
err(new ProviderAdapterError("fixture", operation)),
);
return Promise.resolve(
observed(operation === "address_name" ? "entry" : null),
);
},
close: () => Promise.resolve(ok(null)),
};
},
}),
);
const linkedPath = join(linked, "image.bin");
for (const requested of [path, linkedPath]) {
const opened = await client.callTool({
name: "open_binary",
arguments: {
path: requested,
format: "raw-binary",
architecture: "6502",
entry_point: "0x8001",
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const address = await client.callTool({
name: "address_name",
arguments: { address: "0x8001", document: "image.bin" },
});
expect(address.isError === true, JSON.stringify(address)).toBe(
requested === linkedPath,
);
}
expect(created).toEqual([path, linkedPath]);
expect(executed).toEqual([path, linkedPath]);
},
);
it.skipIf(process.platform !== "win32")(
"reuses saved reads after a fixture admits a noncanonical Windows path",
async () => {
const root = await createTestTempDirectory("rea-raw-mcp-admitted-path-");
const actual = join(root, "actual");
const linked = join(root, "linked");
await mkdir(actual);
const path = join(actual, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
await symlink(actual, linked, "junction");
const calls: string[] = [];
const fixture = createCacheProvider([]);
// This fixture accepts the alias to isolate cache behavior after admission.
// The real Ghidra verifier checks that a junction itself is rejected.
const { client, session } = await connect(
withGhidraFixtureIdentity({
...fixture,
createClient: () => ({
execute: (operation) => {
if (operation === "address_name") calls.push(operation);
return Promise.resolve(
observed(operation === "health" ? null : "entry"),
);
},
close: () => Promise.resolve(ok(null)),
}),
}),
);
const linkedPath = join(linked, "image.bin");
const opened = await client.callTool({
name: "open_binary",
arguments: {
path: linkedPath,
format: "raw-binary",
architecture: "6502",
entry_point: "0x8001",
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
expect(session.activeTarget()?.sourcePath).toBe(linkedPath);
expect(session.activeTarget()?.path).toBe(path);
for (const _ of [0, 1]) {
const address = await client.callTool({
name: "address_name",
arguments: { address: "0x8001", document: "image.bin" },
});
expect(address.isError, JSON.stringify(address)).not.toBe(true);
}
expect(calls).toEqual(["address_name"]);
},
);
+16 -3
View File
@@ -342,17 +342,30 @@ it("exposes overload candidates and executes only an explicitly selected ambiguo
expect(result.method).toMatchObject({
overload_index: 1,
reported_signature: "choose(int): void",
dex_descriptor: null,
dex_descriptor: "(I)V",
});
expect(result.source.text).toContain("overload 1");
const references = await service.execute("trace_android_references", input);
expect(references).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
reason: expect.stringContaining("unique method name"),
_tag: "AnalysisInputError",
issues: [expect.objectContaining({ path: ["overload_index"] })],
},
});
const selectedReferences = await service.execute("trace_android_references", {
...input,
overload_index: 1,
});
if (!selectedReferences.ok) throw selectedReferences.error;
expect(
androidResultSchemas.trace_android_references.parse(
selectedReferences.value.normalized_result,
),
).toMatchObject({
overload_index: 1,
reported_signature: "choose(int): void",
});
await provider.close();
await verifyCleanup(launches);
});
+5 -3
View File
@@ -257,9 +257,11 @@ it.skipIf(process.platform === "win32").each(["cancelled", "timeout"] as const)(
failures: [expect.objectContaining({ reason: "run-token-mismatch" })],
});
expect(failure.cleanupResult).toEqual(cleanup);
expect(failure.resources).toEqual(
expect.arrayContaining([request.runId]),
);
expect(failure.resources).toEqual([
request.runId,
`pid:${launched.ownership.leaderPid}`,
`process-group:${launched.ownership.processGroupId}`,
]);
// An unresolved member does not grant authority to signal the shared group.
const acquiredPid = launched.ownership.leaderPid;
expect(() => process.kill(acquiredPid, 0)).not.toThrow();
@@ -196,9 +196,9 @@ itWithCaptureCapability(
result.value.frames.map(({ at_ms }) => at_ms),
"capture-relative frame times stay ordered and nonnegative",
).toEqual(
[...result.value.frames.map(({ at_ms }) => at_ms)].sort(
(left, right) => left - right,
),
result.value.frames
.map(({ at_ms }) => at_ms)
.sort((left, right) => left - right),
);
expect(result.value.frames.every(({ at_ms }) => at_ms >= 0)).toBe(true);
expect(result.value.exit.reason).toBe("exited");
@@ -28,6 +28,35 @@ const identitySchema = z.object({
const itWithLinuxCaptureCapability =
process.platform === "linux" ? itWithCaptureCapability : it.skip;
itWithCaptureCapability(
"captures a POSIX PATH executable with a literal backslash in its basename",
async () => {
const root = await createTestTempDirectory("rea-process-backslash-name-");
const bin = join(root, "bin");
await mkdir(bin);
const command = "selected\\node";
const selected = join(bin, command);
await symlink(process.execPath, selected);
const scenario = parseProcessScenario({
executable: command,
working_directory: root,
environment: { PATH: bin },
arguments: ["-e", 'process.stdout.write("selected executable")'],
settle_ms: 100,
});
const result = await captureProcessScenario(scenario);
if (!result.ok) throw result.error;
expect(result.value.frames.map(({ data }) => data).join("")).toBe(
"selected executable",
);
expect(result.value.exit).toMatchObject({ code: 0, reason: "exited" });
expect(result.value.cleanup).toMatchObject({
owned_process_group: "verified",
temporary_root: "removed",
});
},
);
itWithCaptureCapability(
"preserves numeric reports and original normalized PTY text in Evidence",
async () => {
@@ -1,4 +1,11 @@
import { access, chmod, readFile, stat } from "node:fs/promises";
import {
access,
chmod,
mkdir,
readFile,
stat,
writeFile,
} from "node:fs/promises";
import { join, posix, win32 } from "node:path";
import { fileURLToPath } from "node:url";
@@ -479,6 +486,66 @@ describe("Ghidra Windows launcher", () => {
}),
).toThrow(/metacharacters/u);
});
});
describe("Ghidra Windows launcher runtime", () => {
it.skipIf(process.platform !== "win32").each([
{
properties:
"application.version=12.1.4\napplication.release.name=PUBLIC\n",
release: "ghidra_12.1.4_PUBLIC",
},
{ properties: undefined, release: "renamed-install" },
{ properties: "application.version=12.1.4\n", release: "renamed-install" },
])(
"prepares the release directory through the Windows runtime ($release)",
async ({ properties, release }) => {
const parent = await createTestTempDirectory("rea-launch-config-");
const installRoot = join(parent, "renamed-install");
if (properties !== undefined) {
await mkdir(join(installRoot, "Ghidra"), { recursive: true });
await writeFile(
join(installRoot, "Ghidra", "application.properties"),
properties,
);
}
const runtime = await createGhidraTestRuntime(parent);
runtimes.push(runtime);
const spawnProcess = vi.fn(async () => {
throw new Error("fixture stops before process creation");
});
const launcher = new GhidraHeadlessLauncher({
environment: process.env,
platform: "win32",
analyzeHeadlessPath: join(
installRoot,
"support",
"analyzeHeadless.bat",
),
javaHome: "C:\\Java\\jdk-21",
bridgeScriptPath: join(parent, "ReaGhidraBridge.java"),
spawnProcess,
});
const launched = await launcher.launch({
runtimeRoot: runtime.path,
transport: "unix-socket",
endpointPath: join(runtime.path, "bridge.sock"),
token: "fixture-token",
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
targetPath: join(parent, "fixture.exe"),
targetSha256: "b".repeat(64),
providerVersion: "12.1.4",
profileDigest: "a".repeat(64),
});
expect(launched.ok).toBe(false);
expect(spawnProcess).toHaveBeenCalledOnce();
expect(
(
await stat(join(runtime.path, "config", "ghidra", release))
).isDirectory(),
).toBe(true);
},
);
it.skipIf(process.platform !== "win32")(
"keeps authority in a private descriptor and isolates Ghidra state through the batch launcher",
@@ -208,6 +208,22 @@ it("preserves missing callgraph coverage through direct, graph, and trace workfl
]),
);
const dossier = await client.execute("analyze_function", {
procedure: "main",
});
if (!dossier.ok) throw dossier.error;
expect(dossier.value.result).toMatchObject({
callers: [],
callees: [],
facet_availability: {
callers: { available: false },
callees: {
available: false,
reason: expect.stringContaining("callgraph was unavailable"),
},
},
});
const application = new EnhancedTools(client);
const graph = await application.execute("get_call_graph", {
address: "main",
@@ -0,0 +1,144 @@
import { rm } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import { inspectAddressContext } from "../../../../src/application/AnalysisContextQueries.js";
import { EnhancedTools } from "../../../../src/application/EnhancedTools.js";
import { IdaSessionClient } from "../../../../src/ida/IdaSessionClient.js";
import { createIdaTarget, RecordingIdaMcp } from "../../../fixtures/idaMcp.js";
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0))
await rm(root, { recursive: true, force: true });
});
const session = async (cappedReferences = false) => {
const { root, target } = await createIdaTarget("arm64");
roots.push(root);
const producer = new RecordingIdaMcp(target, "headless");
if (cappedReferences) {
const inner = producer.overrideCall;
producer.overrideCall = (name, args) =>
name === "xrefs_to"
? [
{
xrefs: [
{
addr: "0x1004",
type: "code",
fn: { addr: "0x1000", name: "main", size: "0x20" },
},
],
more: true,
},
]
: inner?.(name, args);
}
const client = new IdaSessionClient(
{
command: "fixture",
args: [],
env: {},
mode: "headless",
timeoutMs: 1000,
workspaceRoot: root,
},
target,
producer,
);
return { client, target };
};
const MAIN = {
found: true,
procedure: { address: "0x1000", name: "main" },
};
describe("trace_feature on headless IDA", () => {
it("attributes a reference to its containing procedure", async () => {
const { client } = await session();
try {
const result = await new EnhancedTools(client).execute("trace_feature", {
query: "a.b",
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
matches: [{ type: "string", address: "0x3000" }],
references: [
{
target_address: "0x3000",
source_address: "0x1004",
containing_procedure: MAIN,
},
],
truncated: false,
residual_unknowns: [],
});
} finally {
expect((await client.close()).ok).toBe(true);
}
});
it("keeps an upstream reference cap visible once containment makes the trace run", async () => {
const { client } = await session(true);
try {
const result = await new EnhancedTools(client).execute("trace_feature", {
query: "a.b",
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
references: [{ source_address: "0x1004", containing_procedure: MAIN }],
truncated: true,
residual_unknowns: [
"References to 0x3000 were truncated by the provider; additional references may exist.",
],
});
} finally {
expect((await client.close()).ok).toBe(true);
}
});
});
describe("inspect_address_context on headless IDA", () => {
it("resolves the admitted program as the document and reports the containing procedure", async () => {
const { client, target } = await session();
try {
const result = await inspectAddressContext(client, {
address: "0x1004",
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
address: "0x1004",
document: target.path,
procedure: { state: "available", value: MAIN },
name: { state: "unavailable" },
comment: { state: "unavailable" },
inline_comment: { state: "unavailable" },
bookmarks: { state: "unavailable" },
});
} finally {
expect((await client.close()).ok).toBe(true);
}
});
it("answers the same way for an explicit admitted document", async () => {
const { client, target } = await session();
try {
const implicit = await inspectAddressContext(client, {
address: "0x1004",
});
const explicit = await inspectAddressContext(client, {
address: "0x1004",
document: target.path,
});
if (!implicit.ok) throw implicit.error;
if (!explicit.ok) throw explicit.error;
expect(explicit.value).toEqual(implicit.value);
} finally {
expect((await client.close()).ok).toBe(true);
}
});
});
@@ -0,0 +1,114 @@
import { createHash } from "node:crypto";
import { mkdir, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { elf } from "../../../../src/domain/binaryTarget.fixture.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
import { createIdaMcpConnection } from "../../../../src/ida/IdaMcpConnection.js";
import { IdaSessionClient } from "../../../../src/ida/IdaSessionClient.js";
/**
* A headless IDA supervisor over real stdio that answers the session
* lifecycle, but rejects the first inventory after a close so cleanup fails
* once and must be retried through the retained connection.
*/
const FLAKY_INVENTORY_SUPERVISOR = `import { createInterface } from "node:readline";
const tools = ["idb_open", "idb_list", "idb_close", "server_health", "list_funcs",
"lookup_funcs", "find_regex", "decompile", "disasm", "callees", "xrefs_to"];
let session;
let inputPath;
let closed = false;
let inventoryFailed = false;
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
const result = (value) => ({
content: [{ type: "text", text: JSON.stringify(value) }],
structuredContent: value,
});
const call = ({ name, arguments: args }) => {
if (name === "idb_open") {
session = args.preferred_session_id;
inputPath = args.input_path;
return result({ success: true, session: { session_id: session, input_path: inputPath } });
}
if (name === "server_health")
return result({ status: "ok", input_path: inputPath, idb_path: inputPath + ".i64",
module: "target.elf", imagebase: "0x1000", auto_analysis_ready: true });
if (name === "idb_close") {
closed = true;
return result({ success: true, session_id: session, saved: null, owned: true, backend: "worker" });
}
if (name === "idb_list") {
if (closed && !inventoryFailed) {
inventoryFailed = true;
return { isError: true, content: [{ type: "text", text: "inventory unavailable" }] };
}
return result({ sessions: closed ? [] : [{ session_id: session, input_path: inputPath,
owned: true, backend: "worker", is_active: true }] });
}
return { isError: true, content: [{ type: "text", text: "unsupported " + name }] };
};
for await (const line of createInterface({ input: process.stdin })) {
const request = JSON.parse(line);
if (request.method === "initialize")
send({ id: request.id, result: {
protocolVersion: request.params.protocolVersion,
capabilities: { tools: {} },
serverInfo: { name: "flaky-inventory-ida-fixture", version: "1" },
} });
else if (request.method === "tools/list")
send({ id: request.id, result: {
tools: tools.map((name) => ({ name, inputSchema: { type: "object" } })),
} });
else if (request.method === "tools/call")
send({ id: request.id, result: call(request.params) });
}
`;
describe("retained headless IDA connection in a long-lived host", () => {
it("retries cleanup through the detached stdio connection", async () => {
const root = await createTestTempDirectory("rea-ida-retry-");
const supervisor = join(root, "supervisor.mjs");
await writeFile(supervisor, FLAKY_INVENTORY_SUPERVISOR);
const workspaceRoot = join(root, "workspaces");
await mkdir(workspaceRoot);
const bytes = elf(2, 1, 62);
const targetPath = join(root, "target.elf");
await writeFile(targetPath, bytes);
const target: BinaryTarget = {
path: targetPath,
sha256: createHash("sha256").update(bytes).digest("hex"),
kind: "executable",
format: "elf",
architecture: "x86_64",
availableArchitectures: ["x86_64"],
};
const config = {
command: process.execPath,
args: [supervisor],
env: {},
mode: "headless" as const,
timeoutMs: 5000,
workspaceRoot,
};
const connection = createIdaMcpConnection(config, process.env);
// Close the supervisor even when an assertion fails before cleanup does.
onTestFinished(() => connection.close().catch(() => undefined));
const client = new IdaSessionClient(config, target, connection);
expect((await client.execute("health", {})).ok).toBe(true);
const failed = await client.close();
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error.cleanupIncomplete).toBe(true);
expect(await readdir(workspaceRoot)).toHaveLength(1);
// The connection was detached when cleanup failed; it must still serve
// the retry that confirms release and removes the private workspace.
expect((await client.close()).ok).toBe(true);
expect(await readdir(workspaceRoot)).toEqual([]);
});
});
@@ -0,0 +1,212 @@
import { describe, expect, it } from "vitest";
import {
assertFeatureTrace,
findMappedNonFunction,
} from "../../../../scripts/lib/ida-feature-trace.mjs";
const procedure = { address: "0x1000", name: "main" };
const containing = (found: boolean) =>
found
? {
query_address: "0x1004",
found: true,
procedure: { address: "0x1000", name: "main" },
}
: {
query_address: "0x3010",
found: false,
procedure: null,
reason: "not_in_procedure",
};
const trace = (
matches: readonly { type: string; address: string }[],
references: readonly {
target_address: string;
containing_procedure: unknown;
}[],
) => ({
query: "main",
search_mode: "literal",
matches,
references,
truncated: false,
residual_unknowns: [],
});
const SELECTED = { type: "procedure", address: "0x1000" };
const SUBSTRING = { type: "procedure", address: "0x2000" };
const STRING = { type: "string", address: "0x3000" };
describe("the real IDA lane's feature trace assertions", () => {
it("accepts references to every matched address, whoever contains the source", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED, SUBSTRING, STRING],
[
{
target_address: "0x1000",
containing_procedure: containing(true),
},
// A substring match such as main_helper, referenced from code.
{
target_address: "0x2000",
containing_procedure: containing(true),
},
// A string containing the query, referenced from data outside functions.
{
target_address: "0x3000",
containing_procedure: containing(false),
},
],
),
procedure,
),
).not.toThrow();
});
it("accepts a reference to the selected procedure from data outside functions", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED],
[
{
target_address: "0x1000",
containing_procedure: containing(false),
},
],
),
procedure,
),
).not.toThrow();
});
it("rejects a reference whose target is not one of the matches", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED],
[
{
target_address: "0x9999",
containing_procedure: containing(true),
},
],
),
procedure,
),
).toThrow();
});
it("rejects a trace without the selected procedure's match", () => {
expect(() => assertFeatureTrace(trace([STRING], []), procedure)).toThrow();
});
it("rejects a containment answer that is neither found nor a known reason", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED],
[
{
target_address: "0x1000",
containing_procedure: {
query_address: "0x1004",
found: false,
procedure: null,
reason: "unknown",
},
},
],
),
procedure,
),
).toThrow();
});
it("rejects a trace that does not say whether it was truncated", () => {
expect(() =>
assertFeatureTrace(
{ ...trace([SELECTED], []), truncated: undefined },
procedure,
),
).toThrow();
});
});
describe("the real IDA lane's mapped non-function probe", () => {
const inFunction = {
query_address: "0x1100",
found: true,
procedure: { address: "0x1000", name: "main" },
};
const data = {
query_address: "0x3000",
found: false,
procedure: null,
reason: "not_in_procedure",
};
const resolver =
(answers: Readonly<Record<string, unknown>>, asked: string[] = []) =>
async (address: string) => {
asked.push(address);
return answers[address];
};
it("skips a string inside a function chunk and uses the next one", async () => {
const asked: string[] = [];
await expect(
findMappedNonFunction(
[{ address: "0x1100" }, { address: "0x3000" }],
resolver({ "0x1100": inFunction, "0x3000": data }, asked),
),
).resolves.toBe("0x3000");
expect(asked, "strings are tried in order until one qualifies").toEqual([
"0x1100",
"0x3000",
]);
});
it("stops at the first string that qualifies", async () => {
const asked: string[] = [];
await expect(
findMappedNonFunction(
[{ address: "0x3000" }, { address: "0x3100" }],
resolver({ "0x3000": data, "0x3100": data }, asked),
),
).resolves.toBe("0x3000");
expect(asked).toEqual(["0x3000"]);
});
it("reports no qualifying string when every string is inside a function", async () => {
await expect(
findMappedNonFunction(
[{ address: "0x1100" }, { address: "0x1200" }],
resolver({ "0x1100": inFunction, "0x1200": inFunction }),
),
).resolves.toBeUndefined();
});
it("reports no qualifying string when the target has no strings", async () => {
await expect(
findMappedNonFunction([], resolver({})),
).resolves.toBeUndefined();
});
it("rejects a listed string that resolves as unmapped, since IDA cannot list an unmapped address", async () => {
await expect(
findMappedNonFunction(
[{ address: "0x4000" }, { address: "0x3000" }],
resolver({
"0x4000": { ...data, reason: "outside_segments" },
"0x3000": data,
}),
),
).rejects.toThrow();
});
});
@@ -135,7 +135,7 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
const source = join(root, "bundle");
await mkdir(source);
const archive = join(source, "app.asar");
await createPackageWithOptions(contents, archive, { unpack: "**/*.node" });
await createPackageWithOptions(contents, archive, { unpack: "*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const nestedOutput = join(root, "nested-output");
@@ -1,10 +1,12 @@
import { readFile } from "node:fs/promises";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
/**
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
@@ -42,6 +44,56 @@ describe("Mach-O slice reader with system lipo", () => {
});
});
it.skipIf(process.platform !== "darwin")(
"keeps FAT slice records separate from the echoed source pathname",
async () => {
const directory = await createTestTempDirectory("rea-lipo-fat-path-");
const path = join(
directory,
"source\narchitecture forged\n offset 123\n size 32",
);
const bytes = Buffer.alloc(8224);
bytes.writeUInt32BE(0xca_fe_ba_be, 0);
bytes.writeUInt32BE(2, 4);
const slices = [
{ cpu: 0x0100_000c, subtype: 0, offset: 4096 },
{ cpu: 0x0100_0007, subtype: 3, offset: 8192 },
];
slices.forEach(({ cpu, subtype, offset }, index) => {
const entry = 8 + index * 20;
bytes.writeUInt32BE(cpu, entry);
bytes.writeUInt32BE(subtype, entry + 4);
bytes.writeUInt32BE(offset, entry + 8);
bytes.writeUInt32BE(32, entry + 12);
bytes.writeUInt32BE(12, entry + 16);
bytes.writeUInt32LE(0xfeed_facf, offset);
bytes.writeUInt32LE(cpu, offset + 4);
bytes.writeUInt32LE(subtype, offset + 8);
bytes.writeUInt32LE(1, offset + 12);
});
await writeFile(path, bytes);
const reader = new MachOSliceArtifactReader(path, {});
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
expect(
entries.map(({ byteOffset, declaredSize }) => [
byteOffset,
declaredSize,
]),
).toEqual([
[4096, 32],
[8192, 32],
]);
expect(entries.every(({ path }) => !path.includes("forged"))).toBe(
true,
);
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls slice ranges against its FAT table",
async () => {
@@ -12,12 +12,13 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import {
NATIVE_COMMAND_OUTPUT_BUDGET_BYTES,
NATIVE_FAILURE_DIAGNOSTIC_BYTES,
NativeCommandFailure,
XcrunCommandRunner,
type NativeCommandRunner,
} from "../../../../src/native/CommandRunner.js";
import { err, ok } from "../../../../src/domain/result.js";
import { parseLipoArchitectures } from "../../../../src/native/parsers/lipo.js";
import { parseLipoOutput } from "../../../../src/native/parsers/lipo.js";
import { parseCodeSignature } from "../../../../src/native/parsers/codesign.js";
import { prepareProcessOwnershipInspection } from "../../../../src/process/ProcessOwnershipObservation.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
@@ -381,6 +382,36 @@ describe("native command failure capture and limits", () => {
});
});
it("bounds both failure streams at a UTF-8 boundary while keeping their totals", async () => {
const runner = new XcrunCommandRunner({}, () =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
);
// "é" is two bytes and straddles the excerpt boundary, so it is dropped whole.
const stdout = `${"x".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES - 1)}é${"y".repeat(1024)}`;
const stderr = "z".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES + 1024);
// Build the output in the child: one Linux argument is limited to 128 KiB.
const result = await runner.run(
"file",
[
"-e",
`const stdout = "x".repeat(${String(NATIVE_FAILURE_DIAGNOSTIC_BYTES - 1)}) + "\u00e9" + "y".repeat(1024); const stderr = "z".repeat(${String(NATIVE_FAILURE_DIAGNOSTIC_BYTES + 1024)}); process.stdout.write(stdout, () => process.stderr.write(stderr, () => process.exit(3)));`,
],
{},
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.reason).toBe("nonzero-exit");
expect(result.error.capture).toMatchObject({
stdout: "x".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES - 1),
stderr: "z".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES),
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: Buffer.byteLength(stderr),
exitCode: 3,
truncated: true,
});
});
it("rejects output beyond the complete native-command budget", async () => {
const runner = new XcrunCommandRunner({}, () =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
@@ -404,6 +435,13 @@ describe("native command failure capture and limits", () => {
(result.error.capture?.stdoutBytes ?? 0) +
(result.error.capture?.stderrBytes ?? 0),
).toBeLessThanOrEqual(NATIVE_COMMAND_OUTPUT_BUDGET_BYTES);
// The failure carries an excerpt, not the whole retained output budget.
expect(result.error.capture?.stdout.length).toBe(
NATIVE_FAILURE_DIAGNOSTIC_BYTES,
);
expect(result.error.capture?.stdoutBytes).toBeGreaterThan(
NATIVE_FAILURE_DIAGNOSTIC_BYTES,
);
});
});
@@ -834,6 +872,43 @@ describe("native signature entitlements", () => {
});
});
/** Fail every codesign call nonzero after writing more than one excerpt. */
class VerboseCodeSignFailureRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || tool !== "codesign") return result;
const stderr = "e".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES * 2);
return ok({
...result.value,
stderr,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
describe("native signature failure diagnostics", () => {
it("bounds accepted nonzero codesign output once it becomes a failure", async () => {
directory = await createTestTempDirectory("rea-signature-failure-");
const executable = join(directory, "fixture");
await writeFile(executable, "fixture");
const client = new NativeMacOSProvider(
{},
new VerboseCodeSignFailureRunner(),
"darwin",
).createClient(await nativeMachoTargetForFile(executable));
const signature = await client.execute("inspect_signature", {});
if (signature.ok) throw new Error("A failed codesign run must fail");
expect(signature.error.capturedOutput).toMatchObject({
stderr: "e".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES),
stderr_bytes: NATIVE_FAILURE_DIAGNOSTIC_BYTES * 2,
truncated: true,
});
});
});
describe("native dispatch metadata error results", () => {
it("preserves tagged cancellation and integrity failures", async () => {
directory = await createTestTempDirectory("rea-dispatch-errors-");
@@ -960,15 +1035,17 @@ describe("native macOS provider failures and parsing", () => {
});
it("parses thin and universal lipo fixtures", async () => {
expect(
parseLipoArchitectures(await fixture("lipo-thin.txt")),
).toMatchObject([{ name: "arm64" }]);
expect(parseLipoArchitectures(await fixture("lipo-fat.txt"))).toMatchObject(
[
expect(parseLipoOutput(await fixture("lipo-thin.txt"))).toMatchObject({
format: "thin",
architectures: [{ name: "arm64" }],
});
expect(parseLipoOutput(await fixture("lipo-fat.txt"))).toMatchObject({
format: "fat",
architectures: [
{ name: "x86_64", file_offset: 16384, size: 4096 },
{ name: "arm64", file_offset: 32768, size: 8192 },
],
);
});
});
it("rejects trailing text in lipo numeric fields instead of truncating", () => {
@@ -980,7 +1057,7 @@ describe("native macOS provider failures and parsing", () => {
" size 0x10",
" align 2^14 (16384)",
].join("\n");
expect(parseLipoArchitectures(output)).toMatchObject([
expect(parseLipoOutput(output).architectures).toMatchObject([
{ name: "arm64", file_offset: null, size: null, alignment: 16384 },
]);
});
@@ -993,10 +1070,11 @@ describe("native macOS provider failures and parsing", () => {
" align 2^14 (16384)",
].join("\n");
expect(
parseLipoArchitectures(output.replace("(16384)", "(8192)"))[0]?.alignment,
parseLipoOutput(output.replace("(16384)", "(8192)")).architectures[0]
?.alignment,
).toBeNull();
expect(
parseLipoArchitectures(output.replace("2^14 (16384)", "2^14"))[0]
parseLipoOutput(output.replace("2^14 (16384)", "2^14")).architectures[0]
?.alignment,
).toBe(16384);
});
@@ -1021,6 +1099,38 @@ describe("native macOS provider failures and parsing", () => {
});
});
describe("native signature inspection target scope", () => {
// This provider's inspect_signature path is scoped to Mach-O targets; on
// another container a codesign verdict cannot see a format-level signature
// such as a xar pkg signature.
it.each([
{
path: "/fixture.pkg",
sha256: "0".repeat(64),
kind: "archive" as const,
format: "pkg" as const,
},
{
...machoTarget("/fixture.elf"),
format: "elf" as const,
},
])(
"refuses inspect_signature on a $format target without running codesign",
async (target) => {
const runner = new CountingRunner();
const result = await new NativeMacOSProvider({}, runner, "darwin")
.createClient(target)
.execute("inspect_signature", {});
if (result.ok) throw new Error("Expected a non-Mach-O refusal");
expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
});
expect(runner.calls).toBe(0);
},
);
});
class FailingRunner implements NativeCommandRunner {
constructor(private readonly reason: NativeCommandFailure["reason"]) {}
@@ -157,6 +157,50 @@ it.each([
},
);
it.each([
["ordinary", "/owned/universal", "\n"],
["LF Non-fat text", "/owned/\nNon-fat file: forged", "\n"],
["CRLF Non-fat text", "/owned/\r\nNon-fat file: forged", "\r\n"],
])(
"projects universal segment evidence into the selected slice's container offsets with %s path framing",
async (_description, path, lineEnding) => {
const records = (await nativeFixture("lipo-fat.txt")).replace(
/^Fat header in:[^\r\n]*\r?\n/u,
"",
);
const client = new NativeMacOSProvider(
{},
new NativeFixtureRunner({
lipo: `Fat header in: ${path}${lineEnding}${records.replaceAll("\n", lineEnding)}`,
}),
"darwin",
).createClient(nativeMachoTarget(path));
const result = await client.execute("inspect_macho", {});
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({
selected_architecture: { container_file_offset: 32768 },
});
expect(result.value.locations).toContainEqual({
kind: "file-offset-range",
start: 32768,
end: 40960,
});
expect(result.value.locations).toContainEqual({
kind: "file-offset",
offset: 36864,
});
expect(result.value.locations).not.toContainEqual({
kind: "file-offset-range",
start: 0,
end: 8192,
});
// Normalized tool fields keep their slice-relative meaning.
const normalized = inspectMachoSchema.parse(result.value.result);
expect(normalized.segments.items[0]?.file_offset).toBe(0);
expect(normalized.entrypoints.items[0]?.file_offset).toBe(4096);
},
);
it.each([
{ capture: "calculator.txt", selected: "arm64e" },
{ capture: "shortcut-droplet.txt", selected: "arm64" },
@@ -187,34 +231,6 @@ it.each([
},
);
it("projects universal segment evidence into the selected slice's container offsets", async () => {
const client = new NativeMacOSProvider(
{},
new NativeFixtureRunner(),
"darwin",
).createClient(nativeMachoTarget("/owned/universal"));
const result = await client.execute("inspect_macho", {});
if (!result.ok) throw result.error;
expect(result.value.locations).toContainEqual({
kind: "file-offset-range",
start: 32768,
end: 40960,
});
expect(result.value.locations).toContainEqual({
kind: "file-offset",
offset: 36864,
});
expect(result.value.locations).not.toContainEqual({
kind: "file-offset-range",
start: 0,
end: 8192,
});
// Normalized tool fields keep their slice-relative meaning.
const normalized = inspectMachoSchema.parse(result.value.result);
expect(normalized.segments.items[0]?.file_offset).toBe(0);
expect(normalized.entrypoints.items[0]?.file_offset).toBe(4096);
});
it.each([
{
description: "thin",
@@ -2,7 +2,7 @@ import { expect, it } from "vitest";
import { parseOtoolLoadCommands } from "../../../../src/native/parsers/otool.js";
import { parsePlistJson } from "../../../../src/native/parsers/plist.js";
import { parseLipoArchitectures } from "../../../../src/native/parsers/lipo.js";
import { parseLipoOutput } from "../../../../src/native/parsers/lipo.js";
import { nativeFixture } from "../../../fixtures/nativeCommands.js";
const toCrlf = (value: string): string => value.replaceAll("\n", "\r\n");
@@ -15,7 +15,10 @@ it.each([
"retains the reported thin architecture when lipo echoes filename %j",
(filename) => {
const output = `input file /owned/${filename} is not a fat file\nNon-fat file: /owned/${filename} is architecture: arm64\n`;
expect(parseLipoArchitectures(output)).toMatchObject([{ name: "arm64" }]);
expect(parseLipoOutput(output)).toMatchObject({
format: "thin",
architectures: [{ name: "arm64" }],
});
},
);
@@ -38,10 +41,13 @@ it("does not mistake fat slice output for a thin Non-fat file record", () => {
" align 2^12 (4096)",
"",
].join("\n");
expect(parseLipoArchitectures(output)).toMatchObject([
{ name: "arm64", file_offset: 16384 },
{ name: "x86_64", file_offset: 16793600 },
]);
expect(parseLipoOutput(output)).toMatchObject({
format: "fat",
architectures: [
{ name: "arm64", file_offset: 16384 },
{ name: "x86_64", file_offset: 16793600 },
],
});
});
it("keeps section blocks separate under CRLF captures", async () => {
@@ -1,3 +1,7 @@
import {
descriptorFailurePath,
expectRetainedDescriptor,
} from "../../fixtures/descriptorCloseFailure.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { writeFile } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
@@ -15,27 +19,22 @@ const cleanup = vi.hoisted(() => ({
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
return {
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (args[0] === cleanup.path) {
cleanup.handles.push(handle);
const close = handle.close.bind(handle);
handle.close = async () => {
if (cleanup.denied && handle.fd >= 0)
throw new Error("Descriptor close deliberately denied");
await close();
};
}
return handle;
},
};
const { withDescriptorCloseFailure } =
await import("../../fixtures/descriptorCloseFailure.js");
return withDescriptorCloseFailure(filesystem, cleanup);
});
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-signal-descriptor-");
@@ -67,14 +66,16 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
cleanup.path =
member === "capture"
? path
: member === "tool"
? command
: member === "limiter"
? limiter
: "/proc/self/limits";
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_signal_decoders"
: "decode_signal_recording";
cleanup.path = descriptorFailurePath(resource, {
capture: path,
tool: command,
limiter,
});
cleanup.denied = true;
cleanup.handles = [];
onTestFinished(async () => {
@@ -84,22 +85,20 @@ it
cleanup.path = "";
});
const service = new SignalRecordingService(provider);
const first = await service.decode({ path, decoders: "uart" });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const first = discovery
? await service.inspectDecoders({ query: "uart" })
: await service.decode({ path, decoders: "uart" });
expectRetainedDescriptor(first, cleanup, operation);
const launchCount = launches;
expect(await service.decode({ path, decoders: "uart" })).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation,
});
cleanup.denied = false;
await provider.close();
@@ -130,6 +130,71 @@ it("accounts for JSON escape expansion of a stored declaration in the reply limi
]);
});
it("attributes triggers declared with another ASCII case to the stored table name", async () => {
const path = await createDatabase(`
CREATE TABLE Users(id INTEGER PRIMARY KEY, email TEXT);
CREATE INDEX users_email ON users(email);
CREATE TRIGGER audit_insert AFTER INSERT ON users BEGIN SELECT 1; END;
CREATE TRIGGER audit_delete AFTER DELETE ON USERS BEGIN SELECT 1; END;
CREATE VIEW recent AS SELECT 1;
CREATE TRIGGER recent_insert INSTEAD OF INSERT ON Recent BEGIN SELECT 1; END;
`);
const selected = inspectSqliteDatabaseSnapshot(path, {
path,
table: "Users",
});
expect(selected.schema).toMatchObject({
scope: "selected_table",
completeness: "complete",
tables: [{ name: "Users" }],
indexes: [{ name: "users_email", table: "Users" }],
views: [],
});
expect(
selected.schema.triggers.map(({ name, table }) => ({ name, table })),
).toEqual([
{ name: "audit_insert", table: "Users" },
{ name: "audit_delete", table: "Users" },
]);
const inventory = inspectSqliteDatabaseSnapshot(path, { path });
expect(inventory.schema.triggers).toEqual([
{ name: "audit_insert", table: "Users" },
{ name: "audit_delete", table: "Users" },
{ name: "recent_insert", table: "recent" },
]);
});
it.each([
{
selection: "a differently cased table",
schema: "CREATE TABLE Users(id INTEGER PRIMARY KEY)",
trigger: "AFTER INSERT ON Users",
table: "users",
},
{
selection: "an exact view",
schema: "CREATE VIEW Recent AS SELECT 1 AS id",
trigger: "INSTEAD OF INSERT ON recent",
table: "Recent",
},
])(
"refuses $selection before expanding declarations under another spelling",
async ({ schema, trigger, table }) => {
const path = await createDatabase(`
${schema};
CREATE TRIGGER expanded ${trigger} BEGIN /*${"\u0001".repeat(3 * 1024 * 1024)}*/ SELECT 1; END;
`);
expect(() =>
inspectSqliteDatabaseSnapshot(path, { path, table }),
).toThrowError(
expect.objectContaining({
reason: "selection",
message: `Selected ordinary table does not exist with that exact name: ${table}`,
}),
);
},
);
it.each(["UTF-8", "UTF-16le", "UTF-16be"])(
"preserves exact %s schema text when decoding native bytes",
async (encoding) => {
@@ -5,6 +5,7 @@ import { DatabaseSync } from "node:sqlite";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { expect, it as nativeTest, onTestFinished } from "vitest";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
@@ -356,6 +357,73 @@ it("does not execute views when selecting rows", async () => {
});
});
nativeTest.each(["absent.db", "absent-parent/absent.db"])(
"classifies a missing %s as an invalid value",
async (name) => {
const workspace = await createTestWorkspace("rea-sqlite-missing-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = workspace.path(name);
const provider = createProvider();
onTestFinished(() => provider.close());
const result = await provider.inspect({ path });
if (result.ok) throw new Error("Expected a missing database rejection");
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
issues: [
{
path: ["path"],
reason: "invalid_value",
message: `Selected SQLite database does not exist: ${path}`,
},
],
},
});
},
);
it("attributes table and column selection failures to their own arguments", async () => {
const { database } = await createFixture();
const provider = createProvider();
onTestFinished(() => provider.close());
const projection = async (selection: {
table: string;
columns?: string[];
}) => {
const result = await provider.inspect({
path: database.path,
row_limit: 1,
...selection,
});
if (result.ok) throw new Error("Expected a rejected selection");
return projectAnalysisError(result.error);
};
expect(
await projection({ table: "records", columns: ["nope"] }),
).toMatchObject({
details: {
issues: [
{
path: ["columns"],
reason: "invalid_format",
message:
"Selected column does not exist with that exact name in table records: nope",
},
],
},
});
expect(await projection({ table: "absent" })).toMatchObject({
details: { issues: [{ path: ["table"] }] },
});
const selected = await provider.inspect({
path: database.path,
table: "records",
columns: ["id"],
row_limit: 1,
});
if (!selected.ok) throw selected.error;
expect(selected.value.result).toMatchObject({ rows: { columns: ["id"] } });
});
it("rejects malformed databases without altering the selected file", async () => {
const workspace = await createTestWorkspace("rea-sqlite-invalid-");
onTestFinished(() => removeTestWorkspace(workspace.root));