chore: merge main into feat/dylib-resolution
Resolve conflicts against main: - README.md: take main's simplified English README, which no longer has the tool-family table. - README_ja.md: take main's reworded table and count trace_dylib_resolution in the artifact graph row (5 -> 6). - Skill: the references gain the trace_dylib_resolution paragraph, so the version moves to 29 (main already uses 28). - Regenerate the product catalog, conformance manifest, skill digest and package metadata (135 tools). The MCP tool catalog is now built rather than committed (#997), so it is removed here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { Client } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
@@ -11,39 +9,10 @@ import {
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
interface TestHarness {
|
||||
readonly client: Client;
|
||||
readonly session: BinarySession;
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
async function createTestHarness(): Promise<TestHarness> {
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "application-workflow-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
return {
|
||||
client,
|
||||
session,
|
||||
close: async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
import {
|
||||
createApplicationMcpHarness,
|
||||
type ApplicationMcpHarness,
|
||||
} from "./mcpHarness.js";
|
||||
|
||||
async function runInlineEvidenceScenarios(
|
||||
client: Client,
|
||||
@@ -103,7 +72,9 @@ async function runInlineEvidenceScenarios(
|
||||
expect(session.exportEvidenceBundle().records.length).toBeGreaterThan(2);
|
||||
}
|
||||
|
||||
async function runInlineWorkflowScenarios(harness: TestHarness): Promise<void> {
|
||||
async function runInlineWorkflowScenarios(
|
||||
harness: ApplicationMcpHarness,
|
||||
): Promise<void> {
|
||||
const tracedInline = await harness.client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
@@ -250,7 +221,7 @@ async function assertRejectedInlineEvidence(client: Client): Promise<void> {
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("traces and compares authenticated graph Evidence in the session", async () => {
|
||||
const harness = await createTestHarness();
|
||||
const harness = await createApplicationMcpHarness();
|
||||
try {
|
||||
await runInlineEvidenceScenarios(harness.client, harness.session);
|
||||
await runInlineWorkflowScenarios(harness);
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { copyFile, mkdir, rm } from "node:fs/promises";
|
||||
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join, relative, resolve } from "node:path";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { compareJavaScriptExportShapesEvidence } from "../../../src/application/javascript/JavaScriptApplicationWorkflowService.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js";
|
||||
import { createApplicationMcpHarness } from "./mcpHarness.js";
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("compares exact parser export shapes with inline Evidence", async () => {
|
||||
@@ -40,14 +39,8 @@ describe("application workflow MCP parity", () => {
|
||||
const leftAnalysis = javascriptApplicationAnalysisResultSchema.parse(
|
||||
left.value.normalized_result,
|
||||
);
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "export-shape-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const harness = await createApplicationMcpHarness();
|
||||
const { client, session } = harness;
|
||||
const selectors = {
|
||||
left_module_path: "parser.mjs",
|
||||
left_export_name: "default",
|
||||
@@ -55,8 +48,6 @@ describe("application workflow MCP parity", () => {
|
||||
right_export_name: "default",
|
||||
};
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const relativeApplication = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: relative(process.cwd(), leftRoot) },
|
||||
@@ -121,10 +112,114 @@ describe("application workflow MCP parity", () => {
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await harness.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("source-produced export comparison inventories", () => {
|
||||
it("retains large source-produced export inventories through comparison schemas", async () => {
|
||||
const fields = Array.from(
|
||||
{ length: 64 },
|
||||
(_, index) => `field${String(index)}: ${String(index)}`,
|
||||
).join(", ");
|
||||
const returnSites = Array.from(
|
||||
{ length: 33 },
|
||||
(_, index) =>
|
||||
`if (value === ${String(index)}) return { type: "variant-${String(index)}", ${fields} };`,
|
||||
).join("\n");
|
||||
const extraExports = Array.from(
|
||||
{ length: 1_000 },
|
||||
(_, index) =>
|
||||
`export const candidate${String(index)} = ${String(index)};`,
|
||||
).join("\n");
|
||||
const inventorySource = `export default function parse(value) {\n${returnSites}\n throw new Error("no match");\n}\n${extraExports}`;
|
||||
const pairedVariantsSource = `export default function parse(value) {
|
||||
${returnSites}
|
||||
throw new Error("no match");
|
||||
}`;
|
||||
const [inventoryLeft, inventoryRight] = await Promise.all([
|
||||
analyzeSourceEvidence(inventorySource),
|
||||
analyzeSourceEvidence(pairedVariantsSource),
|
||||
]);
|
||||
const variants = compareEvidence(inventoryLeft, inventoryRight);
|
||||
expect(variants.left).toMatchObject({ status: "selected" });
|
||||
expect(variants.coverage).toMatchObject({
|
||||
paired_variants: 33,
|
||||
unpaired_left_variants: 0,
|
||||
unpaired_right_variants: 0,
|
||||
left_source_omitted_variants: 0,
|
||||
right_source_omitted_variants: 0,
|
||||
left_omitted_fields: 0,
|
||||
right_omitted_fields: 0,
|
||||
});
|
||||
|
||||
const missing = compareEvidence(inventoryLeft, inventoryRight, {
|
||||
leftExportName: "missing",
|
||||
});
|
||||
expect(missing.left).toMatchObject({
|
||||
status: "missing",
|
||||
omitted_candidates: 0,
|
||||
});
|
||||
expect(missing.left.candidates).toHaveLength(1_001);
|
||||
|
||||
const changedFieldsLeft = Array.from(
|
||||
{ length: 10_001 },
|
||||
(_, index) => `field${String(index)}: ${String(index)}`,
|
||||
).join(", ");
|
||||
const changedFieldsRight = Array.from(
|
||||
{ length: 10_001 },
|
||||
(_, index) => `field${String(index)}: ${String(index + 1)}`,
|
||||
).join(", ");
|
||||
const [changeLeft, changeRight] = await Promise.all([
|
||||
analyzeSourceEvidence(
|
||||
`export default () => ({ type: "record", ${changedFieldsLeft} });`,
|
||||
),
|
||||
analyzeSourceEvidence(
|
||||
`export default () => ({ type: "record", ${changedFieldsRight} });`,
|
||||
),
|
||||
]);
|
||||
const changes = compareEvidence(changeLeft, changeRight);
|
||||
expect(changes.changes).toHaveLength(10_001);
|
||||
expect(changes.summary).toEqual({
|
||||
added: 0,
|
||||
removed: 0,
|
||||
changed: 10_001,
|
||||
unknown: 0,
|
||||
});
|
||||
expect(changes.coverage).toMatchObject({
|
||||
status: "complete-within-inputs",
|
||||
omitted_changes: 0,
|
||||
left_omitted_fields: 0,
|
||||
right_omitted_fields: 0,
|
||||
});
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
const analyzeSourceEvidence = async (source: string) => {
|
||||
const root = await createTestTempDirectory("rea-export-shape-inventory-");
|
||||
await writeFile(join(root, "parser.mjs"), source);
|
||||
const analyzed = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!analyzed.ok) throw analyzed.error;
|
||||
return analyzed.value;
|
||||
};
|
||||
|
||||
const compareEvidence = (
|
||||
left: Awaited<ReturnType<typeof analyzeSourceEvidence>>,
|
||||
right: Awaited<ReturnType<typeof analyzeSourceEvidence>>,
|
||||
selectors: { readonly leftExportName?: string } = {},
|
||||
) => {
|
||||
const compared = compareJavaScriptExportShapesEvidence({
|
||||
left,
|
||||
right,
|
||||
left_module_path: "parser.mjs",
|
||||
left_export_name: selectors.leftExportName ?? "default",
|
||||
right_module_path: "parser.mjs",
|
||||
right_export_name: "default",
|
||||
});
|
||||
if (!compared.ok) throw compared.error;
|
||||
return javaScriptExportShapeComparisonResultSchema.parse(
|
||||
compared.value.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
/** Owned MCP SDK session shared by application workflow scenarios. */
|
||||
export interface ApplicationMcpHarness {
|
||||
readonly client: Client;
|
||||
readonly session: BinarySession;
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** Connect application workflows through the production MCP registration. */
|
||||
export async function createApplicationMcpHarness(): Promise<ApplicationMcpHarness> {
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "application-workflow-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
return {
|
||||
client,
|
||||
session,
|
||||
close: async () => {
|
||||
await Promise.all([client.close(), server.close(), session.close()]);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -17,12 +17,13 @@ const fixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/fakeLauncher.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const expectAvailableToolInventory = async (client: Client): Promise<void> => {
|
||||
const expectAvailableToolInventory = async (client: Client) => {
|
||||
const listed = await client.listTools();
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.isError).not.toBe(true);
|
||||
const availability = z
|
||||
.object({
|
||||
result: z.object({
|
||||
@@ -43,6 +44,7 @@ const expectAvailableToolInventory = async (client: Client): Promise<void> => {
|
||||
expect(new Set(listed.tools.map(({ name }) => name))).toEqual(
|
||||
new Set(TOOL_CONTRACTS.map(({ name }) => name)),
|
||||
);
|
||||
return status;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -57,72 +59,83 @@ const completeStderrRecords = (stderr: string): unknown[] =>
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line): unknown => JSON.parse(line));
|
||||
|
||||
const callCurrentDocument = async (target?: {
|
||||
readonly path: string;
|
||||
readonly kind?: "database";
|
||||
}) => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [mainPath],
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
...(target === undefined
|
||||
? {}
|
||||
: {
|
||||
HOPPER_TARGET_PATH: target.path,
|
||||
...(target.kind === undefined
|
||||
? {}
|
||||
: { HOPPER_TARGET_KIND: target.kind }),
|
||||
}),
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([fixturePath]),
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer | string) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const client = new Client({ name: "runtime-smoke", version: "1.0.0" });
|
||||
|
||||
let result: Awaited<ReturnType<Client["callTool"]>>;
|
||||
try {
|
||||
await client.connect(transport);
|
||||
result = await client.callTool({
|
||||
name: "current_document",
|
||||
arguments: {},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
return { result, stderr, records: completeStderrRecords(stderr) };
|
||||
};
|
||||
|
||||
describe("production stdio runtime", () => {
|
||||
// The `test:acceptance` lane runs the real entrypoint on the current host;
|
||||
// these cases state each supported host's result in the test name and body.
|
||||
const callCurrentDocument = async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [mainPath],
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_TARGET_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([fixturePath]),
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer | string) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const client = new Client({ name: "runtime-smoke", version: "1.0.0" });
|
||||
|
||||
let result: Awaited<ReturnType<Client["callTool"]>>;
|
||||
try {
|
||||
await client.connect(transport);
|
||||
await expectAvailableToolInventory(client);
|
||||
result = await client.callTool({
|
||||
name: "current_document",
|
||||
arguments: {},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
return { result, stderr, records: completeStderrRecords(stderr) };
|
||||
};
|
||||
|
||||
it.runIf(process.platform === "linux")(
|
||||
"reports the Linux current-document failure through MCP and structured logs",
|
||||
async () => {
|
||||
const { result, stderr, records } = await callCurrentDocument();
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: "text", text: expect.any(String) }),
|
||||
]),
|
||||
);
|
||||
expect(records).toContainEqual(
|
||||
it("reports a missing target through MCP and structured logs", async () => {
|
||||
const { result, stderr, records } = await callCurrentDocument();
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
application: "rea",
|
||||
mode: "mcp",
|
||||
layer: "server",
|
||||
tool: "current_document",
|
||||
status: "error",
|
||||
type: "text",
|
||||
text: expect.stringContaining("No app is open."),
|
||||
}),
|
||||
);
|
||||
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
|
||||
expect(stderr).not.toContain(fixturePath);
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
]),
|
||||
);
|
||||
expect(records).toContainEqual(
|
||||
expect.objectContaining({
|
||||
application: "rea",
|
||||
mode: "mcp",
|
||||
layer: "server",
|
||||
tool: "current_document",
|
||||
status: "error",
|
||||
}),
|
||||
);
|
||||
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
|
||||
expect(stderr).not.toContain(fixturePath);
|
||||
}, 15_000);
|
||||
|
||||
it.runIf(process.platform === "darwin")(
|
||||
"returns the selected document on macOS through MCP and structured logs",
|
||||
async () => {
|
||||
const { result, stderr, records } = await callCurrentDocument();
|
||||
const { result, stderr, records } = await callCurrentDocument({
|
||||
path: process.execPath,
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
const observation = evidenceResultOf(z.literal("fixture")).parse(
|
||||
result.structuredContent,
|
||||
@@ -146,17 +159,13 @@ describe("production stdio runtime", () => {
|
||||
15_000,
|
||||
);
|
||||
|
||||
it("starts with a database-kind initial target without a fatal record", async () => {
|
||||
it("serves the compiled catalog without an initial target or fatal record", async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [mainPath],
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_TARGET_PATH: new URL(import.meta.url).pathname,
|
||||
HOPPER_TARGET_KIND: "database",
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([fixturePath]),
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
@@ -164,23 +173,24 @@ describe("production stdio runtime", () => {
|
||||
transport.stderr?.on("data", (chunk: Buffer | string) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const client = new Client({ name: "database-runtime", version: "1.0.0" });
|
||||
const client = new Client({ name: "catalog-runtime", version: "1.0.0" });
|
||||
|
||||
try {
|
||||
await client.connect(transport);
|
||||
// The catalog itself is already proven against the compiled entrypoint
|
||||
// above, so this test asserts the part that is unique to a database-kind
|
||||
// initial target: the server comes up and serves tools without a fatal
|
||||
// startup record.
|
||||
const listed = await client.listTools();
|
||||
expect(listed.tools.length).toBeGreaterThan(0);
|
||||
// A database-kind initial target must also serve a tool. Merely listing
|
||||
// the catalog starts no bridge work, so without this call the child
|
||||
// writes no startup records at all and the fatal-record assertion below
|
||||
// would pass without observing anything.
|
||||
await expect(
|
||||
client.callTool({ name: "current_document", arguments: {} }),
|
||||
).resolves.toBeDefined();
|
||||
// Keep catalog parity independent of initial target/provider startup.
|
||||
const status = await expectAvailableToolInventory(client);
|
||||
expect(
|
||||
z
|
||||
.object({ result: z.object({ open: z.boolean() }) })
|
||||
.parse(status.structuredContent).result,
|
||||
).toEqual({ open: false });
|
||||
// Closing the empty session produces a structured lifecycle record,
|
||||
// making the fatal-record check observable without launching a provider.
|
||||
const closed = await client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
expect(closed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
@@ -194,6 +204,9 @@ describe("production stdio runtime", () => {
|
||||
records.length,
|
||||
"no startup records were observed, so the fatal-record check is vacuous",
|
||||
).toBeGreaterThan(0);
|
||||
expect(records).toContainEqual(
|
||||
expect.objectContaining({ tool: "close_binary", status: "ok" }),
|
||||
);
|
||||
const fatal = records.filter(
|
||||
(record): record is { level: number } =>
|
||||
typeof record === "object" &&
|
||||
@@ -204,4 +217,30 @@ describe("production stdio runtime", () => {
|
||||
);
|
||||
expect(fatal).toEqual([]);
|
||||
}, 15_000);
|
||||
|
||||
it.runIf(process.platform === "darwin")(
|
||||
"serves a database-kind initial target without a fatal record on macOS",
|
||||
async () => {
|
||||
const { result, records } = await callCurrentDocument({
|
||||
path: fileURLToPath(import.meta.url),
|
||||
kind: "database",
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
evidenceResultOf(z.literal("fixture")).parse(result.structuredContent);
|
||||
expect(records).toContainEqual(
|
||||
expect.objectContaining({ tool: "current_document", status: "ok" }),
|
||||
);
|
||||
expect(
|
||||
records.some(
|
||||
(record) =>
|
||||
typeof record === "object" &&
|
||||
record !== null &&
|
||||
"level" in record &&
|
||||
typeof record.level === "number" &&
|
||||
record.level >= 50,
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -89,6 +89,24 @@ cliTest.skipIf(process.platform !== "linux")(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.skipIf(process.platform !== "linux")(
|
||||
"resolves relative firmware CLI paths against the operator working directory",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-firmware-cli-relative-");
|
||||
await writeFile(join(root, "input.bin"), "firmware fixture");
|
||||
const cliResult = await cli.run({
|
||||
arguments: ["inspect-firmware-regions", "input.bin", "--json"],
|
||||
cwd: root,
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
// A relative path must pass input validation and reach the provider,
|
||||
// which reports the missing firmware engine — not a validation error.
|
||||
expect(cliResult.exitCode).toBe(1);
|
||||
expect(cliResult.json).toMatchObject({ code: "capability_unavailable" });
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves optional JavaScript recovery configuration through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { listBrowserTargetsInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { browserCaptureComparisonInputSchema } from "../../../src/domain/browserCaptureComparison.js";
|
||||
import { compareWebScreenshotsInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
compareWebCaptureEvidence,
|
||||
compareWebScreenshotEvidence,
|
||||
listBrowserTargets,
|
||||
} from "../../../src/application/BrowserObservationService.js";
|
||||
|
||||
describe("browser observation service prerequisites", () => {
|
||||
it("reports a missing provider without requiring a permission grant", async () => {
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "http://[::1]:3000";
|
||||
const result = await listBrowserTargets(
|
||||
undefined,
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("compares supplied scenarios and PNG artifacts without a CDP endpoint", async () => {
|
||||
const browser = new CdpBrowserProvider();
|
||||
const captures = await compareWebCaptureEvidence(
|
||||
browser,
|
||||
browserCaptureComparisonInputSchema.parse(
|
||||
example("compare_web_captures"),
|
||||
),
|
||||
);
|
||||
const screenshots = await compareWebScreenshotEvidence(
|
||||
browser,
|
||||
compareWebScreenshotsInputSchema.parse(
|
||||
example("compare_web_screenshots"),
|
||||
),
|
||||
);
|
||||
for (const result of [captures, screenshots]) {
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.parameters).not.toHaveProperty("cdp_endpoint");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const example = (name: string) => {
|
||||
const input = BROWSER_TOOL_CONTRACTS.find((tool) => tool.name === name)
|
||||
?.examples[0]?.input;
|
||||
if (input === undefined) throw new Error(`Missing example for ${name}`);
|
||||
return input;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
describe("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
it("discovers pages and captures a selected target without an origin list", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
@@ -73,9 +73,12 @@ describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
const browser = await startFakeCdpBrowser({ urlShapedAllowedTitle });
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const input = {
|
||||
const listInput = {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
};
|
||||
const input = {
|
||||
...listInput,
|
||||
target_id: "allowed-page",
|
||||
};
|
||||
const authority = browser.allowedOrigin.replace(/^https?:\/\//u, "");
|
||||
@@ -86,7 +89,7 @@ describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
? "/app?startup=title-secret#fragment"
|
||||
: `${prefix}${authority}/app?startup=title-secret#fragment`;
|
||||
const listed = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse(input),
|
||||
listBrowserTargetsInputSchema.parse(listInput),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets[0]?.title).toBe(expected);
|
||||
@@ -155,7 +158,7 @@ describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 2", () => {
|
||||
describe("CdpBrowserProvider: discovery authorization 2", () => {
|
||||
it("rejects empty browser attachment session identifiers", async () => {
|
||||
const browser = await startFakeCdpBrowser({ invalidAttachedSession: true });
|
||||
trackBrowser(browser);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
@@ -6,20 +6,9 @@ import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalys
|
||||
import { discoverWebMcpToolsInputSchema } from "../../../src/domain/webMcpDiscovery.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 1", () => {
|
||||
it("rejects unknown WebMCP discovery fields", () => {
|
||||
expect(
|
||||
discoverWebMcpToolsInputSchema.safeParse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://example.test"],
|
||||
target_id: "target",
|
||||
unknown_field: true,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describe("CdpBrowserProvider: approved accessibility and source capture", () => {
|
||||
it("captures approved accessibility text inline", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
@@ -120,7 +109,7 @@ describeBrowser("CdpBrowserProvider: document script 1", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: transient WebMCP frames", () => {
|
||||
describe("CdpBrowserProvider: transient WebMCP frames", () => {
|
||||
it("drops stale child tools and reports partial coverage when a blank commit remains", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
@@ -205,7 +194,7 @@ describeBrowser("CdpBrowserProvider: transient WebMCP frames", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 2", () => {
|
||||
describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
|
||||
it("discovers untrusted WebMCP declarations without registering or invoking them", async () => {
|
||||
const browser = await startFakeCdpBrowser({ webMcpTools: true });
|
||||
trackBrowser(browser);
|
||||
@@ -360,7 +349,7 @@ describeBrowser("CdpBrowserProvider: document script 2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider WebMCP inventory completeness", () => {
|
||||
describe("CdpBrowserProvider WebMCP inventory completeness", () => {
|
||||
it("retains every field in a large declared WebMCP input schema", async () => {
|
||||
const propertyCount = 5_001;
|
||||
const browser = await startFakeCdpBrowser({
|
||||
@@ -392,7 +381,7 @@ describeBrowser("CdpBrowserProvider WebMCP inventory completeness", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 3", () => {
|
||||
describe("CdpBrowserProvider: frame scope and screenshots", () => {
|
||||
it("removes WebMCP declarations after their child frame leaves scope", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
@@ -474,7 +463,7 @@ describeBrowser("CdpBrowserProvider: document script 3", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 4", () => {
|
||||
describe("CdpBrowserProvider: complete passive inventories", () => {
|
||||
it("returns every frame, resource, worker, accessibility, and storage inventory item", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
trackBrowser(browser);
|
||||
@@ -501,7 +490,7 @@ describeBrowser("CdpBrowserProvider: document script 4", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: WebMCP registration owners", () => {
|
||||
describe("CdpBrowserProvider: WebMCP registration owners", () => {
|
||||
it.each(["retain", "remove-second"] as const)(
|
||||
"keeps same-URL frame owners separate: %s",
|
||||
async (mode) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
@@ -11,9 +11,9 @@ import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 1", () => {
|
||||
describe("CdpBrowserProvider: cancellation and session events", () => {
|
||||
it("projects direct-session cancellation onto the requested operation", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
@@ -132,7 +132,7 @@ describeBrowser("CdpBrowserProvider: lifecycle failures 1", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 2", () => {
|
||||
describe("CdpBrowserProvider: session termination and scope changes", () => {
|
||||
it("ends a browser session when its flat target session detaches", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "target_detached",
|
||||
@@ -243,7 +243,7 @@ describeBrowser("CdpBrowserProvider: lifecycle failures 2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 3", () => {
|
||||
describe("CdpBrowserProvider: protocol failures and cancellation cleanup", () => {
|
||||
it("degrades optional domains but propagates protocol and payload failures", async () => {
|
||||
const optional = await startFakeCdpBrowser({
|
||||
unsupportedMethods: ["Accessibility.getFullAXTree"],
|
||||
@@ -373,7 +373,7 @@ describeBrowser("CdpBrowserProvider: lifecycle failures 3", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 4", () => {
|
||||
describe("CdpBrowserProvider: navigation commit and target identity", () => {
|
||||
it("waits for navigation commit and rechecks the attached main-frame origin", async () => {
|
||||
const transitioning = await startFakeCdpBrowser({
|
||||
transitionalFrameReads: 2,
|
||||
|
||||
@@ -1,11 +1,64 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describe("CdpBrowserProvider: network 1", () => {
|
||||
it("retains same-origin redirect hops on the one final request", async () => {
|
||||
const browser = await startFakeCdpBrowser({ redirectWithinOrigin: true });
|
||||
trackBrowser(browser);
|
||||
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;
|
||||
expect(result.value.network.requests).toHaveLength(1);
|
||||
expect(result.value.network.requests[0]).toMatchObject({
|
||||
request_id: "request-1",
|
||||
url: `${browser.allowedOrigin}/redirected?token=final-secret`,
|
||||
status: 200,
|
||||
redirects: [
|
||||
{
|
||||
url: `${browser.allowedOrigin}/api?token=network-secret`,
|
||||
response_url: `${browser.allowedOrigin}/api?token=network-secret`,
|
||||
method: "POST",
|
||||
resource_type: "Fetch",
|
||||
status: 301,
|
||||
mime_type: "text/plain",
|
||||
encoded_data_length: 23,
|
||||
request_timestamp: 7,
|
||||
redirect_event_timestamp: 8,
|
||||
},
|
||||
{
|
||||
url: `${browser.allowedOrigin}/intermediate`,
|
||||
response_url: `${browser.allowedOrigin}/intermediate`,
|
||||
method: "GET",
|
||||
resource_type: "Fetch",
|
||||
status: 302,
|
||||
mime_type: "text/plain",
|
||||
encoded_data_length: 27,
|
||||
request_timestamp: 8,
|
||||
redirect_event_timestamp: 9,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(result.value.network.requests)).not.toContain(
|
||||
"redirect-header-secret",
|
||||
);
|
||||
expect(result.value.completeness.excluded).not.toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: network 1", () => {
|
||||
it("drops network evidence when a request redirects outside the approved origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
redirectToDisallowedOrigin: true,
|
||||
@@ -23,4 +76,42 @@ describeBrowser("CdpBrowserProvider: network 1", () => {
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not retain excluded prior-hop data when a redirect returns in scope", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
redirectFromDisallowedOrigin: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
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;
|
||||
expect(result.value.network.requests).toHaveLength(1);
|
||||
expect(result.value.network.requests[0]).toMatchObject({
|
||||
url: `${browser.allowedOrigin}/returned`,
|
||||
redirects: [],
|
||||
});
|
||||
const output = JSON.stringify(result.value.network.requests);
|
||||
expect(output).not.toContain("private.example.test");
|
||||
expect(output).not.toContain("redirect-header-secret");
|
||||
expect(output).not.toContain("redirect-body-secret");
|
||||
expect(result.value.completeness.policy_filtered_sections).toContain(
|
||||
"network_requests",
|
||||
);
|
||||
expect(result.value.completeness.status).toBe("policy_filtered");
|
||||
expect(result.value.completeness.unavailable_sections).not.toContain(
|
||||
"network_requests",
|
||||
);
|
||||
expect(result.value.completeness.excluded).not.toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: expect.any(Number),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import type { FakeOptions } from "../../fixtures/fakeCdpBrowserTypes.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
const inspectNetwork = async (options: FakeOptions) => {
|
||||
const browser = await startFakeCdpBrowser(options);
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return { browser, inspection: result.value };
|
||||
};
|
||||
|
||||
describe("CdpBrowserProvider: redirect errors", () => {
|
||||
it.each([
|
||||
{ label: "missing", url: undefined, reason: "invalid_protocol_value" },
|
||||
{ label: "malformed", url: "http://%", reason: "invalid_protocol_value" },
|
||||
{
|
||||
label: "unsupported scheme",
|
||||
url: "file:///private/redirect",
|
||||
reason: "unsupported_url",
|
||||
},
|
||||
])("classifies $label redirect response URLs", async ({ url, reason }) => {
|
||||
const { inspection } = await inspectNetwork({
|
||||
malformedRedirectResponse: true,
|
||||
...(url === undefined ? {} : { redirectResponseUrl: url }),
|
||||
});
|
||||
|
||||
expect(inspection.network.requests).toEqual([]);
|
||||
expect(inspection.completeness.excluded).toContainEqual({
|
||||
section: "network_requests",
|
||||
reason,
|
||||
count: expect.any(Number),
|
||||
});
|
||||
const section =
|
||||
reason === "unsupported_url"
|
||||
? inspection.completeness.policy_filtered_sections
|
||||
: inspection.completeness.unavailable_sections;
|
||||
expect(section).toContain("network_requests");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ label: "null", envelope: null },
|
||||
{ label: "array", envelope: [] },
|
||||
{ label: "scalar", envelope: "malformed redirect" },
|
||||
])(
|
||||
"preserves prior request for a $label redirect envelope",
|
||||
async ({ envelope }) => {
|
||||
const { browser, inspection } = await inspectNetwork({
|
||||
malformedRedirectResponse: true,
|
||||
redirectResponseEnvelope: envelope,
|
||||
});
|
||||
|
||||
expect(inspection.network.requests).toHaveLength(1);
|
||||
expect(inspection.network.requests[0]).toMatchObject({
|
||||
request_id: "request-1",
|
||||
url: `${browser.allowedOrigin}/malformed-redirect-prior`,
|
||||
status: 201,
|
||||
mime_type: "application/json",
|
||||
encoded_data_length: null,
|
||||
redirects: [
|
||||
{
|
||||
url: `${browser.allowedOrigin}/api?token=network-secret`,
|
||||
response_url: `${browser.allowedOrigin}/api?token=network-secret`,
|
||||
request_timestamp: 7,
|
||||
redirect_event_timestamp: 8,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
inspection.network.requests[0]?.body_shapes.request,
|
||||
).not.toBeNull();
|
||||
expect(inspection.network.requests[0]?.body_shapes.response).toBeNull();
|
||||
expect(inspection.network.requests[0]?.body_shapes.status).toBe(
|
||||
"partial",
|
||||
);
|
||||
expect(inspection.metadata.responses).toHaveLength(1);
|
||||
expect(inspection.metadata.responses[0]).toMatchObject({
|
||||
url: `${browser.allowedOrigin}/malformed-redirect-prior`,
|
||||
mime_type: "application/json",
|
||||
content_length: 123,
|
||||
content_encoding: "gzip",
|
||||
});
|
||||
expect(inspection.completeness.unavailable_sections).toContain(
|
||||
"network_requests",
|
||||
);
|
||||
expect(inspection.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
expect(inspection.completeness.excluded).toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: expect.any(Number),
|
||||
});
|
||||
expect(inspection.completeness.excluded).toContainEqual({
|
||||
section: "json_body_shapes",
|
||||
reason: "invalid_protocol_value",
|
||||
count: expect.any(Number),
|
||||
});
|
||||
expect(JSON.stringify(inspection.network.requests)).not.toContain(
|
||||
"malformed-redirect-final",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps authorized prior evidence when the later response URL is disallowed", async () => {
|
||||
const { browser, inspection } = await inspectNetwork({
|
||||
malformedRedirectResponse: true,
|
||||
redirectResponseEnvelope: null,
|
||||
responseAfterMalformedUrl:
|
||||
"https://private.example.test/late?token=unauthorized-secret",
|
||||
});
|
||||
|
||||
expect(inspection.network.requests).toHaveLength(1);
|
||||
expect(inspection.network.requests[0]).toMatchObject({
|
||||
url: `${browser.allowedOrigin}/malformed-redirect-prior`,
|
||||
status: 201,
|
||||
mime_type: "application/json",
|
||||
encoded_data_length: null,
|
||||
body_shapes: { status: "partial", response: null },
|
||||
});
|
||||
expect(inspection.metadata.responses).toHaveLength(1);
|
||||
expect(inspection.metadata.responses[0]?.url).toBe(
|
||||
`${browser.allowedOrigin}/malformed-redirect-prior`,
|
||||
);
|
||||
expect(inspection.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
expect(inspection.completeness.excluded).toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: expect.any(Number),
|
||||
});
|
||||
const output = JSON.stringify(inspection);
|
||||
expect(output).not.toContain("private.example.test");
|
||||
expect(output).not.toContain("unauthorized-secret");
|
||||
expect(output).not.toContain("header-secret");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 1", () => {
|
||||
describe("CdpBrowserProvider: passive evidence redaction", () => {
|
||||
it("captures bounded passive evidence without retaining sensitive values", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
binaryWebSocketEvent: true,
|
||||
@@ -158,7 +158,7 @@ describeBrowser("CdpBrowserProvider: sensitive data 1", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: page cookie scope", () => {
|
||||
describe("CdpBrowserProvider: page cookie scope", () => {
|
||||
it("uses the attached page URL for cookies and its origin for DOM storage", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
@@ -190,7 +190,7 @@ describeBrowser("CdpBrowserProvider: page cookie scope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: complete storage fingerprints", () => {
|
||||
describe("CdpBrowserProvider: complete storage fingerprints", () => {
|
||||
it("fingerprints cache bodies above the former byte ceiling", async () => {
|
||||
const body = "x".repeat(64 * 1_024 + 1);
|
||||
const browser = await startFakeCdpBrowser({ cachedResponseBody: body });
|
||||
@@ -217,7 +217,7 @@ describeBrowser("CdpBrowserProvider: complete storage fingerprints", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
|
||||
describe("CdpBrowserProvider: explicitly requested text and payload shapes", () => {
|
||||
it("captures requested console text verbatim and value-free payload shapes", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sensitiveShapes: true,
|
||||
@@ -309,45 +309,7 @@ describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: complete sensitive data", () => {
|
||||
it("returns complete requested text and payload shapes verbatim", async () => {
|
||||
const browser = await startFakeCdpBrowser({ sensitiveShapes: true });
|
||||
trackBrowser(browser);
|
||||
const request = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
include_console_text: true,
|
||||
include_json_body_shapes: true,
|
||||
include_websocket_shapes: true,
|
||||
});
|
||||
const result = await new CdpBrowserProvider().inspectPage(request);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.console.events[0]?.text_capture).toEqual({
|
||||
status: "included",
|
||||
values: [
|
||||
{
|
||||
argument_index: 0,
|
||||
type: "string",
|
||||
text: "authorization=Bearer console-secret",
|
||||
},
|
||||
{ argument_index: 1, type: "number", text: "42" },
|
||||
],
|
||||
retained_bytes:
|
||||
Buffer.byteLength("authorization=Bearer console-secret") +
|
||||
Buffer.byteLength("42"),
|
||||
});
|
||||
expect(result.value.network.requests[0]?.body_shapes.status).toBe(
|
||||
"included",
|
||||
);
|
||||
expect(result.value.network.websocket_events[0]?.payload_shape).toEqual({
|
||||
format: "json",
|
||||
json_shape: expect.objectContaining({ root_type: "object" }),
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpBrowserProvider: malformed approved payloads", () => {
|
||||
it("fails closed on malformed approved response and binary payload encodings", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
invalidResponseBodyBase64: true,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe } from "vitest";
|
||||
import { afterEach } from "vitest";
|
||||
|
||||
import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
@@ -11,5 +11,3 @@ afterEach(async () => {
|
||||
export const trackBrowser = (browser: FakeCdpBrowser): void => {
|
||||
browsers.push(browser);
|
||||
};
|
||||
|
||||
export const describeBrowser = describe;
|
||||
|
||||
@@ -1,29 +1,11 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider navigation timeline", () => {
|
||||
it("accepts caller-selected windows and rejects the removed event-count option", () => {
|
||||
const accepted = observeWebSessionInputSchema.safeParse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
observation_ms: 120_000,
|
||||
});
|
||||
expect(accepted.success).toBe(true);
|
||||
expect(
|
||||
observeWebSessionInputSchema.safeParse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
max_timeline_events: 1,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describe("CdpBrowserProvider navigation timeline", () => {
|
||||
it("returns every event beyond the former default collection cap", async () => {
|
||||
const additionalEvents = 2_001;
|
||||
const browser = await startFakeCdpBrowser({
|
||||
|
||||
@@ -1,52 +1,61 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
|
||||
import {
|
||||
captureFrames,
|
||||
captureResources,
|
||||
} from "../../../src/browser/CdpCaptureDocuments.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
it("reports malformed child frame entries instead of silently completing inventory", () => {
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
const captured = captureFrames(
|
||||
{
|
||||
frameTree: {
|
||||
frame: {
|
||||
id: "main",
|
||||
url: "https://example.test/",
|
||||
},
|
||||
childFrames: [
|
||||
null,
|
||||
{ frame: { id: "child", url: "https://example.test/child" } },
|
||||
],
|
||||
},
|
||||
},
|
||||
new Set(["https://example.test"]),
|
||||
undefined,
|
||||
completeness,
|
||||
it("reports malformed child frame entries through the CDP boundary", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: (command, origin) =>
|
||||
command.method === "Page.getFrameTree"
|
||||
? {
|
||||
frameTree: {
|
||||
frame: { id: "main", url: `${origin}/` },
|
||||
childFrames: [
|
||||
null,
|
||||
{ frame: { id: "child", url: `${origin}/child` } },
|
||||
],
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(captured.items.map(({ frame_id }) => frame_id)).toEqual([
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.frames.map(({ frame_id }) => frame_id)).toEqual([
|
||||
"main",
|
||||
"child",
|
||||
]);
|
||||
expect(completeness.snapshot().unavailable_sections).toContain("frames");
|
||||
expect(result.value.completeness.unavailable_sections).toContain("frames");
|
||||
});
|
||||
|
||||
it("reports missing top-level frame trees for frame and resource inventories", () => {
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
expect(
|
||||
captureFrames(
|
||||
{},
|
||||
new Set(["https://example.test"]),
|
||||
undefined,
|
||||
completeness,
|
||||
).items,
|
||||
).toEqual([]);
|
||||
expect(
|
||||
captureResources({}, new Set(["https://example.test"]), completeness).items,
|
||||
).toEqual([]);
|
||||
expect(completeness.snapshot().unavailable_sections).toEqual(
|
||||
expect.arrayContaining(["frames", "resources"]),
|
||||
it("marks a missing resource frame tree incomplete through CDP", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: (command) =>
|
||||
command.method === "Page.getResourceTree" ? {} : undefined,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
|
||||
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;
|
||||
expect(result.value.resources).toEqual([]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain("resources");
|
||||
});
|
||||
|
||||
@@ -1,65 +1,8 @@
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { CdpCaptureEvents } from "../../../src/browser/CdpCaptureEvents.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import type { CdpEvent } from "../../../src/browser/CdpConnection.js";
|
||||
|
||||
const events = (): CdpCaptureEvents =>
|
||||
new CdpCaptureEvents(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://example.test"],
|
||||
target_id: "page-1",
|
||||
}),
|
||||
new Set(["https://example.test"]),
|
||||
);
|
||||
|
||||
const frameNavigated = (url: string, loaderId: string): CdpEvent => ({
|
||||
method: "Page.frameNavigated",
|
||||
params: {
|
||||
frame: { id: "main", url, loaderId },
|
||||
},
|
||||
});
|
||||
|
||||
it("ignores a repeated frameNavigated for the document already committed", () => {
|
||||
const state = events();
|
||||
state.beginAuthorizedFrame("main");
|
||||
state.ingest(frameNavigated("https://example.test/page", "loader-1"));
|
||||
expect(state.navigationDuringCapture).toBe(true);
|
||||
state.navigationDuringCapture = false;
|
||||
|
||||
// A re-fire with the same URL and loader is not a navigation.
|
||||
state.ingest(frameNavigated("https://example.test/page", "loader-1"));
|
||||
expect(state.navigationDuringCapture).toBe(false);
|
||||
});
|
||||
|
||||
it("still reports a genuine change of document", () => {
|
||||
const state = events();
|
||||
state.beginAuthorizedFrame("main");
|
||||
state.ingest(frameNavigated("https://example.test/page", "loader-1"));
|
||||
state.navigationDuringCapture = false;
|
||||
state.ingest(frameNavigated("https://example.test/other", "loader-2"));
|
||||
expect(state.navigationDuringCapture).toBe(true);
|
||||
});
|
||||
|
||||
it("does not forget a navigation that happened during the observation window", () => {
|
||||
const state = events();
|
||||
state.beginAuthorizedFrame("main");
|
||||
state.ingest(frameNavigated("https://example.test/page", "loader-1"));
|
||||
// The final capture re-attaches to the resolved frame; clearing the flag here
|
||||
// used to report a clean capture while carrying pre-navigation state.
|
||||
state.beginFinalCapture("main");
|
||||
expect(state.navigationDuringCapture).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a settled observation window clean", () => {
|
||||
const state = events();
|
||||
state.beginAuthorizedFrame("main");
|
||||
state.beginFinalCapture("main");
|
||||
expect(state.navigationDuringCapture).toBe(false);
|
||||
});
|
||||
|
||||
it("captures a page without aborting on a duplicate frame event", async () => {
|
||||
const browser = await startFakeCdpBrowser({ sessionTimeline: "same_origin" });
|
||||
|
||||
@@ -199,25 +199,6 @@ describe("CdpElectronProvider target selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron request schemas", () => {
|
||||
it("rejects unknown request fields", () => {
|
||||
expect(
|
||||
listElectronTargetsInputSchema.safeParse({
|
||||
cdp_endpoint: "http://127.0.0.1:9223",
|
||||
unknown_field: true,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
inspectElectronPageInputSchema.safeParse({
|
||||
cdp_endpoint: "http://127.0.0.1:9223",
|
||||
target_id: "page-1",
|
||||
observation_ms: 0,
|
||||
unknown_field: true,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider capture", () => {
|
||||
it("captures Electron script source only after separate approval", async () => {
|
||||
const root = await electronFixture();
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { safeResponseMetadata } from "../../../src/browser/CdpSafeMetadata.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
describe("safe CDP response metadata", () => {
|
||||
it("drops credential headers and preserves complete local link URLs", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-1",
|
||||
`${origin}/api`,
|
||||
{
|
||||
mimeType: "application/json",
|
||||
headers: {
|
||||
Authorization: "Bearer credential-secret",
|
||||
Cookie: "session=cookie-secret",
|
||||
"Set-Cookie": "session=response-secret",
|
||||
Link: `</agent?token=link-secret>; rel="mcp service-desc"; title="a,b", <https://private.example.test/x>; rel="mcp"`,
|
||||
"Content-Security-Policy":
|
||||
"default-src 'self'; script-src 'nonce-nonce-secret' 'sha256-hash-secret' https://private.example.test",
|
||||
"Permissions-Policy":
|
||||
"camera=(), geolocation=(self), invalid secret=()",
|
||||
"X-Model-Context": "agent-header-secret",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response).toMatchObject({
|
||||
url: `${origin}/api`,
|
||||
csp: {
|
||||
nonce_count: 1,
|
||||
hash_count: 1,
|
||||
directives: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "script-src",
|
||||
sources: expect.arrayContaining([
|
||||
{ kind: "external_origin", value: null },
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
links: [
|
||||
{
|
||||
href: `${origin}/agent?token=link-secret`,
|
||||
destination_scope: "approved",
|
||||
rel: ["mcp", "service-desc"],
|
||||
as: null,
|
||||
type: null,
|
||||
crossorigin: null,
|
||||
},
|
||||
expect.objectContaining({
|
||||
href: "https://private.example.test/x",
|
||||
destination_scope: "outside_policy",
|
||||
}),
|
||||
],
|
||||
policies: { permissions_policy_features: ["camera", "geolocation"] },
|
||||
});
|
||||
expect(captured.agentHints).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ mechanism: "link_rel" }),
|
||||
expect.objectContaining({
|
||||
mechanism: "response_header",
|
||||
declaration: "x-model-context",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const serialized = JSON.stringify(captured);
|
||||
for (const secret of [
|
||||
"credential-secret",
|
||||
"cookie-secret",
|
||||
"response-secret",
|
||||
"nonce-secret",
|
||||
"hash-secret",
|
||||
"agent-header-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(serialized).toContain("link-secret");
|
||||
expect(serialized).toContain("private.example.test/x");
|
||||
});
|
||||
|
||||
it("reports well-known agent resources as untrusted observations", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-2",
|
||||
`${origin}/.well-known/mcp?token=secret`,
|
||||
{ headers: {} },
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.agentHints).toEqual([
|
||||
{
|
||||
mechanism: "well_known_resource",
|
||||
declaration: "/.well-known/mcp",
|
||||
url: `${origin}/.well-known/mcp?token=secret`,
|
||||
trust: "page-declared-untrusted",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains every parsed header, CSP directive, link, relation, and policy feature", () => {
|
||||
const csp = Array.from(
|
||||
{ length: 105 },
|
||||
(_, index) => `x-${String(index)} 'self'`,
|
||||
).join("; ");
|
||||
const links = Array.from(
|
||||
{ length: 105 },
|
||||
(_, index) => `</${String(index)}>; rel="mcp service-desc"`,
|
||||
).join(", ");
|
||||
const permissions = Array.from(
|
||||
{ length: 205 },
|
||||
(_, index) => `feature-${String(index)}=()`,
|
||||
).join(", ");
|
||||
const headers = Object.fromEntries(
|
||||
Array.from({ length: 501 }, (_, index) => [
|
||||
`x-extra-${String(index)}`,
|
||||
"ok",
|
||||
]),
|
||||
);
|
||||
const captured = safeResponseMetadata(
|
||||
"request-1",
|
||||
`${origin}/api`,
|
||||
{
|
||||
mimeType: "application/json",
|
||||
headers: {
|
||||
...headers,
|
||||
"Content-Security-Policy": csp,
|
||||
Link: links,
|
||||
"Permissions-Policy": permissions,
|
||||
"X-Model-Context": "present-after-many-headers",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response.csp.directives).toHaveLength(105);
|
||||
expect(captured.response.links).toHaveLength(105);
|
||||
expect(captured.response.policies.permissions_policy_features).toHaveLength(
|
||||
205,
|
||||
);
|
||||
expect(captured.agentHints).toContainEqual(
|
||||
expect.objectContaining({ declaration: "x-model-context" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("safe CDP response metadata CSP sources", () => {
|
||||
it("classifies scheme-less CSP host sources by their own host, not the page origin", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-csp",
|
||||
`${origin}/api`,
|
||||
{
|
||||
headers: {
|
||||
"Content-Security-Policy":
|
||||
"script-src cdn.example.test *.trusted.test * 'self' https://api.other.test",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response.csp.directives).toEqual([
|
||||
{
|
||||
name: "script-src",
|
||||
sources: [
|
||||
{ kind: "external_origin", value: null },
|
||||
{ kind: "external_origin", value: null },
|
||||
{ kind: "external_origin", value: null },
|
||||
{ kind: "keyword", value: "'self'" },
|
||||
{ kind: "external_origin", value: null },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("inherits the protected resource scheme for a scheme-less host source", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-csp-scheme",
|
||||
`${origin}/api`,
|
||||
{
|
||||
headers: {
|
||||
"Content-Security-Policy":
|
||||
"script-src cdn.example.test app.example.test",
|
||||
},
|
||||
},
|
||||
new Set([origin, "https://cdn.example.test"]),
|
||||
);
|
||||
|
||||
expect(captured.response.csp.directives[0]?.sources).toEqual([
|
||||
{ kind: "approved_origin", value: "https://cdn.example.test" },
|
||||
{ kind: "approved_origin", value: origin },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Link header value delimiters", () => {
|
||||
const captureLinks = (link: string) =>
|
||||
safeResponseMetadata(
|
||||
"owned",
|
||||
"https://owned.test/page",
|
||||
{
|
||||
headers: { Link: link },
|
||||
},
|
||||
new Set(["https://owned.test"]),
|
||||
).response.links;
|
||||
|
||||
it("preserves commas in URI references and separates later links", () => {
|
||||
const links = captureLinks(
|
||||
'</assets/red,blue.js>; rel="preload"; as=script, </ordinary.js>; rel="modulepreload"',
|
||||
);
|
||||
expect(links.map(({ href }) => href)).toEqual([
|
||||
"https://owned.test/assets/red,blue.js",
|
||||
"https://owned.test/ordinary.js",
|
||||
]);
|
||||
expect(links[0]?.as).toBe("script");
|
||||
});
|
||||
|
||||
it("preserves semicolons and commas inside quoted parameter values", () => {
|
||||
const links = captureLinks(
|
||||
'</plugin.js>; rel="preload"; type="text/javascript; charset=utf-8"; title="a,b", </ordinary.js>; rel="modulepreload"',
|
||||
);
|
||||
expect(links).toHaveLength(2);
|
||||
expect(links[0]?.type).toBe("text/javascript; charset=utf-8");
|
||||
expect(links[1]?.href).toBe("https://owned.test/ordinary.js");
|
||||
});
|
||||
|
||||
it("counts quoted-pair escapes rather than treating every preceding slash as an escape", () => {
|
||||
const links = captureLinks(
|
||||
String.raw`</one.js>; title="ends with \\"; rel="preload", </two.js>; rel="modulepreload"`,
|
||||
);
|
||||
expect(links.map(({ href }) => href)).toEqual([
|
||||
"https://owned.test/one.js",
|
||||
"https://owned.test/two.js",
|
||||
]);
|
||||
expect(links[0]?.rel).toEqual(["preload"]);
|
||||
});
|
||||
|
||||
it("keeps a quoted escaped quote from exposing a delimiter", () => {
|
||||
const links = captureLinks(
|
||||
String.raw`</one.js>; title="quoted \" comma, value"; rel="preload", </two.js>; rel="modulepreload"`,
|
||||
);
|
||||
expect(links).toHaveLength(2);
|
||||
expect(links[0]?.rel).toEqual(["preload"]);
|
||||
});
|
||||
|
||||
it("retains the existing outside-policy classification", () => {
|
||||
const links = captureLinks(
|
||||
'<https://elsewhere.test/red,blue.js>; rel="preload", </ordinary.js>; rel="modulepreload"',
|
||||
);
|
||||
expect(links[0]?.destination_scope).toBe("outside_policy");
|
||||
expect(links[1]?.destination_scope).toBe("approved");
|
||||
});
|
||||
});
|
||||
describe("safe CDP response metadata referrer policy", () => {
|
||||
it.each<[string | undefined, string | null]>([
|
||||
[
|
||||
"no-referrer, strict-origin-when-cross-origin",
|
||||
"strict-origin-when-cross-origin",
|
||||
],
|
||||
["origin, future-policy", "origin"],
|
||||
["future-policy, no-referrer", "no-referrer"],
|
||||
["unsafe-url, NO-REFERRER", "no-referrer"],
|
||||
["origin,, no-referrer", "no-referrer"],
|
||||
["future-policy", null],
|
||||
['unsafe-url, "no-referrer"', null],
|
||||
["no-referrer; report-to=x, origin", null],
|
||||
["", null],
|
||||
[undefined, null],
|
||||
...[
|
||||
"no-referrer",
|
||||
"no-referrer-when-downgrade",
|
||||
"same-origin",
|
||||
"origin",
|
||||
"strict-origin",
|
||||
"origin-when-cross-origin",
|
||||
"strict-origin-when-cross-origin",
|
||||
"unsafe-url",
|
||||
].map((policy): [string, string] => [policy, policy]),
|
||||
])("normalizes declared Referrer-Policy %s", (raw, expected) => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-referrer",
|
||||
`${origin}/api`,
|
||||
{
|
||||
headers: {
|
||||
"Referrer-Policy": raw,
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
expect(captured.response.policies.referrer_policy).toBe(expected);
|
||||
expect(captured.response.policies.coop).toBe("same-origin");
|
||||
});
|
||||
});
|
||||
@@ -82,7 +82,12 @@ it.each(
|
||||
});
|
||||
} else {
|
||||
const result = await provider.observeExecution(
|
||||
observeWebExecutionInputSchema.parse({ ...scope, observation_ms: 5 }),
|
||||
observeWebExecutionInputSchema.parse({
|
||||
...scope,
|
||||
// This fixture sends a real WebSocket event after the armed receipt.
|
||||
// Leave room for transport delivery on a shared CI runner.
|
||||
observation_ms: 100,
|
||||
}),
|
||||
{
|
||||
progress: {
|
||||
report: async (update) => {
|
||||
@@ -124,8 +129,17 @@ it.each(
|
||||
({ script_id }) => script_id === "script-a",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(result.value.requests[0]?.callsites[0]?.source_association).toBe(
|
||||
"unknown",
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.requests).toContainEqual(
|
||||
expect.objectContaining({
|
||||
request_id: "source-completion-request",
|
||||
callsites: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
script_id: "script-a",
|
||||
source_association: "unknown",
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(result.value.script_inventory.main_document_scripts).toBe(1);
|
||||
expect(
|
||||
|
||||
@@ -122,8 +122,11 @@ it("retains active hook lifecycle and IPC evidence without a count ceiling", asy
|
||||
const script = join(root, "exercise.cjs");
|
||||
await writeFile(script, activeCaptureSource);
|
||||
const hook = join(process.cwd(), "scripts/electron-active-hook.cjs");
|
||||
const output = await runNode(hook, script, root, root);
|
||||
const result = JSON.parse(output.trim().split("\n").at(-1) ?? "null") as {
|
||||
const execution = await runNode(hook, script, root, root);
|
||||
expect(execution.code).toBe(0);
|
||||
const result = JSON.parse(
|
||||
execution.stdout.trim().split("\n").at(-1) ?? "null",
|
||||
) as {
|
||||
readonly default_popup_decision: { readonly action: string };
|
||||
readonly popup_decision: { readonly action: string };
|
||||
readonly snapshot: {
|
||||
@@ -181,7 +184,7 @@ it("preserves fatal process termination after recording uncaught exceptions", as
|
||||
const script = join(root, "fatal.cjs");
|
||||
await writeFile(script, 'throw new Error("fatal-hook-secret");\n');
|
||||
const hook = join(process.cwd(), "scripts/electron-active-hook.cjs");
|
||||
const result = await runNodeStatus(hook, script, root, root);
|
||||
const result = await runNode(hook, script, root, root);
|
||||
|
||||
expect(result.code).not.toBe(0);
|
||||
expect(result.stderr).toContain("fatal-hook-secret");
|
||||
@@ -192,7 +195,11 @@ const runNode = (
|
||||
script: string,
|
||||
moduleRoot: string,
|
||||
cwd: string,
|
||||
): Promise<string> =>
|
||||
): Promise<{
|
||||
readonly code: number | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ["-r", hook, script], {
|
||||
cwd,
|
||||
@@ -207,44 +214,11 @@ const runNode = (
|
||||
child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
|
||||
child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) {
|
||||
const text = Buffer.concat(stdout).toString("utf8");
|
||||
if (text.length > 0) resolve(text);
|
||||
else
|
||||
reject(
|
||||
new Error(
|
||||
`hook fixture produced no output: ${Buffer.concat(stderr).toString("utf8")}`,
|
||||
),
|
||||
);
|
||||
} else
|
||||
reject(
|
||||
new Error(
|
||||
`hook fixture exited with ${String(code)}: ${Buffer.concat(stderr).toString("utf8")}`,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const runNodeStatus = (
|
||||
hook: string,
|
||||
script: string,
|
||||
moduleRoot: string,
|
||||
cwd: string,
|
||||
): Promise<{ readonly code: number | null; readonly stderr: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ["-r", hook, script], {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_PATH: moduleRoot,
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stderr: Buffer[] = [];
|
||||
child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) =>
|
||||
resolve({ code, stderr: Buffer.concat(stderr).toString("utf8") }),
|
||||
resolve({
|
||||
code,
|
||||
stdout: Buffer.concat(stdout).toString("utf8"),
|
||||
stderr: Buffer.concat(stderr).toString("utf8"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
mkdtemp,
|
||||
rm,
|
||||
truncate,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { HistoricalCaptureDecoder } from "../../../src/browser/history/HistoricalCaptureDecoder.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "../../../src/browser/history/CaptureRelease.js";
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
} from "../../../src/domain/webNetworkCapture.js";
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
|
||||
it.each([true, false])(
|
||||
"binds decoder replies to the complete selected provider identity (matching name: %s)",
|
||||
async (matching) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-capture-identity-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "capture.har");
|
||||
const text = JSON.stringify(historicalHar());
|
||||
await writeFile(path, text);
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
const value = decodeHarCapture(text, []);
|
||||
if (!matching) value.decoder.name = "different adapter";
|
||||
await writeFile(
|
||||
join(runtimePath, "reply.json"),
|
||||
JSON.stringify({ ok: true, value }),
|
||||
);
|
||||
return { command: process.execPath, arguments: ["-e", ""] };
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(matching);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
else expect(result.value.decoder).toEqual(HAR_CAPTURE_PROVIDER_IDENTITY);
|
||||
},
|
||||
);
|
||||
|
||||
it("classifies an oversized selected capture before creating an owned decoder", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-limit-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, "");
|
||||
await truncate(path, WEB_NETWORK_CAPTURE_LIMITS.inputBytes + 1);
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
throw new Error("Oversized input must not launch decoding");
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Oversized input must fail");
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: "out_of_range",
|
||||
expected: {
|
||||
maximum_capture_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not misclassify decoder filesystem failures as missing selected input", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-command-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
throw Object.assign(
|
||||
new Error("Configured decoder command file missing"),
|
||||
{ code: "ENOENT" },
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Failed decoder command must fail");
|
||||
expect(result.error._tag).toBe("ProviderAdapterError");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
reason: "Configured decoder command file missing",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["missing-capture", "missing-reply", "failed-command"])(
|
||||
"redacts declared paths and diagnostics while preserving the %s failure",
|
||||
async (mode) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-sensitive-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "explicit-private-value.har");
|
||||
if (mode !== "missing-capture")
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => ({
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"-e",
|
||||
mode === "failed-command"
|
||||
? 'process.stderr.write("explicit-private-value ordinary diagnostic"); process.exit(2)'
|
||||
: "process.exit(0)",
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["explicit-private-value", "REDACTED"],
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Failure required");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
const serialized = JSON.stringify(projected);
|
||||
expect(serialized).not.toContain("explicit-private-value");
|
||||
expect(serialized).not.toContain("REDACTED");
|
||||
expect(result.error._tag).toBe(
|
||||
mode === "missing-capture"
|
||||
? "AnalysisInputError"
|
||||
: mode === "missing-reply"
|
||||
? "AnalysisOutputError"
|
||||
: "ProviderAdapterError",
|
||||
);
|
||||
if (mode === "missing-capture") expect(serialized).toContain("ENOENT");
|
||||
if (mode === "failed-command")
|
||||
expect(serialized).toContain('"exit_code":2');
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an absent owned reply as output failure and removes its private snapshot root", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-decoder-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
let privatePath: string | undefined;
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
privatePath = runtimePath;
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Owned reply is required");
|
||||
expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
expect(result.error.message).toContain("ENOENT");
|
||||
if (privatePath === undefined)
|
||||
throw new Error("Private root was not acquired");
|
||||
await expect(access(privatePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("cancels after snapshot acquisition before launch and removes private input declarations", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-cancel-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
let privatePath: string | undefined;
|
||||
const controller = new AbortController();
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
privatePath = runtimePath;
|
||||
controller.abort();
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(3)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["explicit-private-declaration"],
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Cancelled acquisition must fail");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
if (privatePath === undefined)
|
||||
throw new Error("Private root was not acquired");
|
||||
await expect(access(privatePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ reason: "input-limit", tag: "AnalysisInputError" },
|
||||
{ reason: "resource-limit", tag: "ProviderAdapterError" },
|
||||
{ reason: "decoder", tag: "ProviderAdapterError" },
|
||||
{ reason: "limit", tag: "AnalysisOutputError" },
|
||||
])(
|
||||
"preserves $reason decoder failures through the public error boundary",
|
||||
async ({ reason, tag }) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-reply-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
let privatePath: string | undefined;
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
privatePath = runtimePath;
|
||||
await writeFile(
|
||||
join(runtimePath, "reply.json"),
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
reason,
|
||||
message: "Specific decoder constraint",
|
||||
pointer: "/extension/child",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Failure required");
|
||||
expect(result.error._tag).toBe(tag);
|
||||
const projected = projectAnalysisError(result.error);
|
||||
if (reason === "input-limit") {
|
||||
expect(projected).toMatchObject({
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path", "/extension/child"],
|
||||
reason: "out_of_range",
|
||||
expected: {
|
||||
maximum_capture_nesting: WEB_NETWORK_CAPTURE_LIMITS.depth,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} else if (tag === "ProviderAdapterError") {
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
reason: "Specific decoder constraint",
|
||||
failure_kind: reason,
|
||||
pointer: "/extension/child",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (privatePath === undefined)
|
||||
throw new Error("Private root was not acquired");
|
||||
await expect(access(privatePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"reports a real filesystem permission denial separately from missing capture input",
|
||||
async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-denied-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "unreadable.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()), { mode: 0o000 });
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
throw new Error("Permission-denied input must not launch decoding");
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
}),
|
||||
);
|
||||
await chmod(path, 0o600);
|
||||
if (result.ok) throw new Error("Permission denial required");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "access_denied",
|
||||
category: "unavailable",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation: "inspect_web_network_capture",
|
||||
path,
|
||||
system_code: "EACCES",
|
||||
},
|
||||
});
|
||||
expect(projectAnalysisError(result.error).remediation.action).toContain(
|
||||
"read access",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["format", "process"])(
|
||||
"preserves the structured %s failure when runtime cleanup fails",
|
||||
async (kind) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-cleanup-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "capture-private.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async (_, runtimePath) => {
|
||||
if (kind === "format")
|
||||
await writeFile(
|
||||
join(runtimePath, "reply.json"),
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
reason: "format",
|
||||
message: "Malformed retained record",
|
||||
pointer: "/metadata/capture-private",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"-e",
|
||||
kind === "format"
|
||||
? "process.exit(0)"
|
||||
: 'process.stderr.write("Specific provider fault"); process.exit(3)',
|
||||
],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
async () => {
|
||||
const runtime = await PrivateRuntimeRoot.create({
|
||||
prefix: "rea-cleanup-proof-",
|
||||
});
|
||||
onTestFinished(() => runtime.close());
|
||||
return {
|
||||
path: runtime.path,
|
||||
close: async () => {
|
||||
throw new Error("Deliberate cleanup denial");
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
const result = await decoder.inspect(
|
||||
inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["capture-private"],
|
||||
}),
|
||||
);
|
||||
if (result.ok) throw new Error("Cleanup failure required");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
previous_error:
|
||||
kind === "format"
|
||||
? {
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path", "/metadata"],
|
||||
reason: "invalid_format",
|
||||
message: "Malformed retained record",
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
: {
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
exit_code: 3,
|
||||
stderr: "Specific provider fault",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("capture-private");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,109 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, writeFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
const entrypoint = fileURLToPath(
|
||||
new URL("../../../scripts/rea.mjs", import.meta.url),
|
||||
);
|
||||
const cli = async (
|
||||
path: string,
|
||||
format: string,
|
||||
extra: readonly string[] = [],
|
||||
) => {
|
||||
try {
|
||||
const result = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"inspect-web-network-capture",
|
||||
path,
|
||||
format,
|
||||
"--json",
|
||||
...extra,
|
||||
],
|
||||
{ env: { ...process.env, REA_MITMDUMP_COMMAND: "" }, timeout: 40_000 },
|
||||
);
|
||||
return { ok: true, stdout: result.stdout };
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return { ok: false, stdout: cause.stdout };
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
|
||||
it("reads actual upstream HAR packages in an owned process and retains selected producer order", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
fixture.log.entries.push(structuredClone(first));
|
||||
const text = JSON.stringify(fixture);
|
||||
const path = join(root, "capture.har");
|
||||
await writeFile(path, text);
|
||||
const called = await cli(path, "har", ["--record", "1", "--record", "0"]);
|
||||
expect(called.ok, called.stdout).toBe(true);
|
||||
const result = { value: parseEvidence(JSON.parse(called.stdout)) };
|
||||
expect(result.value.subject?.digest).toMatchObject({
|
||||
sha256: createHash("sha256").update(text).digest("hex"),
|
||||
});
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
total_records: 2,
|
||||
records: [{ ordinal: 1 }, { ordinal: 0 }],
|
||||
runtime_attribution: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps malformed JSON separate from absent external mitmproxy capability", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-errors-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "capture.har");
|
||||
await writeFile(path, "{malformed-private-json");
|
||||
const malformed = await cli(path, "har");
|
||||
expect(malformed.ok).toBe(false);
|
||||
expect(JSON.parse(malformed.stdout)).toMatchObject({
|
||||
category: "invalid_input",
|
||||
});
|
||||
expect(malformed.stdout).not.toContain("malformed-private-json");
|
||||
const missing = await cli(path, "mitmproxy");
|
||||
expect(missing.ok).toBe(false);
|
||||
expect(JSON.parse(missing.stdout)).toMatchObject({
|
||||
category: "unsupported_provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the actual HAR decoder nesting constraint as a typed selected-input issue", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-depth-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
let extension: unknown = "leaf";
|
||||
for (let depth = 0; depth < 66; depth++) extension = { child: extension };
|
||||
const path = join(root, "deep.har");
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({ ...historicalHar(), _extension: extension }),
|
||||
);
|
||||
const result = await cli(path, "har");
|
||||
expect(result.ok).toBe(false);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["capture_path", expect.stringMatching(/^\/_extension\/child/)],
|
||||
reason: "out_of_range",
|
||||
expected: { maximum_capture_nesting: 64 },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -22,16 +22,6 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("web capture diff", () => {
|
||||
it("rejects caller limits that would omit difference records", () => {
|
||||
expect(
|
||||
compareWebCapturesInputSchema.safeParse({
|
||||
before: {},
|
||||
after: {},
|
||||
max_changes: 1,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("reports stable observed changes while preserving unknown dimensions", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
@@ -48,7 +38,22 @@ describe("web capture diff", () => {
|
||||
const after = structuredClone(captured.value);
|
||||
after.scripts.items = [];
|
||||
const request = after.network.requests[0];
|
||||
if (request !== undefined) request.status = 204;
|
||||
if (request !== undefined) {
|
||||
request.status = 204;
|
||||
request.redirects = [
|
||||
{
|
||||
url: `${browser.allowedOrigin}/prior`,
|
||||
response_url: `${browser.allowedOrigin}/prior`,
|
||||
method: "GET",
|
||||
resource_type: "Fetch",
|
||||
status: 302,
|
||||
mime_type: "text/plain",
|
||||
encoded_data_length: 12,
|
||||
request_timestamp: 1,
|
||||
redirect_event_timestamp: 2,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const result = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
@@ -163,6 +168,68 @@ describe("web capture diff", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture redirect comparison", () => {
|
||||
it("ignores redirect event times but compares redirect semantics", 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 beforeRequest = before.network.requests[0];
|
||||
if (beforeRequest === undefined) throw new Error("Missing network request");
|
||||
beforeRequest.redirects = [
|
||||
{
|
||||
url: `${browser.allowedOrigin}/prior`,
|
||||
response_url: `${browser.allowedOrigin}/prior`,
|
||||
method: "GET",
|
||||
resource_type: "Fetch",
|
||||
status: 302,
|
||||
mime_type: "text/plain",
|
||||
encoded_data_length: 12,
|
||||
request_timestamp: 1,
|
||||
redirect_event_timestamp: 2,
|
||||
},
|
||||
];
|
||||
markSectionsComplete(before, ["network_requests"]);
|
||||
|
||||
const after = structuredClone(before);
|
||||
const afterRequest = after.network.requests[0];
|
||||
if (afterRequest === undefined) throw new Error("Missing network request");
|
||||
const hop = afterRequest.redirects?.[0];
|
||||
if (hop === undefined) throw new Error("Missing redirect hop");
|
||||
hop.request_timestamp = 10;
|
||||
hop.redirect_event_timestamp = 20;
|
||||
|
||||
const compare = (inspection: typeof before) =>
|
||||
compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: before },
|
||||
after: { inspection },
|
||||
}),
|
||||
).dimensions.network;
|
||||
expect(compare(after)).toMatchObject({
|
||||
status: "unchanged",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const changed = structuredClone(after);
|
||||
const changedHop = changed.network.requests[0]?.redirects?.[0];
|
||||
if (changedHop === undefined) throw new Error("Missing redirect hop");
|
||||
changedHop.status = 307;
|
||||
expect(compare(changed)).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture diff incomplete inventories", () => {
|
||||
it.each(["truncated_sections", "unavailable_sections"] as const)(
|
||||
"does not infer script additions or removals from %s",
|
||||
|
||||
@@ -108,6 +108,57 @@ describe("browser CLI parity", () => {
|
||||
alignment: { status: "aligned", aligned_steps: 2 },
|
||||
},
|
||||
});
|
||||
const intentionalPolicy = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify(scenarioCapture),
|
||||
JSON.stringify(scenarioCapture),
|
||||
"--normalization-json",
|
||||
JSON.stringify({
|
||||
rules: [
|
||||
{
|
||||
rule_id: "domain",
|
||||
artifacts: ["url"],
|
||||
match: "app.example.test",
|
||||
replacement: "normalized.test",
|
||||
},
|
||||
],
|
||||
}),
|
||||
"--json",
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
expect(intentionalPolicy).toMatchObject({
|
||||
normalized_result: {
|
||||
normalization: { rules: [{ rule_id: "domain" }] },
|
||||
},
|
||||
});
|
||||
|
||||
const malformedPolicy = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify(scenarioCapture),
|
||||
JSON.stringify(scenarioCapture),
|
||||
"--normalization-json",
|
||||
"{invalid-policy",
|
||||
"--json",
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
expect(malformedPolicy).toMatchObject({
|
||||
error: "Browser observation failed",
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: [
|
||||
{
|
||||
path: ["normalization"],
|
||||
reason: "invalid_format",
|
||||
expected: "JSON",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
it("reports missing JSON shapes only when body shapes are selected", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
malformedRedirectResponse: true,
|
||||
redirectResponseEnvelope: null,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const commonArgs = [
|
||||
"inspect-web-page",
|
||||
browser.endpoint,
|
||||
"allowed-page",
|
||||
"--allowed-origins",
|
||||
browser.allowedOrigin,
|
||||
"--observation-ms",
|
||||
"0",
|
||||
];
|
||||
const selected = normalizedResult(
|
||||
await runCli([...commonArgs, "--include-json-body-shapes", "--json"]),
|
||||
);
|
||||
expect(selected).toMatchObject({
|
||||
network: {
|
||||
requests: [
|
||||
{
|
||||
body_shapes: {
|
||||
status: "partial",
|
||||
request: expect.any(Object),
|
||||
response: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
completeness: {
|
||||
unavailable_sections: expect.arrayContaining([
|
||||
"network_requests",
|
||||
"json_body_shapes",
|
||||
]),
|
||||
excluded: expect.arrayContaining([
|
||||
{
|
||||
section: "json_body_shapes",
|
||||
reason: "invalid_protocol_value",
|
||||
count: expect.any(Number),
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
|
||||
const defaulted = normalizedResult(await runCli([...commonArgs, "--json"]));
|
||||
expect(defaulted).toMatchObject({
|
||||
network: {
|
||||
requests: [
|
||||
{
|
||||
body_shapes: {
|
||||
status: "not_approved",
|
||||
request: null,
|
||||
response: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(defaulted.completeness).toMatchObject({
|
||||
unavailable_sections: expect.not.arrayContaining(["json_body_shapes"]),
|
||||
});
|
||||
});
|
||||
|
||||
const runCli = async (arguments_: readonly string[]): Promise<unknown> => {
|
||||
try {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
maxBuffer: 16 * 1_024 * 1_024,
|
||||
},
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return JSON.parse(cause.stdout);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const normalizedResult = (value: unknown): Record<string, unknown> => {
|
||||
if (!isRecord(value) || !isRecord(value.normalized_result))
|
||||
throw new TypeError("Missing CLI normalized result");
|
||||
return value.normalized_result;
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -57,7 +57,9 @@ describe("CLI output argument and sanitization boundary", () => {
|
||||
validateCliOutputArguments(["providers", "--token-count", "--json"]),
|
||||
).toEqual({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("CLI output valued-flag parsing", () => {
|
||||
workspaceCliTest(
|
||||
"preserves complete JSON errors when native builtin flags follow unusual arguments",
|
||||
async ({ cli }) => {
|
||||
@@ -92,6 +94,70 @@ describe("CLI output argument and sanitization boundary", () => {
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
workspaceCliTest(
|
||||
"does not treat empty or equals-style output values as active builtins",
|
||||
async ({ cli }) => {
|
||||
for (const arguments_ of [
|
||||
["capabilities", "--json", "--format", ""],
|
||||
["capabilities", "--json", "--filter-output", ""],
|
||||
["capabilities", "--json", "--token-limit", ""],
|
||||
["capabilities", "--json", "--token-limit=5"],
|
||||
]) {
|
||||
const result = await cli.run({ arguments: arguments_ });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toBeDefined();
|
||||
expect(result.stdout).not.toContain("[truncated:");
|
||||
expect(JSON.stringify(result.json)).not.toContain(
|
||||
"UNSUPPORTED_OUTPUT_COMBINATION",
|
||||
);
|
||||
}
|
||||
const validTokenWindow = await cli.run({
|
||||
arguments: ["capabilities", "--json", "--token-limit", "5"],
|
||||
});
|
||||
expect(validTokenWindow.exitCode).toBe(1);
|
||||
expect(validTokenWindow.json).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
|
||||
});
|
||||
const emptyFormatWithTokenWindow = await cli.run({
|
||||
arguments: [
|
||||
"capabilities",
|
||||
"--json",
|
||||
"--format",
|
||||
"",
|
||||
"--token-limit",
|
||||
"5",
|
||||
],
|
||||
});
|
||||
expect(emptyFormatWithTokenWindow.exitCode).toBe(1);
|
||||
expect(emptyFormatWithTokenWindow.stdout).not.toContain("[truncated:");
|
||||
expect(emptyFormatWithTokenWindow.json).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
|
||||
});
|
||||
|
||||
for (const arguments_ of [
|
||||
["capabilities", "--json", "--token-limit", "not-a-number"],
|
||||
[
|
||||
"capabilities",
|
||||
"--format",
|
||||
"unsupported-format",
|
||||
"--json",
|
||||
"--token-limit",
|
||||
"5",
|
||||
],
|
||||
]) {
|
||||
const result = await cli.run({ arguments: arguments_ });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).not.toContain("UNSUPPORTED_OUTPUT_COMBINATION");
|
||||
expect(result.stdout).not.toContain("[truncated:");
|
||||
}
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
describe("CLI output argument and sanitization boundary", () => {
|
||||
it("preserves normal output and sanitizes text and JSON validation errors", () => {
|
||||
expect(sanitizeCliOutput("result: ok\n")).toBe("result: ok\n");
|
||||
expect(sanitizeCliOutput("result: VALIDATION_ERROR\n")).toBe(
|
||||
@@ -179,7 +245,7 @@ describe("compiled CLI output boundary", () => {
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 0,
|
||||
stdout: "{}\n",
|
||||
stderr: "",
|
||||
stderr: expect.stringContaining('"rea_progress":'),
|
||||
json: {},
|
||||
});
|
||||
const nested = await cli.run({
|
||||
@@ -194,7 +260,7 @@ describe("compiled CLI output boundary", () => {
|
||||
});
|
||||
expect(nested).toMatchObject({
|
||||
exitCode: 0,
|
||||
stderr: "",
|
||||
stderr: expect.stringContaining('"rea_progress":'),
|
||||
json: { normalized_result: {} },
|
||||
});
|
||||
const selected = await cli.run({
|
||||
@@ -209,7 +275,7 @@ describe("compiled CLI output boundary", () => {
|
||||
});
|
||||
expect(selected).toMatchObject({
|
||||
exitCode: 0,
|
||||
stderr: "",
|
||||
stderr: expect.stringContaining('"rea_progress":'),
|
||||
json: {
|
||||
normalized_result: {
|
||||
summary: expect.objectContaining({ browser_windows: 0 }),
|
||||
|
||||
@@ -11,6 +11,7 @@ describe("executable dispatcher", () => {
|
||||
async ({ processes, workspace }) => {
|
||||
const scripts = await workspace.mkdir("scripts");
|
||||
await workspace.mkdir("dist");
|
||||
await workspace.mkdir("dist/cli");
|
||||
await Promise.all([
|
||||
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
|
||||
workspace.write(
|
||||
@@ -29,6 +30,10 @@ describe("executable dispatcher", () => {
|
||||
"dist/cliOutput.js",
|
||||
"export const sanitizeCliOutput = (output) => output; export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli/streamedJsonOutput.js",
|
||||
"export const createStreamedCliJsonOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/mcpDoctor.js",
|
||||
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Filter } from "incur";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const filter = "evidence_id,normalized_result.graph.nodes[0:1].node_id";
|
||||
|
||||
for (const command of ["analyze-javascript-application", "analyze"]) {
|
||||
for (const format of ["json", "jsonl"]) {
|
||||
for (const fullOutput of [false, true]) {
|
||||
for (const filtered of [false, true]) {
|
||||
cliTest(
|
||||
`${command} preserves ${format}, full output ${String(fullOutput)}, filtering ${String(filtered)}`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-json-output-");
|
||||
await writeFile(join(root, "main.js"), "fetch('');\n");
|
||||
const direct = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
});
|
||||
if (!direct.ok) throw direct.error;
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
command,
|
||||
root,
|
||||
"--format",
|
||||
format,
|
||||
...(fullOutput ? ["--full-output"] : []),
|
||||
...(filtered ? ["--filter-output", filter] : []),
|
||||
],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
let data: unknown = output.json;
|
||||
if (fullOutput) {
|
||||
const envelope = z
|
||||
.object({
|
||||
ok: z.literal(true),
|
||||
data: z.unknown(),
|
||||
meta: z.object({
|
||||
command: z.literal(command),
|
||||
duration: z.string().regex(/^\d+ms$/u),
|
||||
}),
|
||||
})
|
||||
.parse(output.json);
|
||||
data = envelope.data;
|
||||
}
|
||||
expect(data).toEqual(
|
||||
filtered
|
||||
? Filter.apply(direct.value, Filter.parse(filter))
|
||||
: direct.value,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"preserves a complete empty filtered JSON document",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-json-empty-filter-");
|
||||
await writeFile(join(root, "main.js"), "export const value = 1;\n");
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--json",
|
||||
"--filter-output",
|
||||
"absent.field",
|
||||
],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
expect(output.json).toEqual({});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves a typed failed analysis in the JSON result",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-json-failure-");
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
join(root, "absent"),
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(output.json).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
details: { reason: "io" },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves JSON omission for inherited filter methods",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-json-inherited-filter-");
|
||||
await writeFile(join(root, "main.js"), "export const value = 1;\n");
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--json",
|
||||
"--filter-output",
|
||||
"toString",
|
||||
],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
expect(output.json).toEqual({});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,72 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const progressLine = z.object({
|
||||
rea_progress: z.object({
|
||||
phase: z.string(),
|
||||
completed: z.number(),
|
||||
total: z.number().nullable(),
|
||||
message: z.string(),
|
||||
sequence: z.number(),
|
||||
terminal: z.boolean().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
for (const command of ["analyze-javascript-application", "analyze"]) {
|
||||
cliTest(
|
||||
`${command} reports real analysis phases on stderr and preserves stdout Evidence`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-cli-progress-");
|
||||
await writeFile(join(root, "main.js"), "fetch('');\n");
|
||||
const direct = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!direct.ok) throw direct.error;
|
||||
|
||||
const output = await cli.run({ arguments: [command, root, "--json"] });
|
||||
expect(output.exitCode).toBe(0);
|
||||
expect(parseEvidence(output.json).evidence_id).toBe(
|
||||
direct.value.evidence_id,
|
||||
);
|
||||
const updates = output.stderr
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => progressLine.parse(JSON.parse(line)).rea_progress);
|
||||
expect(updates[0]?.completed).toBe(0);
|
||||
expect(
|
||||
updates.some(({ phase }) => phase === "parse_javascript_sources"),
|
||||
).toBe(true);
|
||||
expect(updates.at(-1)).toMatchObject({ completed: 1, terminal: true });
|
||||
expect(
|
||||
updates.slice(0, -1).every(({ terminal }) => terminal !== true),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"keeps a failed analysis distinct from a completed result",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-cli-progress-failure-");
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
join(root, "absent"),
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(output.json).toMatchObject({ code: "artifact_operation_failed" });
|
||||
const updates = output.stderr
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => progressLine.parse(JSON.parse(line)).rea_progress);
|
||||
expect(updates[0]?.completed).toBe(0);
|
||||
expect(updates.every(({ terminal }) => terminal !== true)).toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -1,9 +1,8 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
@@ -30,46 +29,63 @@ const JSON_COMMANDS = [
|
||||
|
||||
describe("compiled CLI JSON input failure status", () => {
|
||||
for (const [command, operation] of JSON_COMMANDS)
|
||||
for (const kind of ["inline", "file", "missing"] as const)
|
||||
cliTest(
|
||||
`${command} rejects malformed or unreadable ${kind} input before dispatch`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-status-");
|
||||
const input = kind === "inline" ? "{" : join(root, "input.json");
|
||||
if (kind === "file") await writeFile(input, "{");
|
||||
const parsed = await parseCliJsonInput(input, operation);
|
||||
if (parsed.ok)
|
||||
throw new Error("Expected JSON input to fail before dispatch");
|
||||
cliTest(
|
||||
`${command} rejects malformed inline input before dispatch`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-status-");
|
||||
const input = "{";
|
||||
const result = await cli.run({
|
||||
arguments: [command, input, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: [command, input, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: { operation },
|
||||
});
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.stdout).toBe(
|
||||
`${JSON.stringify(parsed.error, null, 2)}\n`,
|
||||
);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
...(kind === "missing" ? {} : { details: { operation } }),
|
||||
...(kind === "inline"
|
||||
? {}
|
||||
: {
|
||||
input_path: input,
|
||||
input_reason:
|
||||
kind === "file" ? "invalid-json" : "read-failed",
|
||||
}),
|
||||
});
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
for (const kind of ["file", "missing"] as const)
|
||||
cliTest(
|
||||
`preserves ${kind} JSON input diagnostics through a real command`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-status-");
|
||||
const input = join(root, "input.json");
|
||||
if (kind === "file") await writeFile(input, "{");
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["compare-javascript-export-shapes", input, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
input_path: input,
|
||||
input_reason: kind === "file" ? "invalid-json" : "read-failed",
|
||||
...(kind === "file"
|
||||
? { details: { operation: "compare-javascript-export-shapes" } }
|
||||
: {}),
|
||||
});
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("compiled CLI JSON input diagnostic preservation", () => {
|
||||
for (const [format, flags] of [
|
||||
["JSON", ["--json"]],
|
||||
["JSONL", ["--format", "jsonl"]],
|
||||
@@ -113,7 +129,7 @@ describe("compiled CLI JSON input failure status", () => {
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(result.json).toMatchObject({
|
||||
expect(JSON.parse(result.stdout.trim())).toMatchObject({
|
||||
code: "invalid_request",
|
||||
input_path: "",
|
||||
input_reason: "read-failed",
|
||||
@@ -121,6 +137,125 @@ describe("compiled CLI JSON input failure status", () => {
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"classifies an overlong malformed inline value before dispatch",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-overlong-");
|
||||
const input = `[${"x".repeat(3_000)}`;
|
||||
const result = await cli.run({
|
||||
arguments: ["compare-javascript-export-shapes", input, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
operation: "compare-javascript-export-shapes",
|
||||
issues: [{ path: [], reason: "invalid_format", expected: "JSON" }],
|
||||
},
|
||||
});
|
||||
expect(result.json).not.toHaveProperty("input_path");
|
||||
expect(result.stdout).not.toContain("read-failed");
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves explicit overlong JSON path diagnostics",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-overlong-path-");
|
||||
const input = `[${"x".repeat(3_000)}.json`;
|
||||
const result = await cli.run({
|
||||
arguments: ["compare-javascript-export-shapes", input, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
input_path: input,
|
||||
input_reason: "read-failed",
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("compiled CLI JSON path ambiguity", () => {
|
||||
cliTest(
|
||||
"classifies malformed inline JSON when a path prefix is a regular file",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-not-dir-");
|
||||
await writeFile(join(root, "[prefix"), "regular file");
|
||||
const input = "[prefix/rest";
|
||||
const result = await cli.run({
|
||||
arguments: ["capture-browser-scenario", input, "--json"],
|
||||
cwd: root,
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
operation: "capture_browser_scenario",
|
||||
issues: [{ path: [], reason: "invalid_format", expected: "JSON" }],
|
||||
},
|
||||
});
|
||||
expect(result.json).not.toHaveProperty("input_path");
|
||||
expect(result.stdout).not.toContain("read-failed");
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(process.platform !== "win32" && process.getuid?.() !== 0)(
|
||||
"preserves permission errors for malformed path-like JSON input",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-denied-");
|
||||
const denied = join(root, "[locked");
|
||||
const input = "[locked/rest";
|
||||
await mkdir(denied);
|
||||
await chmod(denied, 0);
|
||||
try {
|
||||
await expect(readFile(join(root, input))).rejects.toMatchObject({
|
||||
code: "EACCES",
|
||||
});
|
||||
const result = await cli.run({
|
||||
arguments: ["capture-browser-scenario", input, "--json"],
|
||||
cwd: root,
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
input_path: input,
|
||||
input_reason: "read-failed",
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
} finally {
|
||||
await chmod(denied, 0o700);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("compiled JSON parser and logger success seam", () => {
|
||||
@@ -159,3 +294,78 @@ describe("compiled JSON parser and logger success seam", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("compiled CLI parser with relative brace and bracket paths", () => {
|
||||
for (const filename of ["[input].json", "{capture}.json"])
|
||||
cliTest(
|
||||
`reads the selected relative file ${filename}`,
|
||||
async ({ processes }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-path-");
|
||||
const value = { selected: filename };
|
||||
await writeFile(join(root, filename), JSON.stringify(value));
|
||||
const moduleUrl = new URL(
|
||||
"../../../dist/cliJsonInput.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
const result = await processes.run(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`import { parseCliJsonInput } from ${JSON.stringify(moduleUrl)};
|
||||
console.log(JSON.stringify(await parseCliJsonInput(process.argv[1], "test-input")));`,
|
||||
filename,
|
||||
],
|
||||
{
|
||||
cwd: root,
|
||||
env: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.stdout).toBe(`${JSON.stringify({ ok: true, value })}\n`);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
for (const filename of ["[missing].json", "{missing}.json"])
|
||||
cliTest(
|
||||
`keeps missing relative path diagnostics for ${filename}`,
|
||||
async ({ processes }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-json-missing-");
|
||||
const moduleUrl = new URL(
|
||||
"../../../dist/cliJsonInput.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
const result = await processes.run(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`import { parseCliJsonInput } from ${JSON.stringify(moduleUrl)};
|
||||
console.log(JSON.stringify(await parseCliJsonInput(process.argv[1], "test-input")));`,
|
||||
filename,
|
||||
],
|
||||
{
|
||||
cwd: root,
|
||||
env: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(JSON.parse(result.stdout.trim())).toMatchObject({
|
||||
ok: false,
|
||||
error: { input_path: filename, input_reason: "read-failed" },
|
||||
});
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.exitCode).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { Writable } from "node:stream";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { writeJsonOutput } from "../../../src/cli/jsonOutput.js";
|
||||
import { createStreamedCliJsonOutput } from "../../../src/cli/streamedJsonOutput.js";
|
||||
|
||||
const collect = async (
|
||||
value: unknown,
|
||||
format: "json" | "jsonl" = "json",
|
||||
): Promise<string> => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: unknown, _encoding, callback) {
|
||||
if (!Buffer.isBuffer(chunk)) {
|
||||
callback(new TypeError("Expected a UTF-8 output buffer"));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
await writeJsonOutput(value, destination, format);
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
};
|
||||
|
||||
describe("incremental CLI JSON", () => {
|
||||
it.each([
|
||||
null,
|
||||
true,
|
||||
-0,
|
||||
1e-7,
|
||||
"",
|
||||
{ empty: [], object: {}, nested: [{ value: null }] },
|
||||
{ 'quoted"key': '\u0000\b\t\n\f\r\\"', unicode: "雪𝟠\ud800\udfff" },
|
||||
{ text: `${"x".repeat(8191)}𝟠${"y".repeat(8191)}\ud800` },
|
||||
])("matches native JSON encoding for %j", async (value) => {
|
||||
expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`);
|
||||
});
|
||||
|
||||
it("preserves shared objects without interpreting them as cycles", async () => {
|
||||
const shared = { value: "shared" };
|
||||
const value = { copies: [shared, shared] };
|
||||
expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`);
|
||||
});
|
||||
|
||||
it("writes compact JSONL records and preserves an empty record set", async () => {
|
||||
const value = [{ text: "first\nrecord" }, { text: "雪𝟠" }];
|
||||
expect(await collect(value, "jsonl")).toBe(
|
||||
`${value.map((item) => JSON.stringify(item)).join("\n")}\n`,
|
||||
);
|
||||
expect(await collect([], "jsonl")).toBe("");
|
||||
});
|
||||
|
||||
it("bounds escaped leaf writes and waits for a slow destination", async () => {
|
||||
const leaf = `\u0000雪𝟠`.repeat(32 * 1024);
|
||||
const chunks: Buffer[] = [];
|
||||
let largestChunk = 0;
|
||||
const destination = new Writable({
|
||||
highWaterMark: 1,
|
||||
write(chunk: unknown, _encoding, callback) {
|
||||
if (!Buffer.isBuffer(chunk)) {
|
||||
callback(new TypeError("Expected UTF-8 bytes"));
|
||||
return;
|
||||
}
|
||||
largestChunk = Math.max(largestChunk, chunk.length);
|
||||
setTimeout(() => {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
}, 1);
|
||||
},
|
||||
});
|
||||
await writeJsonOutput({ leaf }, destination);
|
||||
expect(largestChunk).toBeLessThan(Buffer.byteLength(leaf));
|
||||
const actual = Buffer.concat(chunks).toString("utf8");
|
||||
const expected = `${JSON.stringify({ leaf }, null, 2)}\n`;
|
||||
expect(actual.length).toBe(expected.length);
|
||||
expect(actual === expected).toBe(true);
|
||||
expect(destination.writableEnded).toBe(false);
|
||||
});
|
||||
|
||||
it("waits for the final write even when it fits the destination buffer", async () => {
|
||||
let completed = false;
|
||||
const destination = new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
setTimeout(() => {
|
||||
completed = true;
|
||||
callback();
|
||||
}, 5);
|
||||
},
|
||||
});
|
||||
await writeJsonOutput({ result: "small" }, destination);
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"propagates a failed destination (deferred: %s)",
|
||||
async (deferred) => {
|
||||
const cause = new Error("Fixture destination failed");
|
||||
const destination = new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
if (deferred) setTimeout(() => callback(cause), 5);
|
||||
else callback(cause);
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
writeJsonOutput({ result: "small" }, destination),
|
||||
).rejects.toBe(cause);
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves a reusable destination open without adding error listeners", async () => {
|
||||
const destination = new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const listeners = destination.listenerCount("error");
|
||||
await writeJsonOutput({ result: "first" }, destination);
|
||||
await writeJsonOutput({ result: "second" }, destination);
|
||||
expect(destination.listenerCount("error")).toBe(listeners);
|
||||
expect(destination.writableEnded).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a cycle at the serialization boundary", async () => {
|
||||
const cycle: Record<string, unknown> = {};
|
||||
cycle.self = cycle;
|
||||
await expect(collect(cycle)).rejects.toThrow("circular reference");
|
||||
});
|
||||
|
||||
it.each([undefined, Number.NaN, Number.POSITIVE_INFINITY, 1n, new Date(0)])(
|
||||
"rejects non-JSON input %s",
|
||||
async (value) => {
|
||||
await expect(collect(value)).rejects.toThrow("ordinary JSON");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("streamed CLI result surface", () => {
|
||||
it.each([
|
||||
[],
|
||||
["--format", "md"],
|
||||
["--json", "--token-count"],
|
||||
["--json", "--token-limit", "5"],
|
||||
["--json", "--format", "invalid"],
|
||||
])("delegates unsupported output controls %j", (...arguments_) => {
|
||||
expect(createStreamedCliJsonOutput(arguments_, new Writable())).toBe(
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps ownership after a failed write so no second document is emitted", async () => {
|
||||
const cause = new Error("Fixture destination failed");
|
||||
const destination = new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
callback(cause);
|
||||
},
|
||||
});
|
||||
const output = createStreamedCliJsonOutput(["--json"], destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
await expect(
|
||||
output.write(
|
||||
{ result: "small" },
|
||||
{ command: "fixture", duration: "1ms", format: "json" },
|
||||
),
|
||||
).rejects.toBe(cause);
|
||||
expect(output.handled).toBe(true);
|
||||
expect(output.failed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import type { TestCli } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const runCapture = async (cli: TestCli, steps: string | undefined) => {
|
||||
const arguments_ = [
|
||||
"capture-native-ui-scenario",
|
||||
"/provider-must-not-be-invoked",
|
||||
"--pid",
|
||||
"1",
|
||||
"--window-id",
|
||||
"1",
|
||||
];
|
||||
if (steps !== undefined) arguments_.push("--steps", steps);
|
||||
arguments_.push("--json");
|
||||
return cli.run({
|
||||
arguments: arguments_,
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
};
|
||||
|
||||
describe("native UI scenario CLI input", () => {
|
||||
cliTest(
|
||||
"rejects omitted steps under the shared scenario contract",
|
||||
async ({ cli }) => {
|
||||
const result = await runCapture(cli, undefined);
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_native_ui_scenario",
|
||||
issues: [{ path: ["steps"], reason: "missing_argument" }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest("rejects malformed JSON as invalid input", async ({ cli }) => {
|
||||
const result = await runCapture(cli, "[");
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_native_ui_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["steps"],
|
||||
reason: "invalid_format",
|
||||
expected: "JSON",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"requires at least one schema-valid scenario step",
|
||||
async ({ cli }) => {
|
||||
const result = await runCapture(cli, "[]");
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_native_ui_scenario",
|
||||
issues: [{ path: ["steps"], reason: "out_of_range", minimum: 1 }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -13,9 +13,9 @@ import {
|
||||
captureProcessScenarioFile,
|
||||
compareProcessEvidenceFiles,
|
||||
projectProcessCliError,
|
||||
} from "../../../src/application/ProcessCli.js";
|
||||
} from "../../../src/application/process/ProcessCli.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -120,8 +120,17 @@ describe("process CLI errors", () => {
|
||||
const root = await fixture();
|
||||
const malformed = join(root, "malformed.json");
|
||||
const invalid = join(root, "invalid.json");
|
||||
const invalidUtf8 = join(root, "invalid-utf8.json");
|
||||
await writeFile(malformed, "not-json");
|
||||
await writeFile(invalid, "{}");
|
||||
await writeFile(
|
||||
invalidUtf8,
|
||||
Buffer.concat([
|
||||
Buffer.from('{"executable":"'),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(
|
||||
await captureProcessScenarioFile(join(root, "missing.json")),
|
||||
@@ -137,6 +146,12 @@ describe("process CLI errors", () => {
|
||||
message:
|
||||
"Process input file is not valid JSON. Repair the file, then try again.",
|
||||
});
|
||||
expect(await captureProcessScenarioFile(invalidUtf8)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Process input file is not valid JSON. Repair the file, then try again.",
|
||||
});
|
||||
expect(await captureProcessScenarioFile(invalid)).toEqual({
|
||||
error: "Process command failed",
|
||||
code: "invalid_request",
|
||||
@@ -153,6 +168,66 @@ describe("process CLI errors", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects NUL arguments before process launch", async () => {
|
||||
const root = await fixture();
|
||||
const scenario = join(root, "nul-argument.json");
|
||||
await writeFile(
|
||||
scenario,
|
||||
JSON.stringify({ executable: process.execPath, arguments: ["\0"] }),
|
||||
);
|
||||
|
||||
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
|
||||
error: "Process command failed",
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["arguments", 0],
|
||||
reason: "invalid_format",
|
||||
expected: "regex",
|
||||
message:
|
||||
"Values passed to operating-system APIs cannot contain NUL",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("process CLI environment key diagnostics", () => {
|
||||
it("reports the reserved process environment key constraint", async () => {
|
||||
const root = await fixture();
|
||||
const scenario = join(root, "reserved-environment.json");
|
||||
await writeFile(
|
||||
scenario,
|
||||
JSON.stringify({
|
||||
executable: process.execPath,
|
||||
environment: { REA_PROCESS_RUN_ID: "caller-value" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
|
||||
error: "Process command failed",
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["environment", "REA_PROCESS_RUN_ID"],
|
||||
reason: "invalid_format",
|
||||
expected: "regex",
|
||||
message: "REA_PROCESS_RUN_ID is reserved by the process adapter",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("process CLI evidence validation", () => {
|
||||
it("captures the minimal executable-and-arguments scenario", async () => {
|
||||
const root = await fixture();
|
||||
const scenario = join(root, "scenario.json");
|
||||
|
||||
@@ -19,6 +19,10 @@ import {
|
||||
MANAGED_WORKFLOW_PROVIDER,
|
||||
} from "../../../src/application/InvestigationProviders.js";
|
||||
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
MITMPROXY_CAPTURE_PROVIDER_IDENTITY,
|
||||
} from "../../../src/browser/history/CaptureRelease.js";
|
||||
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightElectronActiveProvider.js";
|
||||
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
|
||||
@@ -106,6 +110,8 @@ describe("canonical product catalog", () => {
|
||||
BINWALK_PROVIDER_IDENTITY,
|
||||
UNBLOB_PROVIDER_IDENTITY,
|
||||
WAKARU_PROVIDER_IDENTITY,
|
||||
HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
MITMPROXY_CAPTURE_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
IDA_PROVIDER_IDENTITY,
|
||||
NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
@@ -286,6 +292,8 @@ describe("canonical product catalog drift", () => {
|
||||
true,
|
||||
);
|
||||
expect(issues.some((issue) => issue.includes("Future Client"))).toBe(true);
|
||||
expect(issues).toContain("docs/installation.md: missing Future Client");
|
||||
expect(issues).not.toContain("README.md: missing Future Client");
|
||||
});
|
||||
|
||||
it("changes the provider projection digest when provider facts drift", async () => {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
describe("scenario CLI schema diagnostics", () => {
|
||||
cliTest("reports browser scenario schema paths", async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["capture-browser-scenario", "{}", "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_browser_scenario",
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
path: ["browser"],
|
||||
reason: "missing_argument",
|
||||
expected: "object",
|
||||
},
|
||||
{
|
||||
path: ["start_url"],
|
||||
reason: "missing_argument",
|
||||
expected: "object",
|
||||
},
|
||||
{
|
||||
path: ["actions"],
|
||||
reason: "missing_argument",
|
||||
expected: "array",
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
cliTest("reports Electron scenario schema paths", async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["capture-electron-scenario", "{}", "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_electron_scenario",
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
path: ["executable_path"],
|
||||
reason: "missing_argument",
|
||||
expected: "string",
|
||||
},
|
||||
{
|
||||
path: ["application_path"],
|
||||
reason: "missing_argument",
|
||||
expected: "string",
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { compareArtifacts } from "../../../src/domain/artifactComparison.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
@@ -31,10 +31,7 @@ const observe = async (path: string) => {
|
||||
describe("artifact comparison summary", () => {
|
||||
it.each([
|
||||
{ removed: 1, added: 1 },
|
||||
{ removed: 1, added: 2 },
|
||||
{ removed: 2, added: 1 },
|
||||
{ removed: 0, added: 1 },
|
||||
{ removed: 1, added: 0 },
|
||||
{ removed: 0, added: 0 },
|
||||
])(
|
||||
"counts unchanged paths with $removed removals and $added additions",
|
||||
@@ -74,15 +71,6 @@ describe("artifact comparison summary", () => {
|
||||
contradiction: 0,
|
||||
});
|
||||
expect(comparison.changes).toHaveLength(removed + added + changed);
|
||||
expect(comparison.summary.unchanged + comparison.changes.length).toBe(
|
||||
3 + removed + added,
|
||||
);
|
||||
expect(
|
||||
comparison.changes.map(({ logical_path }) => logical_path),
|
||||
).not.toContain("same.txt");
|
||||
expect(
|
||||
comparison.changes.map(({ logical_path }) => logical_path),
|
||||
).not.toContain("duplicate.txt");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { canonicalDigest } from "../../../src/domain/comparisonSemantics.js";
|
||||
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { compareArtifacts } from "../../../src/domain/artifactComparison.js";
|
||||
import type { ArtifactInventoryResult } from "../../../src/domain/artifactGraph.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import {
|
||||
artifactOccurrenceAt,
|
||||
artifactParentPaths,
|
||||
@@ -14,10 +14,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const permutations = [
|
||||
["pkg/", "pkg/sub/", "pkg/sub/data.txt"],
|
||||
["pkg/", "pkg/sub/data.txt", "pkg/sub/"],
|
||||
["pkg/sub/", "pkg/", "pkg/sub/data.txt"],
|
||||
["pkg/sub/", "pkg/sub/data.txt", "pkg/"],
|
||||
["pkg/sub/data.txt", "pkg/", "pkg/sub/"],
|
||||
["pkg/sub/data.txt", "pkg/sub/", "pkg/"],
|
||||
];
|
||||
const expectedParents = {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
|
||||
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
|
||||
describe("artifact inventory snapshot", () => {
|
||||
it("retains the complete scan after the source directory changes", async () => {
|
||||
|
||||
@@ -3,15 +3,12 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { classifyArtifactContent } from "../../../src/application/ArtifactGraphConstruction.js";
|
||||
import { classifyRoot } from "../../../src/application/ArtifactInventory/classify.js";
|
||||
import { classifyArtifactContent } from "../../../src/artifacts/inventory/ArtifactGraphConstruction.js";
|
||||
import { classifyRoot } from "../../../src/artifacts/inventory/classify.js";
|
||||
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../../../src/artifacts/ArtifactHash.js";
|
||||
import { scanCanonicalArtifactInventory } from "../../../src/application/ArtifactInventory/scanCanonical.js";
|
||||
import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
|
||||
import { targetFormatSchema } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { identifyRuntimes } from "../../../src/domain/runtimeIdentification.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("MZ artifact classification", () => {
|
||||
@@ -62,7 +59,7 @@ describe("MZ artifact classification", () => {
|
||||
expect(targetFormatSchema.parse("dos-mz")).toBe("dos-mz");
|
||||
});
|
||||
|
||||
it("keeps standalone and embedded DOS identities through inventory and runtime evidence", async () => {
|
||||
it("keeps standalone and embedded DOS identities through inventory", async () => {
|
||||
const directory = await createTestTempDirectory("rea-mz-inventory-");
|
||||
const dosPath = join(directory, "LEGACY.EXE");
|
||||
const pePath = join(directory, "NATIVE.EXE");
|
||||
@@ -88,30 +85,6 @@ describe("MZ artifact classification", () => {
|
||||
expect(inventory.nodes.map(({ format }) => format)).toEqual(
|
||||
expect.arrayContaining(["dos-mz", "pe"]),
|
||||
);
|
||||
const evidence = createEvidence(
|
||||
{
|
||||
path: tree,
|
||||
sha256: inventory.manifest.root_sha256,
|
||||
format: "directory",
|
||||
},
|
||||
{ id: "inventory-fixture", name: "Inventory fixture", version: null },
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(inventory),
|
||||
},
|
||||
);
|
||||
const runtimes = identifyRuntimes({ inventory_evidence: [evidence] });
|
||||
expect(runtimes.runtimes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
family: "native",
|
||||
inspection: "provider-selection-required",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "LEGACY.EXE", format: "dos-mz" }),
|
||||
expect.objectContaining({ path: "NATIVE.EXE", format: "pe" }),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { writeOrderedZip } from "../../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
|
||||
it("rejects overlapping ZIP member data ranges through artifact inventory", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-overlap-");
|
||||
const path = join(root, "overlap.zip");
|
||||
await writeOrderedZip(path, ["a.txt", "b.txt"]);
|
||||
const bytes = await readFile(path);
|
||||
const centralDirectorySignature = Buffer.from([0x50, 0x4b, 0x01, 0x02]);
|
||||
const first = bytes.indexOf(centralDirectorySignature);
|
||||
const second = bytes.indexOf(centralDirectorySignature, first + 4);
|
||||
if (first < 0 || second <= first)
|
||||
throw new Error("Expected two ZIP central-directory entries");
|
||||
|
||||
const firstLocalOffset = bytes.readUInt32LE(first + 42);
|
||||
const secondLocalOffset = bytes.readUInt32LE(second + 42);
|
||||
expect(secondLocalOffset).not.toBe(firstLocalOffset);
|
||||
bytes.writeUInt32LE(firstLocalOffset, second + 42);
|
||||
await writeFile(path, bytes);
|
||||
|
||||
const target = await parseBinaryTarget(path);
|
||||
if (!target.ok) throw target.error;
|
||||
const result = await new ArtifactProvider()
|
||||
.createClient(target.value)
|
||||
.execute("inventory_artifact", {});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "io" },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves encrypted-member and corrupt-CRC observations", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-integrity-");
|
||||
const encryptedPath = join(root, "encrypted.zip");
|
||||
const encryptedWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
await encryptedWriter.add("secret.txt", new TextReader("secret bytes"), {
|
||||
password: "fixture-password",
|
||||
});
|
||||
await writeFile(encryptedPath, await encryptedWriter.close());
|
||||
|
||||
const encryptedTarget = await parseBinaryTarget(encryptedPath);
|
||||
if (!encryptedTarget.ok) throw encryptedTarget.error;
|
||||
const encryptedResult = await new ArtifactProvider()
|
||||
.createClient(encryptedTarget.value)
|
||||
.execute("inventory_artifact", {});
|
||||
if (!encryptedResult.ok) throw encryptedResult.error;
|
||||
const encryptedInventory = artifactInventoryResultSchema.parse(
|
||||
encryptedResult.value.result,
|
||||
);
|
||||
expect(encryptedInventory.occurrences).toContainEqual(
|
||||
expect.objectContaining({
|
||||
logical_path: "secret.txt",
|
||||
encrypted: true,
|
||||
hash_status: "unavailable",
|
||||
}),
|
||||
);
|
||||
|
||||
const corruptPath = join(root, "corrupt-crc.zip");
|
||||
const corruptWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
await corruptWriter.add("data.txt", new TextReader("evidence\n"));
|
||||
await writeFile(corruptPath, await corruptWriter.close());
|
||||
const bytes = await readFile(corruptPath);
|
||||
const localFileHeaderSignature = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
|
||||
const localHeader = bytes.indexOf(localFileHeaderSignature);
|
||||
if (localHeader < 0) throw new Error("Expected a ZIP local-file header");
|
||||
const dataOffset =
|
||||
localHeader +
|
||||
30 +
|
||||
bytes.readUInt16LE(localHeader + 26) +
|
||||
bytes.readUInt16LE(localHeader + 28);
|
||||
const firstByte = bytes[dataOffset];
|
||||
if (firstByte === undefined) throw new Error("Expected ZIP member bytes");
|
||||
bytes[dataOffset] = firstByte ^ 1;
|
||||
await writeFile(corruptPath, bytes);
|
||||
|
||||
const corruptTarget = await parseBinaryTarget(corruptPath);
|
||||
if (!corruptTarget.ok) throw corruptTarget.error;
|
||||
const corruptResult = await new ArtifactProvider()
|
||||
.createClient(corruptTarget.value)
|
||||
.execute("inventory_artifact", {});
|
||||
expect(corruptResult).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "io" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a truncated ZIP through artifact inventory", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-malformed-");
|
||||
const path = join(root, "truncated.zip");
|
||||
await writeFile(path, Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||
|
||||
const target = await parseBinaryTarget(path);
|
||||
if (!target.ok) throw target.error;
|
||||
const result = await new ArtifactProvider()
|
||||
.createClient(target.value)
|
||||
.execute("inventory_artifact", {});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "io" },
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import {
|
||||
artifactOccurrenceAt,
|
||||
artifactParentPaths,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { buffer } from "node:stream/consumers";
|
||||
import { createPackage, listPackage, uncache } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { fstatSync, type Stats } from "node:fs";
|
||||
import {
|
||||
open as openFile,
|
||||
lstat,
|
||||
mkdir,
|
||||
rm,
|
||||
readdir,
|
||||
writeFile,
|
||||
truncate,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { buffer } from "node:stream/consumers";
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
|
||||
import {
|
||||
closeAsarHandle,
|
||||
readValidatedAsarEntry,
|
||||
} from "../../../src/artifacts/AsarEntryStream.js";
|
||||
import { hashReadable } from "../../../src/artifacts/ArtifactHash.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const memberBytes = 64 * 1024 * 1024;
|
||||
const expectedSha256 = (): string => {
|
||||
const hash = createHash("sha256");
|
||||
const zeros = Buffer.alloc(64 * 1024);
|
||||
for (let written = 0; written < memberBytes; written += zeros.length)
|
||||
hash.update(zeros);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
const descriptorDirectory =
|
||||
process.platform === "darwin" ? "/dev/fd" : "/proc/self/fd";
|
||||
|
||||
const matchingDescriptorCount = async (identity: Stats): Promise<number> => {
|
||||
const descriptors = await readdir(descriptorDirectory);
|
||||
return descriptors.filter((descriptor) => {
|
||||
if (!/^\d+$/u.test(descriptor)) return false;
|
||||
try {
|
||||
const observed = fstatSync(Number(descriptor));
|
||||
return observed.dev === identity.dev && observed.ino === identity.ino;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}).length;
|
||||
};
|
||||
|
||||
const waitForNoMatchingDescriptor = async (identity: Stats): Promise<void> => {
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
if ((await matchingDescriptorCount(identity)) === 0) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(await matchingDescriptorCount(identity)).toBe(0);
|
||||
};
|
||||
|
||||
describe("ASAR entry streaming", () => {
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes a packed member handle when its unopened output stream is destroyed",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-asar-destroy-before-read-",
|
||||
);
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
|
||||
const identity = await lstat(archive);
|
||||
const probe = await openFile(archive, "r");
|
||||
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
|
||||
await probe.close();
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) {
|
||||
entries.push(entry);
|
||||
}
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined) throw new Error("Expected packed ASAR member");
|
||||
expect(await matchingDescriptorCount(identity)).toBe(0);
|
||||
const output = await reader.open(entry);
|
||||
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
|
||||
const closed = new Promise<void>((resolve) =>
|
||||
output.once("close", resolve),
|
||||
);
|
||||
output.destroy();
|
||||
await closed;
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes a packed member handle when cancellation arrives during open",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-abort-during-stat-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
|
||||
const identity = await lstat(archive);
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined) throw new Error("Expected packed ASAR member");
|
||||
const controller = new AbortController();
|
||||
const opening = reader.open(entry, controller.signal);
|
||||
controller.abort();
|
||||
await expect(opening).rejects.toMatchObject({ reason: "cancelled" });
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("classifies a missing packed member container as an I/O failure", async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-missing-member-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined) throw new Error("Expected packed ASAR member");
|
||||
await rm(archive);
|
||||
await expect(reader.open(entry)).rejects.toMatchObject({
|
||||
reason: "io",
|
||||
cause: { code: "ENOENT" },
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("ASAR entry producer identity", () => {
|
||||
it.each([false, true] as const)(
|
||||
"rejects a copied entry with a changed unpacked flag for unpacked=%s",
|
||||
async (unpacked) => {
|
||||
const root = await createTestTempDirectory("rea-asar-entry-identity-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
|
||||
await createPackageWithOptions(
|
||||
source,
|
||||
archive,
|
||||
unpacked ? { unpack: "small.js" } : {},
|
||||
);
|
||||
const selectedPath = unpacked
|
||||
? join(`${archive}.unpacked`, "small.js")
|
||||
: archive;
|
||||
const identity = await lstat(selectedPath);
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined) throw new Error("Expected ASAR file entry");
|
||||
expect(entry.unpacked).toBe(unpacked);
|
||||
expect(await matchingDescriptorCount(identity)).toBe(0);
|
||||
if (entry.declaredSize === null)
|
||||
throw new Error("Expected ASAR file size metadata");
|
||||
|
||||
for (const changedEntry of [
|
||||
{ ...entry, unpacked: !entry.unpacked },
|
||||
{ ...entry, path: `stale/${entry.path}` },
|
||||
{ ...entry, declaredSize: entry.declaredSize + 1 },
|
||||
])
|
||||
await expect(reader.open(changedEntry)).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "integrity",
|
||||
message: expect.stringContaining(
|
||||
`ASAR entry metadata changed since inventory: ${entry.path}`,
|
||||
),
|
||||
});
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["packed to unpacked", false],
|
||||
["unpacked to packed", true],
|
||||
] as const)(
|
||||
"rejects a retained %s entry after a new entries pass",
|
||||
async (_transition, wasUnpacked) => {
|
||||
const root = await createTestTempDirectory("rea-asar-entry-refresh-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
const memberContents = "module.exports = 1;\n";
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "small.js"), memberContents);
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
|
||||
try {
|
||||
await createPackageWithOptions(
|
||||
source,
|
||||
archive,
|
||||
wasUnpacked ? { unpack: "small.js" } : {},
|
||||
);
|
||||
const firstEntries = [];
|
||||
for await (const entry of reader.entries()) firstEntries.push(entry);
|
||||
const retained = firstEntries.find(({ path }) => path === "small.js");
|
||||
if (retained === undefined)
|
||||
throw new Error("Expected first ASAR file entry");
|
||||
const copiedRetained = {
|
||||
...retained,
|
||||
limitations: [...retained.limitations],
|
||||
};
|
||||
|
||||
await createPackageWithOptions(
|
||||
source,
|
||||
archive,
|
||||
wasUnpacked ? {} : { unpack: "small.js" },
|
||||
);
|
||||
const currentEntries = [];
|
||||
for await (const entry of reader.entries()) currentEntries.push(entry);
|
||||
const current = currentEntries.find(({ path }) => path === "small.js");
|
||||
if (current === undefined)
|
||||
throw new Error("Expected refreshed ASAR file entry");
|
||||
expect(current.unpacked).toBe(!wasUnpacked);
|
||||
|
||||
await expect(reader.open(copiedRetained)).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "integrity",
|
||||
message: expect.stringContaining(
|
||||
"ASAR entry metadata changed since inventory",
|
||||
),
|
||||
});
|
||||
expect((await buffer(await reader.open(current))).toString()).toBe(
|
||||
memberContents,
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("ASAR read failures", () => {
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"checks cancellation after closing an empty member handle",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-empty-close-");
|
||||
const archive = join(root, "container.asar");
|
||||
await writeFile(archive, "container bytes");
|
||||
const identity = await lstat(archive);
|
||||
const handle = await openFile(archive, "r");
|
||||
try {
|
||||
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
|
||||
const controller = new AbortController();
|
||||
|
||||
await expect(
|
||||
closeAsarHandle(async () => {
|
||||
await handle.close();
|
||||
controller.abort();
|
||||
}, controller.signal),
|
||||
).rejects.toMatchObject({ reason: "cancelled" });
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
} finally {
|
||||
await handle.close().catch(() => undefined);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes the opened unpacked file and retains ASAR context when handle stat fails",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-unpacked-stat-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
|
||||
await createPackageWithOptions(source, archive, { unpack: "small.js" });
|
||||
const unpackedPath = join(`${archive}.unpacked`, "small.js");
|
||||
const identity = await lstat(unpackedPath);
|
||||
const ioError = Object.assign(new Error("device stat failed"), {
|
||||
code: "EIO",
|
||||
errno: -5,
|
||||
syscall: "fstat",
|
||||
});
|
||||
let closeCount = 0;
|
||||
const reader = new AsarArtifactReader(archive, async (path, flags) => {
|
||||
const handle = await openFile(path, flags);
|
||||
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
|
||||
let statCount = 0;
|
||||
return {
|
||||
async stat() {
|
||||
statCount += 1;
|
||||
if (statCount === 2) throw ioError;
|
||||
return handle.stat();
|
||||
},
|
||||
async close() {
|
||||
closeCount += 1;
|
||||
await handle.close();
|
||||
},
|
||||
createReadStream: (options) => handle.createReadStream(options),
|
||||
};
|
||||
});
|
||||
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined)
|
||||
throw new Error("Expected unpacked ASAR member");
|
||||
|
||||
await expect(reader.open(entry)).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "io",
|
||||
message: expect.stringContaining(
|
||||
`Could not read ${entry.path} ASAR at ${archive}: device stat failed`,
|
||||
),
|
||||
cause: { code: "EIO", errno: -5, syscall: "fstat" },
|
||||
});
|
||||
expect(closeCount).toBe(1);
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["missing", "replaced"] as const)(
|
||||
"validates the container before returning a zero-length member when it is %s",
|
||||
async (change) => {
|
||||
const root = await createTestTempDirectory("rea-asar-empty-member-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "empty.js"), "");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "empty.js");
|
||||
if (entry === undefined) throw new Error("Expected empty ASAR member");
|
||||
if (change === "missing") await rm(archive);
|
||||
else await writeFile(archive, "replacement container");
|
||||
|
||||
await expect(reader.open(entry)).rejects.toMatchObject(
|
||||
change === "missing"
|
||||
? { reason: "io", cause: { code: "ENOENT" } }
|
||||
: { reason: "integrity" },
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves filesystem errors raised while consuming a member stream", async () => {
|
||||
const ioError = Object.assign(new Error("device read failed"), {
|
||||
code: "EIO",
|
||||
errno: -5,
|
||||
syscall: "read",
|
||||
});
|
||||
const source = Readable.from(
|
||||
(async function* () {
|
||||
yield Buffer.from("partial");
|
||||
throw ioError;
|
||||
})(),
|
||||
);
|
||||
const output = readValidatedAsarEntry(
|
||||
source,
|
||||
undefined,
|
||||
"nested/member.bin",
|
||||
"/tmp/source.asar",
|
||||
);
|
||||
|
||||
await expect(async () => {
|
||||
for await (const _chunk of output) {
|
||||
// Consume through the source failure.
|
||||
}
|
||||
}).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "io",
|
||||
message: expect.stringContaining(
|
||||
"Could not read nested/member.bin ASAR at /tmp/source.asar",
|
||||
),
|
||||
cause: { code: "EIO", errno: -5, syscall: "read" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ASAR entry streaming", () => {
|
||||
it("reports the observed digest when an unpacked member changes size", async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-asar-unpacked-size-change-",
|
||||
);
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
const original = join(source, "small.js");
|
||||
const changed = "changed();\n";
|
||||
await mkdir(source);
|
||||
await writeFile(original, "module.exports = 1;\n");
|
||||
await createPackageWithOptions(source, archive, { unpack: "small.js" });
|
||||
await writeFile(join(`${archive}.unpacked`, "small.js"), changed);
|
||||
|
||||
await expect(scanArtifactInventory(archive)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
details: {
|
||||
logicalPath: "small.js",
|
||||
calculatedSha256: createHash("sha256").update(changed).digest("hex"),
|
||||
unpacked: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["packed", {}],
|
||||
["unpacked", { unpack: "large.bin" }],
|
||||
] as const)(
|
||||
"opens a %s member without allocating its full contents",
|
||||
async (_kind, options) => {
|
||||
const root = await createTestTempDirectory("rea-asar-streaming-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "fixture.asar");
|
||||
const member = join(source, "large.bin");
|
||||
await mkdir(source);
|
||||
await writeFile(member, Buffer.alloc(0));
|
||||
await truncate(member, memberBytes);
|
||||
await createPackageWithOptions(source, archive, options);
|
||||
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "large.bin");
|
||||
if (entry === undefined) throw new Error("Expected large ASAR member");
|
||||
|
||||
const before = process.memoryUsage().arrayBuffers;
|
||||
const stream = await reader.open(entry);
|
||||
const afterOpen = process.memoryUsage().arrayBuffers;
|
||||
const observed = await hashReadable(stream);
|
||||
const allocation = afterOpen - before;
|
||||
|
||||
expect(allocation).toBeLessThan(memberBytes / 2);
|
||||
expect(observed).toMatchObject({
|
||||
sha256: expectedSha256(),
|
||||
bytes: memberBytes,
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
120_000,
|
||||
);
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { scanAuthorizedArtifactInventory } from "../../../src/application/AuthorizedArtifactInventory.js";
|
||||
|
||||
describe("authorized artifact inventory", () => {
|
||||
it("scans a local artifact without configured input roots", async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-roots-");
|
||||
const path = join(root, "artifact.js");
|
||||
await writeFile(path, "export const value = 1;\n");
|
||||
const inventory = await scanAuthorizedArtifactInventory(path);
|
||||
expect(inventory.manifest.root_format).toBe("javascript-bundle");
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { readBoundedFileBytes } from "../../../src/process/BoundedFileBytes.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("bounded file byte reads", () => {
|
||||
it.each([0, 1, 65_536, 65_537])(
|
||||
it.each([0, 65_536])(
|
||||
"accepts a file exactly at the %i byte limit",
|
||||
async (limit) => {
|
||||
const root = await createTestTempDirectory("rea-bounded-bytes-");
|
||||
|
||||
@@ -7,13 +7,18 @@ import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("CLI JSON input", () => {
|
||||
it("preserves JSON scalars and distinguishes malformed inline text from files", async () => {
|
||||
for (const value of [null, false, 0, "text", [], {}])
|
||||
expect(
|
||||
await parseCliJsonInput(JSON.stringify(value), "test-input"),
|
||||
).toEqual({ ok: true, value });
|
||||
expect(await parseCliJsonInput("{", "test-input")).toMatchObject({
|
||||
it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => {
|
||||
expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
details: { issues: [{ reason: "invalid_format", expected: "JSON" }] },
|
||||
},
|
||||
});
|
||||
expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
details: { issues: [{ reason: "invalid_format", expected: "JSON" }] },
|
||||
},
|
||||
});
|
||||
const root = await createTestTempDirectory("rea-json-input-");
|
||||
const path = join(root, "input.json");
|
||||
@@ -22,6 +27,24 @@ describe("CLI JSON input", () => {
|
||||
ok: true,
|
||||
value: { value: 1 },
|
||||
});
|
||||
expect(await parseCliJsonInput("false", "test-input")).toEqual({
|
||||
ok: true,
|
||||
value: false,
|
||||
});
|
||||
const bracketPath = join(root, "[input].json");
|
||||
await writeFile(bracketPath, '["preserved"]');
|
||||
expect(await parseCliJsonInput(bracketPath, "test-input")).toEqual({
|
||||
ok: true,
|
||||
value: ["preserved"],
|
||||
});
|
||||
for (const missingPath of [
|
||||
join(root, "{capture}.json"),
|
||||
join(root, "[missing].json"),
|
||||
])
|
||||
expect(await parseCliJsonInput(missingPath, "test-input")).toMatchObject({
|
||||
ok: false,
|
||||
error: { input_path: missingPath, input_reason: "read-failed" },
|
||||
});
|
||||
expect(await parseCliJsonInput(root, "test-input")).toMatchObject({
|
||||
ok: false,
|
||||
error: { input_reason: "read-failed" },
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe.each([
|
||||
@@ -46,68 +45,55 @@ describe.each([
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFile(client.configPath, original);
|
||||
const currentCommandPath = join(home, "rea");
|
||||
|
||||
for (const command of [
|
||||
["npx", "-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
|
||||
[currentCommandPath, "mcp"],
|
||||
]) {
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "update",
|
||||
backupPath: `${client.configPath}.rea.backup`,
|
||||
});
|
||||
expect(await clientConfigurationAligned(client, {}, command)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual(
|
||||
{
|
||||
status: "configured",
|
||||
backupPath: `${client.configPath}.rea.backup`,
|
||||
},
|
||||
);
|
||||
const updated = await readFile(client.configPath, "utf8");
|
||||
expect(
|
||||
updated.startsWith(`${bom}// Keep the client preferences.\r\n`),
|
||||
).toBe(true);
|
||||
expect(
|
||||
parseClientConfiguration(updated, client.format).document,
|
||||
).toEqual({
|
||||
const command = [currentCommandPath, "mcp"];
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "update",
|
||||
backupPath: `${client.configPath}.rea.backup`,
|
||||
});
|
||||
expect(await clientConfigurationAligned(client, {}, command)).toBe(false);
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "configured",
|
||||
backupPath: `${client.configPath}.rea.backup`,
|
||||
});
|
||||
const updated = await readFile(client.configPath, "utf8");
|
||||
expect(
|
||||
updated.startsWith(`${bom}// Keep the client preferences.\r\n`),
|
||||
).toBe(true);
|
||||
expect(parseClientConfiguration(updated, client.format).document).toEqual(
|
||||
{
|
||||
label: "left\uFEFFright",
|
||||
[serversKey]: {
|
||||
other: { command: "other" },
|
||||
rea: clientRegistrationEntry(client.format, command, {}),
|
||||
},
|
||||
theme: "dark",
|
||||
});
|
||||
expect(await clientConfigurationAligned(client, {}, command)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "already_current",
|
||||
});
|
||||
expect(
|
||||
await readClientRegistrationStatuses(home, currentCommandPath, {
|
||||
platform: "linux",
|
||||
environment: {},
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
client: name,
|
||||
config_path: client.configPath,
|
||||
state: "aligned",
|
||||
command,
|
||||
remediation: null,
|
||||
},
|
||||
]);
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual(
|
||||
{
|
||||
status: "unchanged",
|
||||
},
|
||||
);
|
||||
expect(await readFile(client.configPath)).toEqual(Buffer.from(updated));
|
||||
expect(await readFile(`${client.configPath}.rea.backup`)).toEqual(
|
||||
Buffer.from(original),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
expect(await clientConfigurationAligned(client, {}, command)).toBe(true);
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "already_current",
|
||||
});
|
||||
expect(
|
||||
await readClientRegistrationStatuses(home, currentCommandPath, {
|
||||
platform: "linux",
|
||||
environment: {},
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
client: name,
|
||||
config_path: client.configPath,
|
||||
state: "aligned",
|
||||
command,
|
||||
remediation: null,
|
||||
},
|
||||
]);
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(await readFile(client.configPath)).toEqual(Buffer.from(updated));
|
||||
expect(await readFile(`${client.configPath}.rea.backup`)).toEqual(
|
||||
Buffer.from(original),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -34,25 +34,23 @@ describe("client configuration write failures", () => {
|
||||
});
|
||||
|
||||
describe("TOML client configuration comparison", () => {
|
||||
it.each(["nan", "inf", "-inf"])(
|
||||
"replaces a registration containing %s and preserves unrelated settings",
|
||||
async (value) => {
|
||||
const root = await createTestTempDirectory("rea-client-toml-");
|
||||
const configPath = join(root, "config.toml");
|
||||
const original = `unrelated = ${value}\n[mcp_servers.rea]\ncommand = "old"\nstartup_timeout_sec = ${value}\n`;
|
||||
await writeFile(configPath, original);
|
||||
const client = { name: "codex", format: "toml", configPath } as const;
|
||||
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "configured",
|
||||
backupPath: `${configPath}.rea.backup`,
|
||||
});
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(await readFile(configPath, "utf8")).toContain(
|
||||
`unrelated = ${value}`,
|
||||
);
|
||||
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
},
|
||||
);
|
||||
it("replaces a registration containing a non-finite TOML float and preserves unrelated settings", async () => {
|
||||
const value = "-inf";
|
||||
const root = await createTestTempDirectory("rea-client-toml-");
|
||||
const configPath = join(root, "config.toml");
|
||||
const original = `unrelated = ${value}\n[mcp_servers.rea]\ncommand = "old"\nstartup_timeout_sec = ${value}\n`;
|
||||
await writeFile(configPath, original);
|
||||
const client = { name: "codex", format: "toml", configPath } as const;
|
||||
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "configured",
|
||||
backupPath: `${configPath}.rea.backup`,
|
||||
});
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(await readFile(configPath, "utf8")).toContain(
|
||||
`unrelated = ${value}`,
|
||||
);
|
||||
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { copyFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFile,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
writeFile,
|
||||
symlink,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const script = join(process.cwd(), "scripts", "check-dependency-install.mjs");
|
||||
const sourceRoot = process.cwd();
|
||||
|
||||
const fixture = async (
|
||||
installedVersion?: string,
|
||||
@@ -88,4 +96,175 @@ describe("dependency install freshness", () => {
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
|
||||
});
|
||||
|
||||
it("checks installed dependencies before restoring a cached build", async () => {
|
||||
const root = await createBuildCacheFixture();
|
||||
const seeded = await runNpm(root, ["run", "build:cached"]);
|
||||
expect(seeded.status, seeded.stderr).toBe(0);
|
||||
|
||||
const rootLock = asRecord(
|
||||
JSON.parse(await readFile(join(root, "package-lock.json"), "utf8")),
|
||||
);
|
||||
const lockPackages = asRecord(rootLock?.packages);
|
||||
const rootPackage = asRecord(lockPackages?.[""]);
|
||||
const directDependencies = {
|
||||
...asRecord(rootPackage?.dependencies),
|
||||
...asRecord(rootPackage?.devDependencies),
|
||||
};
|
||||
const dependencyName = Object.keys(directDependencies).sort()[0];
|
||||
if (dependencyName === undefined)
|
||||
throw new Error("fixture has no direct dependencies");
|
||||
const dependencyPath = `node_modules/${dependencyName}`;
|
||||
const expectedDependency = asRecord(lockPackages?.[dependencyPath]);
|
||||
if (typeof expectedDependency?.version !== "string")
|
||||
throw new Error(
|
||||
`fixture is missing the locked ${dependencyName} version`,
|
||||
);
|
||||
const installedLockPath = join(root, "node_modules", ".package-lock.json");
|
||||
const installedLock = asRecord(
|
||||
JSON.parse(await readFile(installedLockPath, "utf8")),
|
||||
);
|
||||
const packages = asRecord(installedLock?.packages);
|
||||
const installedDependency = asRecord(packages?.[dependencyPath]);
|
||||
if (installedDependency === undefined)
|
||||
throw new Error(`fixture is missing installed ${dependencyName}`);
|
||||
installedDependency.version = "0.0.0";
|
||||
await writeFile(installedLockPath, JSON.stringify(installedLock));
|
||||
|
||||
const blocked = await runNpm(root, ["run", "build:cached"]);
|
||||
expect(blocked.status).toBe(1);
|
||||
expect(blocked.stderr).toContain(
|
||||
`${dependencyName}: installed 0.0.0, expected ${expectedDependency.version}`,
|
||||
);
|
||||
|
||||
const cached = await runTurbo(root);
|
||||
expect(cached.status, cached.stderr).toBe(0);
|
||||
expect(`${cached.stdout}${cached.stderr}`).toMatch(/cache hit/u);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
const createBuildCacheFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-build-cache-guard-");
|
||||
const packageJson = asRecord(
|
||||
JSON.parse(await readFile(join(sourceRoot, "package.json"), "utf8")),
|
||||
);
|
||||
const scripts = asRecord(packageJson?.scripts);
|
||||
if (
|
||||
packageJson === undefined ||
|
||||
typeof scripts?.["build:cached"] !== "string"
|
||||
)
|
||||
throw new Error("package is missing its cached build command");
|
||||
const paths = [
|
||||
".nvmrc",
|
||||
"package-lock.json",
|
||||
"turbo.json",
|
||||
"tsconfig.json",
|
||||
"tsconfig.build.json",
|
||||
"scripts/check-dependency-install.mjs",
|
||||
"scripts/clean-build-output.mjs",
|
||||
"scripts/generate-package-metadata.mjs",
|
||||
"scripts/lib/generated-file.mjs",
|
||||
"skills/reverse-engineer-anything/SKILL.md",
|
||||
"src/generatedPackageMetadata.ts",
|
||||
];
|
||||
await Promise.all(
|
||||
paths.map(async (path) => {
|
||||
const destination = join(root, path);
|
||||
await mkdir(dirname(destination), { recursive: true });
|
||||
await copyFile(join(sourceRoot, path), destination);
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
...packageJson,
|
||||
scripts: {
|
||||
...scripts,
|
||||
build: "node scripts/cache-fixture-build.mjs",
|
||||
},
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "scripts/cache-fixture-build.mjs"),
|
||||
'import { mkdir, writeFile } from "node:fs/promises"; await mkdir("dist", { recursive: true }); await writeFile("dist/cache-fixture.js", "built");\n',
|
||||
);
|
||||
await createNodeModulesLinks(root);
|
||||
await writeFile(
|
||||
join(root, "node_modules", ".package-lock.json"),
|
||||
await readFile(join(sourceRoot, "node_modules", ".package-lock.json")),
|
||||
);
|
||||
return root;
|
||||
};
|
||||
|
||||
const createNodeModulesLinks = async (root: string): Promise<void> => {
|
||||
const source = join(sourceRoot, "node_modules");
|
||||
const destination = join(root, "node_modules");
|
||||
await mkdir(destination);
|
||||
for (const entry of await readdir(source, { withFileTypes: true })) {
|
||||
if (entry.name === ".package-lock.json") continue;
|
||||
const sourcePath = join(source, entry.name);
|
||||
const destinationPath = join(destination, entry.name);
|
||||
if (entry.name.startsWith("@") && entry.isDirectory()) {
|
||||
await mkdir(destinationPath);
|
||||
for (const packageName of await readdir(sourcePath))
|
||||
await symlink(
|
||||
join(sourcePath, packageName),
|
||||
join(destinationPath, packageName),
|
||||
process.platform === "win32" ? "junction" : undefined,
|
||||
);
|
||||
} else {
|
||||
await symlink(
|
||||
sourcePath,
|
||||
destinationPath,
|
||||
process.platform === "win32" ? "junction" : undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const runNpm = (cwd: string, arguments_: readonly string[]) =>
|
||||
run("npm", arguments_, cwd);
|
||||
|
||||
const runTurbo = (cwd: string) =>
|
||||
run(
|
||||
process.execPath,
|
||||
[
|
||||
join(cwd, "node_modules", "turbo", "bin", "turbo"),
|
||||
"run",
|
||||
"build",
|
||||
"--output-logs=full",
|
||||
],
|
||||
cwd,
|
||||
);
|
||||
|
||||
const run = (
|
||||
command: string,
|
||||
arguments_: readonly string[],
|
||||
cwd: string,
|
||||
): Promise<{
|
||||
readonly status: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn(command, [...arguments_], {
|
||||
cwd,
|
||||
env: process.env,
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
|
||||
child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
|
||||
child.once("error", reject);
|
||||
child.once("close", (status) =>
|
||||
resolve({ status: status ?? 1, stdout, stderr }),
|
||||
);
|
||||
});
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
|
||||
isRecord(value) ? value : undefined;
|
||||
|
||||
@@ -54,7 +54,7 @@ describe("direct analysis snapshot files", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("replays a cache hit from the supplied path without root configuration", async () => {
|
||||
it("does not replay unbound historical Evidence from a supplied snapshot", async () => {
|
||||
const directory = await createTestTempDirectory("rea-direct-snapshot-");
|
||||
const snapshotPath = join(directory, "analysis.json");
|
||||
const launcherPath = join(directory, "hopper-launcher");
|
||||
@@ -97,6 +97,6 @@ describe("direct analysis snapshot files", () => {
|
||||
snapshotPath,
|
||||
},
|
||||
),
|
||||
).resolves.toEqual(evidence);
|
||||
).resolves.not.toEqual(evidence);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,36 +6,33 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("DOS COM admission", () => {
|
||||
it.each(["fixture.com", "fixture.hop", "fixture.js", "fixture.bin"])(
|
||||
"requires explicit interpretation for %s",
|
||||
async (name) => {
|
||||
const directory = await createTestTempDirectory("rea-com-target-");
|
||||
const path = join(directory, name);
|
||||
const bytes = Buffer.from("b83412c3", "hex");
|
||||
await writeFile(path, bytes);
|
||||
const target = await parseBinaryTarget(
|
||||
it("requires explicit interpretation even when a DOS COM uses a misleading suffix", async () => {
|
||||
const directory = await createTestTempDirectory("rea-com-target-");
|
||||
const path = join(directory, "fixture.js");
|
||||
const bytes = Buffer.from("b83412c3", "hex");
|
||||
await writeFile(path, bytes);
|
||||
const target = await parseBinaryTarget(
|
||||
path,
|
||||
directory,
|
||||
"arm64",
|
||||
undefined,
|
||||
"dos-com",
|
||||
);
|
||||
expect(target).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
path,
|
||||
directory,
|
||||
"arm64",
|
||||
undefined,
|
||||
"dos-com",
|
||||
);
|
||||
expect(target).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
path,
|
||||
format: "dos-com",
|
||||
kind: "executable",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
},
|
||||
});
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
const detected = await parseBinaryTarget(path);
|
||||
expect(detected.ok && detected.value.format).not.toBe("dos-com");
|
||||
},
|
||||
);
|
||||
format: "dos-com",
|
||||
kind: "executable",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
},
|
||||
});
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
const detected = await parseBinaryTarget(path);
|
||||
expect(detected.ok && detected.value.format).not.toBe("dos-com");
|
||||
});
|
||||
it.each([0, 0xff01])("rejects invalid file extent %i", async (length) => {
|
||||
const directory = await createTestTempDirectory("rea-com-target-");
|
||||
const path = join(directory, "fixture.com");
|
||||
|
||||
@@ -30,18 +30,22 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
expect(await readdir(fixture.temporary)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["22.19.0", "24.11.0", "26.0.0", "27.0.0"])(
|
||||
it.each(["22.19.0", "24.11.0", "26.0.0"])(
|
||||
"accepts supported Node %s without installing or replacing it",
|
||||
async (version) => {
|
||||
const fixture = await createFixture();
|
||||
const result = await runInstaller(fixture, ["--version", "0.3.0"], {
|
||||
FAKE_NODE_VERSION: version,
|
||||
});
|
||||
const result = await runInstaller(
|
||||
fixture,
|
||||
["--version", "0.3.0", "--dry-run"],
|
||||
{
|
||||
FAKE_NODE_VERSION: version,
|
||||
},
|
||||
);
|
||||
expect(result.stdout).toContain(`Runtime: Node.js ${version}`);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["22.18.9", "23.0.0", "24.10.9", "25.1.0", "26.0.0-rc.1"])(
|
||||
it.each(["22.18.9", "24.10.9", "23.0.0", "26.0.0-rc.1"])(
|
||||
"rejects unsupported Node %s before invoking npm",
|
||||
async (version) => {
|
||||
const fixture = await createFixture();
|
||||
@@ -77,15 +81,7 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Every installer failure must carry a recovery action. AGENTS.md requires
|
||||
// actionable diagnostics, including for mismatch locations, so a failure that
|
||||
// only states what went wrong is a regression.
|
||||
// The installer is the one surface whose output is read directly by a person
|
||||
// in a terminal, so the exact wording is a real contract and stays pinned.
|
||||
// Alongside it, each row asserts the two properties that matter
|
||||
// independently of phrasing: the failure is announced as a REA installation
|
||||
// failure, and the message carries a recovery action. A copy edit then shows
|
||||
// up as one reviewable diff instead of silently losing the guidance.
|
||||
// Keep each distinct failure route while checking its reason and recovery.
|
||||
it.each([
|
||||
[
|
||||
"unsupported Node",
|
||||
@@ -158,11 +154,6 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
expect(failure).toBeInstanceOf(Error);
|
||||
const stderr = String((failure as { stderr?: unknown }).stderr ?? "");
|
||||
expect(stderr).toBe(message);
|
||||
expect(stderr.startsWith("REA installation failed: ")).toBe(true);
|
||||
// Actionable guidance must survive any rewording.
|
||||
expect(stderr).toMatch(
|
||||
/\b(?:Check|Repair|Reinstall|Install|Retry|then retry|use Node)\b/,
|
||||
);
|
||||
expect(await readdir(fixture.temporary)).toEqual([]);
|
||||
},
|
||||
);
|
||||
@@ -181,6 +172,95 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("installer semantic version parsing", { timeout: 20_000 }, () => {
|
||||
it.each(["1.2.3-01"])(
|
||||
"rejects malformed semantic versions before invoking npm: %s",
|
||||
async (version) => {
|
||||
const fixture = await createFixture();
|
||||
await expect(
|
||||
runInstaller(fixture, ["--version", version, "--dry-run"]),
|
||||
).rejects.toMatchObject({
|
||||
stderr:
|
||||
"REA installation failed: version must be an exact semantic version.\n",
|
||||
});
|
||||
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects valid build metadata before printing a plan or invoking npm", async () => {
|
||||
const fixture = await createFixture();
|
||||
const failure = await runInstaller(fixture, [
|
||||
"--version",
|
||||
"1.2.3+build.01",
|
||||
"--dry-run",
|
||||
]).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(Error);
|
||||
const stderr = getProcessOutput(failure, "stderr");
|
||||
expect(stderr).toBe(
|
||||
"REA installation failed: npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry.\n",
|
||||
);
|
||||
expect(getProcessOutput(failure, "stdout")).not.toContain(
|
||||
"REA install plan",
|
||||
);
|
||||
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a valid prerelease version without build metadata", async () => {
|
||||
const fixture = await createFixture();
|
||||
const result = await runInstaller(fixture, [
|
||||
"--version",
|
||||
"1.2.3-alpha.0",
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(result.stdout).toContain("Version: 1.2.3-alpha.0");
|
||||
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects build metadata in the latest release tag before printing a plan", async () => {
|
||||
const fixture = await createFixture();
|
||||
const failure = await runInstaller(fixture, [], {
|
||||
FAKE_CURL_BODY: '{"tag_name":"rea-agents-1.2.3+build.01"}',
|
||||
}).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(Error);
|
||||
expect(getProcessOutput(failure, "stderr")).toBe(
|
||||
"REA installation failed: npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry.\n",
|
||||
);
|
||||
expect(getProcessOutput(failure, "stdout")).not.toContain(
|
||||
"REA install plan",
|
||||
);
|
||||
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an invalid semantic version from the latest release tag", async () => {
|
||||
const fixture = await createFixture();
|
||||
await expect(
|
||||
runInstaller(fixture, [], {
|
||||
FAKE_CURL_BODY: '{"tag_name":"rea-agents-1.2.3-01"}',
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
stderr:
|
||||
"REA installation failed: the latest release tag was invalid. Retry later or pass --version VERSION.\n",
|
||||
});
|
||||
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
interface InstallerFixture {
|
||||
readonly home: string;
|
||||
readonly bin: string;
|
||||
@@ -189,6 +269,20 @@ interface InstallerFixture {
|
||||
readonly reaLog: string;
|
||||
}
|
||||
|
||||
const getProcessOutput = (
|
||||
failure: unknown,
|
||||
stream: "stdout" | "stderr",
|
||||
): string => {
|
||||
if (!(failure instanceof Error)) return "";
|
||||
if (stream === "stdout" && "stdout" in failure) {
|
||||
return typeof failure.stdout === "string" ? failure.stdout : "";
|
||||
}
|
||||
if (stream === "stderr" && "stderr" in failure) {
|
||||
return typeof failure.stderr === "string" ? failure.stderr : "";
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
const createFixture = async (): Promise<InstallerFixture> => {
|
||||
const root = await createTestTempDirectory("rea-install-test-");
|
||||
const home = join(root, "home");
|
||||
@@ -197,19 +291,20 @@ const createFixture = async (): Promise<InstallerFixture> => {
|
||||
const npmLog = join(root, "npm.log");
|
||||
const reaLog = join(root, "rea.log");
|
||||
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
|
||||
await executable(
|
||||
join(bin, "uname"),
|
||||
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
|
||||
);
|
||||
await executable(
|
||||
join(bin, "node"),
|
||||
`#!/bin/sh
|
||||
await Promise.all([
|
||||
executable(
|
||||
join(bin, "uname"),
|
||||
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
|
||||
),
|
||||
executable(
|
||||
join(bin, "node"),
|
||||
`#!/bin/sh
|
||||
if [ "$1" = "-p" ]; then printf '%s\n' "\${FAKE_NODE_VERSION:-24.18.0}"; else exec ${shellQuote(process.execPath)} "$@"; fi
|
||||
`,
|
||||
);
|
||||
await executable(
|
||||
join(bin, "npm"),
|
||||
`#!/bin/sh
|
||||
),
|
||||
executable(
|
||||
join(bin, "npm"),
|
||||
`#!/bin/sh
|
||||
printf '%s\n' "$*" >> "$FAKE_NPM_LOG"
|
||||
[ "$1" = "prefix" ] && { [ "\${FAKE_NPM_PREFIX_FAIL:-}" = "1" ] && exit 1; printf '%s\n' "$FAKE_NPM_PREFIX"; exit 0; }
|
||||
[ "\${FAKE_NPM_FAIL:-}" = "1" ] && exit 1
|
||||
@@ -223,25 +318,27 @@ mkdir -p "$prefix/bin"
|
||||
cp "$FAKE_REA_SOURCE" "$prefix/bin/rea"
|
||||
chmod +x "$prefix/bin/rea"
|
||||
`,
|
||||
);
|
||||
await executable(
|
||||
join(bin, "curl"),
|
||||
`#!/bin/sh
|
||||
),
|
||||
executable(
|
||||
join(bin, "curl"),
|
||||
`#!/bin/sh
|
||||
[ "\${FAKE_CURL_FAIL:-}" = "1" ] && exit 1
|
||||
if [ -n "\${FAKE_CURL_BODY:-}" ]; then printf '%s' "$FAKE_CURL_BODY"; else printf '%s' '{"tag_name":"rea-agents-0.3.0"}'; fi
|
||||
`,
|
||||
);
|
||||
await executable(
|
||||
join(bin, "rea-source"),
|
||||
`#!/bin/sh
|
||||
),
|
||||
executable(
|
||||
join(bin, "rea-source"),
|
||||
`#!/bin/sh
|
||||
printf '%s\n' "$*" >> "$FAKE_REA_LOG"
|
||||
[ "\${FAKE_REA_VERSION_FAIL:-}" = "1" ] && exit 1
|
||||
[ "$1" = "--version" ] && printf '%s\n' "\${FAKE_REA_VERSION:-0.3.0}"
|
||||
exit 0
|
||||
`,
|
||||
);
|
||||
for (const command of ["chmod", "cp", "mkdir", "tr"])
|
||||
await symlink(`/usr/bin/${command}`, join(bin, command));
|
||||
),
|
||||
...["chmod", "cp", "mkdir", "tr"].map((command) =>
|
||||
symlink(`/usr/bin/${command}`, join(bin, command)),
|
||||
),
|
||||
]);
|
||||
return { home, bin, temporary, npmLog, reaLog };
|
||||
};
|
||||
|
||||
|
||||
@@ -13,6 +13,57 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const compile = promisify(execFile);
|
||||
|
||||
type PlistValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| Date
|
||||
| Uint8Array
|
||||
| PlistValue[]
|
||||
| { [key: string]: PlistValue }
|
||||
| null;
|
||||
|
||||
const keyedArchiveHierarchy = (
|
||||
nodes: readonly {
|
||||
readonly id: string;
|
||||
readonly children: readonly number[];
|
||||
}[],
|
||||
) => {
|
||||
const nodeClass = 1 + nodes.length * 2;
|
||||
const arrayClass = nodeClass + 1;
|
||||
const objects: PlistValue[] = Array.from(
|
||||
{ length: arrayClass + 1 },
|
||||
() => null,
|
||||
);
|
||||
objects[0] = "$null";
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
const nodeUid = 1 + index * 2;
|
||||
objects[nodeUid] = {
|
||||
$class: { UID: nodeClass },
|
||||
objectID: node.id,
|
||||
children: { UID: nodeUid + 1 },
|
||||
};
|
||||
objects[nodeUid + 1] = {
|
||||
$class: { UID: arrayClass },
|
||||
"NS.objects": node.children.map((child) => ({ UID: 1 + child * 2 })),
|
||||
};
|
||||
}
|
||||
objects[nodeClass] = {
|
||||
$classname: "FixtureHierarchyNode",
|
||||
$classes: ["FixtureHierarchyNode", "NSObject"],
|
||||
};
|
||||
objects[arrayClass] = {
|
||||
$classname: "__NSArrayI",
|
||||
$classes: ["__NSArrayI", "NSArray", "NSObject"],
|
||||
};
|
||||
return buildBinary({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: objects,
|
||||
$top: { root: { UID: 1 } },
|
||||
});
|
||||
};
|
||||
|
||||
describe("compiled Interface Builder bundle reader", () => {
|
||||
it("reads nib plist archives and reports provenance", async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
@@ -149,7 +200,118 @@ describe("compiled Interface Builder bundle reader", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("keyed archive hierarchy coverage", () => {
|
||||
it("projects a deep keyed-archive hierarchy through NSArray wrappers", async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
const nodes = Array.from({ length: 40 }, (_, index) => ({
|
||||
id: `view-${index}`,
|
||||
children: index === 39 ? [] : [index + 1],
|
||||
}));
|
||||
await writeFile(join(resources, "Deep.nib"), keyedArchiveHierarchy(nodes));
|
||||
|
||||
const analysis = await analyzeInterfaceBuilderBundle({
|
||||
bundlePath: bundle,
|
||||
targetSha256: "f".repeat(64),
|
||||
});
|
||||
|
||||
expect(analysis.documents[0]?.hierarchy_complete).toBe(true);
|
||||
expect(analysis.graph.truncated).toBe(false);
|
||||
expect(analysis.graph.coverage).toContainEqual(
|
||||
expect.objectContaining({
|
||||
facet: "hierarchy:Contents/Resources/Deep.nib",
|
||||
status: "complete",
|
||||
omitted: 0,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
analysis.graph.edges.filter(
|
||||
({ relation, id }) =>
|
||||
relation === "contains" && id.includes(":hierarchy:"),
|
||||
),
|
||||
).toHaveLength(40);
|
||||
});
|
||||
|
||||
it("preserves source order for children in an archived collection", async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await writeFile(
|
||||
join(resources, "Branching.nib"),
|
||||
keyedArchiveHierarchy([
|
||||
{ id: "root", children: [1, 2] },
|
||||
{ id: "first", children: [] },
|
||||
{ id: "second", children: [] },
|
||||
]),
|
||||
);
|
||||
|
||||
const analysis = await analyzeInterfaceBuilderBundle({
|
||||
bundlePath: bundle,
|
||||
targetSha256: "e".repeat(64),
|
||||
});
|
||||
const archiveIdsByNodeId = new Map(
|
||||
analysis.graph.nodes.map(({ id, attributes }) => [
|
||||
id,
|
||||
attributes.interface_builder_object_id,
|
||||
]),
|
||||
);
|
||||
const rootId = analysis.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "root",
|
||||
)?.id;
|
||||
const childNames = analysis.graph.edges
|
||||
.filter(
|
||||
({ from, relation, id }) =>
|
||||
from === rootId &&
|
||||
relation === "contains" &&
|
||||
id.includes(":hierarchy:"),
|
||||
)
|
||||
.map(({ to }) => (to === null ? null : archiveIdsByNodeId.get(to)));
|
||||
expect(childNames).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "darwin")(
|
||||
"projects a deep NSView archive produced by Foundation NSKeyedArchiver",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
const archive = join(resources, "Foundation.nib");
|
||||
await compile("/usr/bin/xcrun", [
|
||||
"swift",
|
||||
"tests/conformance/native/keyed-archive-hierarchy.swift",
|
||||
archive,
|
||||
"40",
|
||||
]);
|
||||
|
||||
const analysis = await analyzeInterfaceBuilderBundle({
|
||||
bundlePath: bundle,
|
||||
targetSha256: "d".repeat(64),
|
||||
});
|
||||
expect(analysis.documents[0]?.hierarchy_complete).toBe(true);
|
||||
expect(analysis.graph.truncated).toBe(false);
|
||||
expect(
|
||||
analysis.graph.coverage.find(
|
||||
({ facet }) =>
|
||||
facet === "hierarchy:Contents/Resources/Foundation.nib",
|
||||
),
|
||||
).toMatchObject({ status: "complete", examined: 41, omitted: 0 });
|
||||
expect(
|
||||
analysis.graph.edges.filter(
|
||||
({ relation, id }) =>
|
||||
relation === "contains" && id.includes(":hierarchy:"),
|
||||
),
|
||||
).toHaveLength(41);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("compiled Interface Builder bundle reader cancellation", () => {
|
||||
it("honors cancellation during directory traversal", async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const controller = new AbortController();
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { lstat, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
|
||||
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { readJavaScriptArtifactFiles } from "../../../src/artifacts/javascript/JavaScriptArtifactFiles.js";
|
||||
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../../../src/artifacts/DirectoryArtifactReader.js";
|
||||
@@ -86,6 +86,24 @@ describe("JavaScript artifact ingestion content identities", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a same-size ASAR replacement against the inventoried root digest", async () => {
|
||||
const { source, archive } = await fixture();
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
const original = await lstat(archive);
|
||||
await writeFile(join(source, "main.js"), "module.exports = 43;\n");
|
||||
await createPackage(source, archive);
|
||||
expect((await lstat(archive)).size).toBe(original.size);
|
||||
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
try {
|
||||
await expect(
|
||||
readJavaScriptArtifactFiles(reader, snapshot),
|
||||
).rejects.toMatchObject({ reason: "integrity" });
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves typed cancellation when the direct ASAR filesystem stream aborts", async () => {
|
||||
const { archive } = await fixture();
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { readJavaScriptArtifactFiles } from "../../../src/artifacts/javascript/JavaScriptArtifactFiles.js";
|
||||
import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
|
||||
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
|
||||
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import {
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
|
||||
@@ -88,6 +88,21 @@ describe("JavaScript export return-shape comparison", () => {
|
||||
expect(result.coverage.status).toBe("partial");
|
||||
});
|
||||
|
||||
it("orders multiple changed paths deterministically across Unicode names", async () => {
|
||||
const graphs = await analyzeSources({
|
||||
left: `export default () => ({ type: "item", zeta: 1, alpha: 1, "éclair": 1 });`,
|
||||
right: `export default () => ({ type: "item", zeta: 2, alpha: 2, "éclair": 2 });`,
|
||||
});
|
||||
const first = compare(...graphs);
|
||||
const second = compare(...graphs);
|
||||
|
||||
expect(new Set(first.changes.map(({ path }) => path))).toEqual(
|
||||
new Set(["/alpha", "/zeta", "/éclair"]),
|
||||
);
|
||||
expect(first.changes).toEqual(second.changes);
|
||||
expect(first.comparison_id).toBe(second.comparison_id);
|
||||
});
|
||||
|
||||
it("does not pair discriminants that an unknown trailing spread can overwrite", async () => {
|
||||
const [left, right] = await analyzeSources({
|
||||
left: `
|
||||
|
||||
@@ -5,31 +5,28 @@ import { readJsonFile } from "../../../src/application/JsonFiles.js";
|
||||
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
describe("JSON file UTF-8 byte integrity", () => {
|
||||
it.each([0x80, 0xe9, 0xff])(
|
||||
"rejects invalid UTF-8 byte %s through both file input boundaries",
|
||||
async (invalidByte) => {
|
||||
const root = await createTestTempDirectory("rea-json-utf8-");
|
||||
const path = join(root, "input.json");
|
||||
await writeFile(
|
||||
path,
|
||||
Buffer.concat([
|
||||
Buffer.from('{"message":"'),
|
||||
Buffer.from([invalidByte]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
);
|
||||
const fileInput = await readJsonFile(path);
|
||||
const cliInput = await parseCliJsonInput(path, "compare_web_captures");
|
||||
expect(fileInput).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "invalid-json" },
|
||||
});
|
||||
expect(cliInput).toMatchObject({
|
||||
ok: false,
|
||||
error: { input_reason: "invalid-json" },
|
||||
});
|
||||
},
|
||||
);
|
||||
it("rejects invalid UTF-8 through both file input boundaries", async () => {
|
||||
const root = await createTestTempDirectory("rea-json-utf8-");
|
||||
const path = join(root, "input.json");
|
||||
await writeFile(
|
||||
path,
|
||||
Buffer.concat([
|
||||
Buffer.from('{"message":"'),
|
||||
Buffer.from([0x80]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
);
|
||||
const fileInput = await readJsonFile(path);
|
||||
const cliInput = await parseCliJsonInput(path, "compare_web_captures");
|
||||
expect(fileInput).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "invalid-json" },
|
||||
});
|
||||
expect(cliInput).toMatchObject({
|
||||
ok: false,
|
||||
error: { input_reason: "invalid-json" },
|
||||
});
|
||||
});
|
||||
it("preserves a legitimate UTF-8 replacement character", async () => {
|
||||
const root = await createTestTempDirectory("rea-json-utf8-control-");
|
||||
const path = join(root, "input.json");
|
||||
|
||||
@@ -11,16 +11,12 @@ it("imports test-suffixed filenames with unchanged paths, hashes, and languages"
|
||||
const root = await createTestTempDirectory("rea-reference-test-filenames-");
|
||||
const files = [
|
||||
["main_test.go", "package main\n", ["source", "test"], "Go"],
|
||||
["main_test.py", "assert True\n", ["source", "test"], "Python"],
|
||||
["test_helper.py", "assert True\n", ["source", "test"], "Python"],
|
||||
["parser_spec.rs", "fn checks() {}\n", ["source", "test"], "Rust"],
|
||||
["Widget_SPEC.TS", "export {};\n", ["source", "test"], "TypeScript"],
|
||||
["main_test", "test fixture\n", ["test"], null],
|
||||
["main_spec", "spec fixture\n", ["test"], null],
|
||||
["test_helper.py", "assert True\n", ["source", "test"], "Python"],
|
||||
["main.test.js", "export {};\n", ["source", "test"], "JavaScript"],
|
||||
["main.go", "package main\n", ["source"], "Go"],
|
||||
["main_test_helper.py", "value = 1\n", ["source"], "Python"],
|
||||
["main_specimen.rs", "fn main() {}\n", ["source"], "Rust"],
|
||||
["main_test.py.bak", "backup\n", ["unknown"], null],
|
||||
] as const;
|
||||
await Promise.all(
|
||||
|
||||
@@ -1,8 +1,420 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
import { parse } from "yaml";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const stepSchema = z.object({
|
||||
name: z.string().optional(),
|
||||
uses: z.string().optional(),
|
||||
run: z.string().optional(),
|
||||
if: z.string().optional(),
|
||||
with: z.record(z.string(), z.unknown()).optional(),
|
||||
env: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
const jobSchema = z.object({
|
||||
if: z.string().optional(),
|
||||
outputs: z.record(z.string(), z.string()).optional(),
|
||||
steps: z.array(stepSchema),
|
||||
});
|
||||
|
||||
async function readReleaseWorkflow() {
|
||||
return z
|
||||
.object({
|
||||
on: z.record(z.string(), z.unknown()),
|
||||
jobs: z.object({
|
||||
"release-please": jobSchema,
|
||||
publish: jobSchema,
|
||||
"publish-mcp": jobSchema,
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL("../../../.github/workflows/release.yml", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it("requires explicit release preparation or publication instead of main pushes", async () => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
expect(Object.keys(workflow.on)).toEqual(["workflow_dispatch"]);
|
||||
expect(workflow.on.workflow_dispatch).toMatchObject({
|
||||
inputs: {
|
||||
release_branch: { required: true, type: "string" },
|
||||
phase: {
|
||||
required: true,
|
||||
type: "choice",
|
||||
default: "prepare",
|
||||
options: ["prepare", "publish"],
|
||||
},
|
||||
},
|
||||
});
|
||||
const release = workflow.jobs["release-please"].steps.find((step) =>
|
||||
step.uses?.startsWith("googleapis/release-please-action@"),
|
||||
);
|
||||
expect(release?.with).toMatchObject({
|
||||
token: "${{ secrets.RELEASE_PLEASE_TOKEN || secrets.GITHUB_TOKEN }}",
|
||||
"target-branch": "${{ inputs.release_branch }}",
|
||||
"skip-github-release": "${{ inputs.phase == 'prepare' }}",
|
||||
"skip-github-pull-request": "${{ inputs.phase == 'publish' }}",
|
||||
});
|
||||
const catalogCommit = workflow.jobs["release-please"].steps.find(
|
||||
(step) => step.name === "Commit canonical release catalog",
|
||||
);
|
||||
expect(catalogCommit?.env?.GH_TOKEN).toBe(
|
||||
"${{ secrets.RELEASE_PLEASE_TOKEN || secrets.GITHUB_TOKEN }}",
|
||||
);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32").each([
|
||||
{ phase: "prepare", customToken: "" },
|
||||
{ phase: "publish", customToken: "" },
|
||||
{ phase: "prepare", customToken: "fixture-custom-token" },
|
||||
{ phase: "publish", customToken: "fixture-custom-token" },
|
||||
])(
|
||||
"accepts $phase with optional custom credentials: $customToken",
|
||||
async ({ phase, customToken }) => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const steps = workflow.jobs["release-please"].steps;
|
||||
const actionIndex = steps.findIndex((step) =>
|
||||
step.uses?.startsWith("googleapis/release-please-action@"),
|
||||
);
|
||||
expect(actionIndex).toBeGreaterThanOrEqual(0);
|
||||
const commands = steps
|
||||
.slice(0, actionIndex)
|
||||
.filter(
|
||||
(step) =>
|
||||
step.if === undefined ||
|
||||
(phase === "publish" && step.if === "inputs.phase == 'publish'"),
|
||||
)
|
||||
.map((step) => z.string().parse(step.run));
|
||||
const directory = await createTestTempDirectory("rea-release-credential-");
|
||||
const output = join(directory, "github-output");
|
||||
await writeFile(
|
||||
join(directory, "gh"),
|
||||
'#!/bin/sh\nprintf "%s\\n" "$GITHUB_SHA"\n',
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
await expect(
|
||||
execFileAsync(
|
||||
"bash",
|
||||
["-e", "-o", "pipefail", "-c", commands.join("\n")],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `${directory}${delimiter}${process.env.PATH ?? ""}`,
|
||||
RELEASE_PLEASE_TOKEN: customToken,
|
||||
GH_TOKEN: customToken || "fixture-built-in-token",
|
||||
RELEASE_PHASE: phase,
|
||||
RELEASE_BRANCH: "release/5.0.0",
|
||||
GITHUB_REF:
|
||||
phase === "prepare"
|
||||
? "refs/heads/main"
|
||||
: "refs/heads/release/5.0.0",
|
||||
GITHUB_REPOSITORY: "fixture/fixture",
|
||||
GITHUB_SHA: "1111111111111111111111111111111111111111",
|
||||
BRANCH_SHA: "1111111111111111111111111111111111111111",
|
||||
GITHUB_OUTPUT: output,
|
||||
},
|
||||
},
|
||||
),
|
||||
).resolves.toMatchObject({ stderr: "" });
|
||||
expect(await readFile(output, "utf8")).toBe(
|
||||
"sha=1111111111111111111111111111111111111111\n",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("binds npm and MCP publication to the same immutable release SHA", async () => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
expect(workflow.jobs["release-please"].outputs).toEqual({
|
||||
release_created: "${{ steps.release.outputs.release_created }}",
|
||||
sha: "${{ steps.release.outputs.sha }}",
|
||||
});
|
||||
expect(workflow.jobs.publish.if).toBe(
|
||||
"inputs.phase == 'publish' && needs.release-please.outputs.release_created == 'true'",
|
||||
);
|
||||
expect(workflow.jobs["publish-mcp"].if).toBe(
|
||||
"inputs.phase == 'publish' && needs.release-please.outputs.release_created == 'true' && needs.publish.result == 'success'",
|
||||
);
|
||||
for (const job of [workflow.jobs.publish, workflow.jobs["publish-mcp"]]) {
|
||||
const checkout = job.steps.find((step) =>
|
||||
step.uses?.startsWith("actions/checkout@"),
|
||||
);
|
||||
expect(checkout?.with).toMatchObject({
|
||||
ref: "${{ needs.release-please.outputs.sha }}",
|
||||
"persist-credentials": false,
|
||||
});
|
||||
}
|
||||
const preparation = [
|
||||
"Check out release pull request",
|
||||
"Set up Node.js for generated documentation",
|
||||
"Install dependencies",
|
||||
"Regenerate release documentation",
|
||||
"Commit canonical release catalog",
|
||||
];
|
||||
for (const name of preparation) {
|
||||
expect(
|
||||
workflow.jobs["release-please"].steps.find((step) => step.name === name)
|
||||
?.if,
|
||||
).toBe(
|
||||
"inputs.phase == 'prepare' && steps.release.outputs.prs_created == 'true'",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it
|
||||
.skipIf(process.platform === "win32")
|
||||
.each(["main", "feature/new-work", "release/", "release/../main"])(
|
||||
"rejects %s as a checkpoint before contacting GitHub",
|
||||
async (releaseBranch) => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const command = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) => step.name === "Validate release selection",
|
||||
)?.run,
|
||||
);
|
||||
await expect(
|
||||
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_REF: "refs/heads/main",
|
||||
RELEASE_BRANCH: releaseBranch,
|
||||
RELEASE_PHASE: "prepare",
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringMatching(/release_branch/u),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32").each([
|
||||
{ phase: "prepare", ref: "refs/heads/feature/unreviewed-workflow" },
|
||||
{ phase: "publish", ref: "refs/heads/main" },
|
||||
{ phase: "publish", ref: "refs/heads/release/another-version" },
|
||||
])(
|
||||
"rejects $phase from $ref before contacting GitHub",
|
||||
async ({ phase, ref }) => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const command = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) => step.name === "Validate release selection",
|
||||
)?.run,
|
||||
);
|
||||
await expect(
|
||||
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_REF: ref,
|
||||
RELEASE_BRANCH: "release/5.0.0",
|
||||
RELEASE_PHASE: phase,
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining(`Run ${phase} from`),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"checks the checkpoint locally and resolves the branch tip separately",
|
||||
async () => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const validate = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) => step.name === "Validate release selection",
|
||||
)?.run,
|
||||
);
|
||||
expect(validate).not.toMatch(/\bgh\b/u);
|
||||
const resolve = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) => step.name === "Resolve release branch tip",
|
||||
)?.run,
|
||||
);
|
||||
expect(resolve).toContain("gh api");
|
||||
for (const releaseBranch of ["release/5.0.0", "release/5.0.0-rc.1"]) {
|
||||
await expect(
|
||||
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", validate], {
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_REF: "refs/heads/main",
|
||||
RELEASE_BRANCH: releaseBranch,
|
||||
RELEASE_PHASE: "prepare",
|
||||
},
|
||||
}),
|
||||
).resolves.toMatchObject({ stderr: "" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it
|
||||
.skipIf(process.platform === "win32")
|
||||
.each(["", "release", "prepare ", "true"])(
|
||||
"rejects phase %j before contacting GitHub",
|
||||
async (phase) => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const command = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) => step.name === "Validate release selection",
|
||||
)?.run,
|
||||
);
|
||||
await expect(
|
||||
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_REF: "refs/heads/main",
|
||||
RELEASE_BRANCH: "release/5.0.0",
|
||||
RELEASE_PHASE: phase,
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining("phase must be prepare or publish"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32").each([true, false])(
|
||||
"creates a release only when the branch tip is the dispatched checkpoint (match: %s)",
|
||||
async (match) => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const command = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) =>
|
||||
step.name ===
|
||||
"Require the publish dispatch to match the branch tip",
|
||||
)?.run,
|
||||
);
|
||||
const result = execFileAsync(
|
||||
"bash",
|
||||
["-e", "-o", "pipefail", "-c", command],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_SHA: "1111111111111111111111111111111111111111",
|
||||
BRANCH_SHA: match
|
||||
? "1111111111111111111111111111111111111111"
|
||||
: "2222222222222222222222222222222222222222",
|
||||
},
|
||||
},
|
||||
);
|
||||
if (match) {
|
||||
await expect(result).resolves.toMatchObject({ stderr: "" });
|
||||
} else {
|
||||
await expect(result).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining(
|
||||
"refusing to create a release for a moved source",
|
||||
),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32").each([true, false])(
|
||||
"publishes only when the tag and provenance source match (match: %s)",
|
||||
async (match) => {
|
||||
const workflow = await readReleaseWorkflow();
|
||||
const command = z
|
||||
.string()
|
||||
.parse(
|
||||
workflow.jobs["release-please"].steps.find(
|
||||
(step) =>
|
||||
step.name === "Bind publication to the dispatched checkpoint",
|
||||
)?.run,
|
||||
);
|
||||
const result = execFileAsync(
|
||||
"bash",
|
||||
["-e", "-o", "pipefail", "-c", command],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_SHA: "1111111111111111111111111111111111111111",
|
||||
RELEASE_SHA: match
|
||||
? "1111111111111111111111111111111111111111"
|
||||
: "2222222222222222222222222222222222222222",
|
||||
},
|
||||
},
|
||||
);
|
||||
if (match) {
|
||||
await expect(result).resolves.toMatchObject({ stderr: "" });
|
||||
} else {
|
||||
await expect(result).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining(
|
||||
"refusing to publish mismatched source provenance",
|
||||
),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("runs release PR CI without enabling implementation pushes on release branches", async () => {
|
||||
const workflow = z
|
||||
.object({
|
||||
on: z.object({
|
||||
push: z.object({ branches: z.array(z.string()) }),
|
||||
pull_request: z.object({ branches: z.array(z.string()) }),
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL("../../../.github/workflows/ci.yml", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(workflow.on.push.branches).toEqual(["main"]);
|
||||
expect(workflow.on.pull_request.branches).toEqual(
|
||||
expect.arrayContaining(["main", "release/*"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("checks website changes on release-branch pull requests", async () => {
|
||||
const workflow = z
|
||||
.object({
|
||||
on: z.object({
|
||||
pull_request: z.object({ branches: z.array(z.string()) }),
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL(
|
||||
"../../../.github/workflows/website-check.yml",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(workflow.on.pull_request.branches).toEqual(["main", "release/*"]);
|
||||
});
|
||||
|
||||
// Publishing is irreversible. Keep the release authority invariant as a static
|
||||
// boundary check; it is not proof that package installation or publishing works.
|
||||
it("requires package verification before publishing and retains the registry canary", async () => {
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
TextReader,
|
||||
Uint8ArrayReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipWriter,
|
||||
} from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { runProviderAnalysis } from "../../../src/composition/directAnalysis.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
identifyRuntimes,
|
||||
runtimeIdentificationResultSchema,
|
||||
} from "../../../src/domain/runtimeIdentification.js";
|
||||
|
||||
describe("runtime identification", () => {
|
||||
it("identifies APK runtime families and exposes missing semantic providers", async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-");
|
||||
const path = join(root, "Fixture.apk");
|
||||
await writeApkRuntimeFixture(path);
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const first = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
const second = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
expect(first).toEqual(second);
|
||||
expect(runtimeIdentificationResultSchema.parse(first)).toMatchObject({
|
||||
root_format: "apk",
|
||||
coverage: {
|
||||
status: "complete-within-inventory",
|
||||
inventory_complete: true,
|
||||
},
|
||||
});
|
||||
expect(first.runtimes.map(({ family }) => family)).toEqual([
|
||||
"android",
|
||||
"javascript",
|
||||
"jvm",
|
||||
"native",
|
||||
"webassembly",
|
||||
]);
|
||||
expect(first.runtimes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
family: "android",
|
||||
inspection: "available",
|
||||
provider_id: "rea-android-application",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "jvm",
|
||||
inspection: "provider-missing",
|
||||
provider_id: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "webassembly",
|
||||
inspection: "provider-missing",
|
||||
provider_id: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "javascript",
|
||||
inspection: "available",
|
||||
provider_id: "rea-javascript-application",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "native",
|
||||
inspection: "provider-selection-required",
|
||||
provider_id: null,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const widened = runtimeIdentificationResultSchema.parse({
|
||||
...first,
|
||||
root_format: "x".repeat(101),
|
||||
source_evidence_ids: Array.from(
|
||||
{ length: 101 },
|
||||
() => inventory.evidence_id,
|
||||
),
|
||||
limitations: Array.from({ length: 101 }, () => "x".repeat(4_097)),
|
||||
runtimes: first.runtimes.map((runtime) => ({
|
||||
...runtime,
|
||||
...(runtime.provider_id === null
|
||||
? { reason: "x".repeat(1_001) }
|
||||
: { provider_id: `provider-${"x".repeat(200)}` }),
|
||||
observations: runtime.observations.map((observation) => ({
|
||||
...observation,
|
||||
path: "x".repeat(4_097),
|
||||
format: "x".repeat(101),
|
||||
})),
|
||||
})),
|
||||
});
|
||||
expect(widened.limitations).toHaveLength(101);
|
||||
expect(widened.runtimes[0]?.observations[0]?.path).toHaveLength(4_097);
|
||||
const available = first.runtimes.find(
|
||||
({ inspection }) => inspection === "available",
|
||||
);
|
||||
if (available === undefined)
|
||||
throw new TypeError("Expected an available runtime provider");
|
||||
expect(
|
||||
runtimeIdentificationResultSchema.safeParse({
|
||||
...first,
|
||||
runtimes: [{ ...available, provider_id: null, reason: "Missing." }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts more than 100 supplied inventory Evidence records", async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-pages-");
|
||||
const path = join(root, "Fixture.apk");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("one.js", new TextReader("one"));
|
||||
await writeFile(path, await writer.close());
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const result = identifyRuntimes({
|
||||
inventory_evidence: Array.from({ length: 101 }, () => inventory),
|
||||
});
|
||||
|
||||
expect(result.source_evidence_ids).toHaveLength(101);
|
||||
expect(result.coverage.status).toBe("complete-within-inventory");
|
||||
expect(result.runtimes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
family: "javascript",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "one.js" }),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not route nested DEX content to the APK-only provider", async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-dex-");
|
||||
const path = join(root, "Fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(
|
||||
"classes.dex",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
|
||||
),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const result = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
|
||||
expect(result.runtimes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
family: "android",
|
||||
inspection: "provider-selection-required",
|
||||
provider_id: null,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const writeApkRuntimeFixture = async (path: string): Promise<void> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(
|
||||
"AndroidManifest.xml",
|
||||
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0, 8, 0, 0, 0])),
|
||||
);
|
||||
await writer.add(
|
||||
"classes.dex",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
|
||||
),
|
||||
);
|
||||
await writer.add(
|
||||
"assets/Fixture.class",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]),
|
||||
),
|
||||
);
|
||||
await writer.add(
|
||||
"assets/module.wasm",
|
||||
new Uint8ArrayReader(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])),
|
||||
);
|
||||
await writer.add("assets/main.js", new TextReader("bridge.call();"));
|
||||
await writer.add(
|
||||
"lib/arm64-v8a/libfixture.so",
|
||||
new Uint8ArrayReader(Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0])),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
};
|
||||
@@ -243,36 +243,34 @@ describe("JSON client configuration migration and provider paths", () => {
|
||||
expect(await readFile(configPath, "utf8")).toBe("not-json");
|
||||
});
|
||||
|
||||
it.each(["null", "[]", '"value"'])(
|
||||
"refuses a non-object JSON root without overwriting %s",
|
||||
async (original) => {
|
||||
const directory = await createTestTempDirectory("rea-setup-");
|
||||
const configPath = join(directory, "mcp.json");
|
||||
await writeFile(configPath, original);
|
||||
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
|
||||
{ status: "failed", reason: "readback" },
|
||||
);
|
||||
expect(await readFile(configPath, "utf8")).toBe(original);
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
it("refuses a non-object JSON root without overwriting it", async () => {
|
||||
const original = "null";
|
||||
const directory = await createTestTempDirectory("rea-setup-");
|
||||
const configPath = join(directory, "mcp.json");
|
||||
await writeFile(configPath, original);
|
||||
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
expect(await readFile(configPath, "utf8")).toBe(original);
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it.each(["null", "[]", '"value"'])(
|
||||
"preserves a non-object mcpServers value %s",
|
||||
async (servers) => {
|
||||
const directory = await createTestTempDirectory("rea-setup-");
|
||||
const configPath = join(directory, "mcp.json");
|
||||
const original = `{"mcpServers":${servers}}`;
|
||||
await writeFile(configPath, original);
|
||||
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
|
||||
{ status: "failed", reason: "readback" },
|
||||
);
|
||||
expect(await readFile(configPath, "utf8")).toBe(original);
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
it("preserves a non-object mcpServers value", async () => {
|
||||
const servers = "[]";
|
||||
const directory = await createTestTempDirectory("rea-setup-");
|
||||
const configPath = join(directory, "mcp.json");
|
||||
const original = `{"mcpServers":${servers}}`;
|
||||
await writeFile(configPath, original);
|
||||
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
expect(await readFile(configPath, "utf8")).toBe(original);
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { lstat, readdir, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createStoreFileLock,
|
||||
removeStaleStoreFileLock,
|
||||
} from "../../../src/application/StoreFileLock.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("store lock cleanup ownership", () => {
|
||||
it.each(["released", "replaced"] as const)(
|
||||
"preserves a successor lock when an old %s owner cleans up",
|
||||
async (state) => {
|
||||
const root = await createTestTempDirectory("rea-store-lock-owner-");
|
||||
const path = join(root, "transaction.lock");
|
||||
const previous = await createStoreFileLock(path);
|
||||
if (state === "released") await previous.release();
|
||||
else await rm(path, { recursive: true });
|
||||
const successor = await createStoreFileLock(path);
|
||||
try {
|
||||
await previous.release();
|
||||
await expect(lstat(path)).resolves.toBeDefined();
|
||||
await expect(createStoreFileLock(path)).rejects.toMatchObject({
|
||||
code: "EEXIST",
|
||||
});
|
||||
} finally {
|
||||
await successor.release();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("store lock acquisition and recovery", () => {
|
||||
it("admits one concurrent owner and removes all preparation directories", async () => {
|
||||
const root = await createTestTempDirectory("rea-store-lock-contenders-");
|
||||
const path = join(root, "transaction.lock");
|
||||
const results = await Promise.allSettled(
|
||||
Array.from({ length: 8 }, () => createStoreFileLock(path)),
|
||||
);
|
||||
try {
|
||||
expect(
|
||||
results.filter((result) => result.status === "fulfilled"),
|
||||
).toHaveLength(1);
|
||||
for (const result of results)
|
||||
if (result.status === "rejected")
|
||||
expect(result.reason).toMatchObject({ code: "EEXIST" });
|
||||
expect(await readdir(root)).toEqual(["transaction.lock"]);
|
||||
expect(await removeStaleStoreFileLock(path)).toBe(false);
|
||||
} finally {
|
||||
await Promise.all(
|
||||
results.map((result) =>
|
||||
result.status === "fulfilled" ? result.value.release() : undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
});
|
||||
|
||||
it("recovers a directory lock abandoned by an exited process", async () => {
|
||||
const root = await createTestTempDirectory("rea-store-lock-exited-");
|
||||
const path = join(root, "transaction.lock");
|
||||
await promisify(execFile)(
|
||||
process.execPath,
|
||||
["tests/fixtures/abandonStoreFileLock.mjs", path],
|
||||
{ timeout: 5_000 },
|
||||
);
|
||||
expect((await lstat(path)).isDirectory()).toBe(true);
|
||||
expect(await removeStaleStoreFileLock(path)).toBe(true);
|
||||
const successor = await createStoreFileLock(path);
|
||||
try {
|
||||
expect(await removeStaleStoreFileLock(path)).toBe(false);
|
||||
} finally {
|
||||
await successor.release();
|
||||
}
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { access, realpath, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("test temporary directory ownership", { concurrent: false }, () => {
|
||||
let completedDirectory: string | undefined;
|
||||
|
||||
it("creates a canonical directory owned by the current test", async () => {
|
||||
const directory = await createTestTempDirectory("rea-owned-temp-");
|
||||
completedDirectory = directory;
|
||||
|
||||
expect(directory).toBe(await realpath(directory));
|
||||
expect(dirname(directory)).toBe(await realpath(tmpdir()));
|
||||
await writeFile(join(directory, "nested.txt"), "owned");
|
||||
});
|
||||
|
||||
it("removes the prior test directory after that test finishes", async () => {
|
||||
const directory = completedDirectory;
|
||||
if (directory === undefined)
|
||||
throw new Error("Prior test did not create a directory");
|
||||
await expect(access(directory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["", "../escape-", "/absolute-", "missing-dash"])(
|
||||
"rejects unsafe prefix %j",
|
||||
async (prefix) => {
|
||||
await expect(createTestTempDirectory(prefix)).rejects.toThrow(TypeError);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -3,27 +3,22 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { classifyRoot } from "../../../src/application/ArtifactInventory/classify.js";
|
||||
import { classifyRoot } from "../../../src/artifacts/inventory/classify.js";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("ZIP signature detection", () => {
|
||||
it.each([
|
||||
[0x03, 0x04, true],
|
||||
[0x05, 0x06, true],
|
||||
[0x07, 0x08, true],
|
||||
[0x03, 0x06, false],
|
||||
[0x03, 0x08, false],
|
||||
[0x05, 0x04, false],
|
||||
[0x05, 0x08, false],
|
||||
[0x07, 0x04, false],
|
||||
[0x07, 0x06, false],
|
||||
{ signature: [0x50, 0x4b, 0x05, 0x06], archive: true },
|
||||
{ signature: [0x50, 0x4b, 0x03, 0x06], archive: false },
|
||||
{ signature: [0x50, 0x4b, 0x03, 0x04], archive: true },
|
||||
{ signature: [0x50, 0x4b, 0x07, 0x08], archive: true },
|
||||
] as const)(
|
||||
"classifies PK %i %i with archive signature %s",
|
||||
async (third, fourth, archive) => {
|
||||
"routes representative ZIP signature $signature through inventory and target parsing",
|
||||
async ({ signature, archive }) => {
|
||||
const root = await createTestTempDirectory("rea-zip-signature-");
|
||||
const path = join(root, "input");
|
||||
await writeFile(path, Buffer.from([0x50, 0x4b, third, fourth]));
|
||||
await writeFile(path, Buffer.from(signature));
|
||||
expect(await classifyRoot(path, false)).toBe(archive ? "zip" : "file");
|
||||
const target = await parseBinaryTarget(path);
|
||||
if (archive)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it as test, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { access } from "node:fs/promises";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "../../../src/contracts/android/androidToolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
@@ -92,8 +94,15 @@ it("publishes and executes all APK contracts with inline Evidence and no active
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = await client.listTools();
|
||||
const wireTools = new Map(advertised.tools.map((tool) => [tool.name, tool]));
|
||||
for (const contract of ANDROID_TOOL_CONTRACTS) {
|
||||
const wire = advertised.tools.find((tool) => tool.name === contract.name);
|
||||
const wire = wireTools.get(contract.name);
|
||||
if (wire === undefined || wire.outputSchema === undefined)
|
||||
throw new Error(`Missing advertised output schema for ${contract.name}`);
|
||||
const validateOutput = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(z.record(z.string(), z.unknown()).parse(wire.outputSchema));
|
||||
expect(wire?.annotations).toMatchObject(contract.annotations);
|
||||
expect(contract.effects).toMatchObject({
|
||||
mutatesTarget: false,
|
||||
@@ -120,6 +129,7 @@ it("publishes and executes all APK contracts with inline Evidence and no active
|
||||
arguments: input,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(validateOutput(response.structuredContent)).toBe(true);
|
||||
const result = contract.outputSchema.parse(response.structuredContent);
|
||||
const evidence = parseEvidence(result.evidence);
|
||||
expect(result.result).toEqual(evidence.normalized_result);
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { createBinarySession } from "../../../src/composition/binary.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
import {
|
||||
artifactParentPaths,
|
||||
writeOrderedZip,
|
||||
} from "../../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("returns correct child-first ZIP containment through MCP inspection", async () => {
|
||||
const root = await createTestTempDirectory("rea-entry-order-mcp-");
|
||||
const archive = join(root, "child-first.zip");
|
||||
await writeOrderedZip(archive, ["pkg/sub/data.txt", "pkg/sub/", "pkg/"]);
|
||||
const configured = parseConfig({});
|
||||
if (!configured.ok) throw configured.error;
|
||||
const session = createBinarySession(configured.value);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "entry-order-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
expect(
|
||||
(
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
})
|
||||
).isError,
|
||||
).not.toBe(true);
|
||||
const called = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
|
||||
);
|
||||
const substep = inspection.substeps[0];
|
||||
if (substep === undefined) throw new Error("Missing inventory Evidence");
|
||||
const inventory = artifactInventoryResultSchema.parse(
|
||||
substep.evidence.normalized_result,
|
||||
);
|
||||
expect(artifactParentPaths(inventory)).toEqual({
|
||||
".": null,
|
||||
pkg: ".",
|
||||
"pkg/sub": "pkg",
|
||||
"pkg/sub/data.txt": "pkg/sub",
|
||||
});
|
||||
expect(inspection.coverage.status).toBe("complete-within-substeps");
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
@@ -5,8 +5,6 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { createBinarySession } from "../../../src/composition/binary.js";
|
||||
import { keyedArchiveResultSchema } from "../../../src/domain/apple/keyedArchive.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -71,25 +69,19 @@ it("inspects a standalone keyed archive through MCP with original object identit
|
||||
}
|
||||
});
|
||||
|
||||
it("returns every artifact occurrence in one MCP call", async () => {
|
||||
it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-inline-");
|
||||
const archive = join(directory, "many.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
const fileCount = 520;
|
||||
for (let index = 0; index < fileCount; index += 1) {
|
||||
for (let index = 0; index < fileCount; index += 1)
|
||||
await writer.add(
|
||||
`files/${String(index)}.txt`,
|
||||
new TextReader(`file-${String(index)}`),
|
||||
);
|
||||
}
|
||||
await writeFile(archive, await writer.close());
|
||||
|
||||
const configured = parseConfig({
|
||||
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
|
||||
});
|
||||
expect(configured.ok).toBe(true);
|
||||
if (!configured.ok) throw configured.error;
|
||||
const session = createBinarySession(configured.value);
|
||||
const session = createTestBinarySession(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "artifact-inline-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
@@ -102,43 +94,6 @@ it("returns every artifact occurrence in one MCP call", async () => {
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).toContain("inspect_artifact");
|
||||
expect(names).toContain("inspect_asset_catalog");
|
||||
expect(names).not.toContain("inventory_artifact");
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.isError).not.toBe(true);
|
||||
const capabilities = z
|
||||
.object({
|
||||
result: z.object({
|
||||
capabilities: z.array(
|
||||
z.object({
|
||||
operation: z.string(),
|
||||
available: z.boolean(),
|
||||
reason: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.parse(status.structuredContent).result.capabilities;
|
||||
expect(capabilities.map(({ operation }) => operation)).not.toContain(
|
||||
"inventory_artifact",
|
||||
);
|
||||
expect(
|
||||
capabilities.find(
|
||||
({ operation }) => operation === "inspect_asset_catalog",
|
||||
),
|
||||
).toMatchObject(
|
||||
process.platform === "darwin"
|
||||
? { available: true, reason: null }
|
||||
: {
|
||||
available: false,
|
||||
reason: "Apple asset catalogs require macOS assetutil.",
|
||||
},
|
||||
);
|
||||
const result = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {},
|
||||
@@ -157,23 +112,14 @@ it("returns every artifact occurrence in one MCP call", async () => {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
observations: z.array(z.unknown()),
|
||||
derived_relationships: z.array(z.unknown()),
|
||||
hypotheses: z.array(z.unknown()),
|
||||
unexplored_branches: z.array(z.unknown()),
|
||||
next_probes: z.array(z.unknown()),
|
||||
})
|
||||
.parse(
|
||||
z.object({ result: z.unknown() }).parse(result.structuredContent)
|
||||
.result,
|
||||
);
|
||||
const occurrences =
|
||||
inspection.substeps[0]?.evidence.normalized_result.occurrences;
|
||||
if (occurrences === undefined)
|
||||
throw new Error("inspection omitted the artifact inventory");
|
||||
expect(occurrences).toHaveLength(fileCount + 1);
|
||||
expect(inspection.observations.length).toBeGreaterThan(0);
|
||||
expect(inspection.derived_relationships.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
inspection.substeps[0]?.evidence.normalized_result.occurrences,
|
||||
).toHaveLength(fileCount + 1);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from "zod";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { webPageInspectionSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
@@ -190,6 +191,40 @@ const verifySessionAndComparisonTools = async (
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: { overall_status: "unknown" },
|
||||
});
|
||||
const parsedCapture = webPageInspectionSchema.parse(capture);
|
||||
const socket = parsedCapture.network.websocket_events.find(
|
||||
(event) => event.payload_shape?.json_shape != null,
|
||||
);
|
||||
const payload = socket?.payload_shape;
|
||||
if (socket === undefined || payload == null || payload.json_shape === null)
|
||||
throw new Error("Missing deep WebSocket JSON shape fixture");
|
||||
const malformedCapture = {
|
||||
...parsedCapture,
|
||||
network: {
|
||||
...parsedCapture.network,
|
||||
websocket_events: [
|
||||
{
|
||||
...socket,
|
||||
payload_shape: {
|
||||
...payload,
|
||||
json_shape: {
|
||||
...payload.json_shape,
|
||||
properties: [{ path: "/event", types: [42], observations: 1 }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const malformedComparison = await connected.client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: {
|
||||
before: { inspection: malformedCapture },
|
||||
after: { inspection: capture },
|
||||
},
|
||||
});
|
||||
expect(malformedComparison.isError).toBe(true);
|
||||
expect(JSON.stringify(malformedComparison.content)).toContain("types");
|
||||
const incompleteComparison = await connected.client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: { before: { inspection: capture } },
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const analysis = {
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
};
|
||||
|
||||
describe("MCP server composition", () => {
|
||||
mcpTest("does not advertise unavailable session tools", async ({ mcp }) => {
|
||||
const server = createServer(analysis);
|
||||
const client = await mcp.connect(server, {
|
||||
name: "composition-test",
|
||||
version: "1.0.0",
|
||||
});
|
||||
expect(client.getInstructions()).not.toContain("open_binary");
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).not.toContain("compare_managed_members");
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { ElectronActiveObservationPort } from "../../../src/application/javascript/ElectronActiveObservationPort.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
@@ -270,12 +271,18 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const analyzed = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root },
|
||||
});
|
||||
const progress: number[] = [];
|
||||
const analyzed = await client.callTool(
|
||||
{
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root },
|
||||
},
|
||||
{ onprogress: (update) => progress.push(update.progress) },
|
||||
);
|
||||
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
expect(progress[0]).toBe(0);
|
||||
expect(progress.at(-1)).toBe(1);
|
||||
const projected = z
|
||||
.object({
|
||||
evidence_id: z.string(),
|
||||
@@ -314,6 +321,9 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
expect(projected.result.graph.nodes.length).toBeGreaterThan(0);
|
||||
expect(projected.result.semantic_graph.nodes.length).toBeGreaterThan(0);
|
||||
expect(projected.evidence.operation).toBe("analyze_javascript_application");
|
||||
const direct = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!direct.ok) throw direct.error;
|
||||
expect(projected.evidence_id).toBe(direct.value.evidence_id);
|
||||
});
|
||||
|
||||
const evidenceFor = (value: unknown) => {
|
||||
|
||||
+33
-144
@@ -1,123 +1,18 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { PROCEDURES, inventory } from "./enhancedToolsHarness.js";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: "return 0;",
|
||||
assembly: [],
|
||||
comments: [],
|
||||
callers: [],
|
||||
callees: [],
|
||||
incoming_references: [],
|
||||
outgoing_references: [],
|
||||
referenced_strings: [],
|
||||
referenced_names: [],
|
||||
basic_blocks: [],
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
afterEach(closeEnhancedToolResources);
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("rejects incomplete function dossiers at the application boundary", async () => {
|
||||
describe("analyze_function MCP producer validation", () => {
|
||||
it("rejects an incomplete function dossier", async () => {
|
||||
const client = await connect({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
observed({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
pseudocode: { text: "plausible but incomplete" },
|
||||
}),
|
||||
@@ -127,46 +22,40 @@ describe("enhanced MCP tools", () => {
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "0x1" },
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
expect(text?.type === "text" ? text.text : "").toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
expect(result.content).toContainEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects deceptive function dossier collection metadata", async () => {
|
||||
const malformedPort = fixturePort();
|
||||
it("rejects a malformed collection in an otherwise complete dossier", async () => {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_, options) => {
|
||||
const result = await malformedPort.execute(name, arguments_, options);
|
||||
if (!result.ok || name !== "analyze_function") return result;
|
||||
const dossier = result.value.result;
|
||||
if (
|
||||
typeof dossier !== "object" ||
|
||||
dossier === null ||
|
||||
Array.isArray(dossier)
|
||||
)
|
||||
return result;
|
||||
return ok({
|
||||
...dossier,
|
||||
comments: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 1,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
});
|
||||
},
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
observed({
|
||||
...dossier,
|
||||
comments: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 1,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "0x1" },
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
expect(text?.type === "text" ? text.text : "").toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
expect(result.content).toContainEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,18 @@ afterEach(closeEnhancedToolResources);
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("returns Evidence IDs and a complete call path", async () => {
|
||||
const client = await connect();
|
||||
const client = await connect({
|
||||
execute: async (_name, arguments_) => {
|
||||
const procedure = arguments_.procedure;
|
||||
return ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "trace_call_path",
|
||||
arguments: {
|
||||
|
||||
@@ -1,136 +1,13 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { PROCEDURES, emptyBounded, inventory } from "./enhancedToolsHarness.js";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "search_strings":
|
||||
case "search_procedures":
|
||||
return Promise.resolve(ok(inventory({ "0x1": "needle" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
afterEach(closeEnhancedToolResources);
|
||||
|
||||
describe("enhanced MCP input validation", () => {
|
||||
it("lets the SDK reject misspelled tool inputs", async () => {
|
||||
const client = await connect();
|
||||
const client = await connect({ execute: () => Promise.resolve(ok([])) });
|
||||
const valid = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle" },
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
export const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
@@ -20,119 +19,9 @@ export const PROCEDURES = {
|
||||
export const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
export const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
export const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
export const connect = async (
|
||||
analysis: AnalysisOperationPort = fixturePort(),
|
||||
) => {
|
||||
export const connect = async (analysis: AnalysisOperationPort) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
|
||||
@@ -124,28 +124,6 @@ describe("MCP runtime errors", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("starts the core transport when optional providers fail to load", async () => {
|
||||
const output: string[] = [];
|
||||
let serveCalls = 0;
|
||||
expect(
|
||||
await run(
|
||||
dependencies({
|
||||
serve: () => {
|
||||
serveCalls += 1;
|
||||
return { close: () => Promise.resolve() };
|
||||
},
|
||||
output,
|
||||
shutdown: [],
|
||||
exitCodes: [],
|
||||
loadOptionalProviders: () =>
|
||||
Promise.reject(new Error("synthetic optional import failure")),
|
||||
}),
|
||||
),
|
||||
).toBe(0);
|
||||
expect(serveCalls).toBe(1);
|
||||
expect(output).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports shutdown failure and sets a failing exit code", async () => {
|
||||
const output: string[] = [];
|
||||
const shutdown: Array<() => void> = [];
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { RuntimeDependencies } from "../../../src/main/types.js";
|
||||
import { createRuntimeState } from "../../../src/main/state.js";
|
||||
|
||||
describe("runtime configuration reload", () => {
|
||||
it("applies a valid configuration reload", () => {
|
||||
it("applies valid reloads and keeps the last valid config after an invalid reload", () => {
|
||||
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
|
||||
const runtime = setupReload(env);
|
||||
|
||||
@@ -16,16 +16,11 @@ describe("runtime configuration reload", () => {
|
||||
runtime.reload();
|
||||
|
||||
expect(runtime.state.currentConfig.logLevel).toBe("debug");
|
||||
});
|
||||
|
||||
it("retains the last valid configuration after an invalid reload", () => {
|
||||
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
|
||||
const runtime = setupReload(env);
|
||||
|
||||
env.REA_LOG_LEVEL = "invalid";
|
||||
runtime.reload();
|
||||
|
||||
expect(runtime.state.currentConfig.logLevel).toBe("info");
|
||||
expect(runtime.state.currentConfig.logLevel).toBe("debug");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -14,16 +15,21 @@ import type { BinarySession } from "../../../src/application/binary/BinarySessio
|
||||
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import { SessionProviderRouter } from "../../../src/application/binary/SessionProviderRouter.js";
|
||||
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
type ManagedOutputAssertion = Awaited<ReturnType<typeof createOutputAssertion>>;
|
||||
|
||||
it("runs every managed static inspection independently of an active native target", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-independent-mcp-",
|
||||
);
|
||||
const path = join(directory, "fixture.dll");
|
||||
const otherPath = join(directory, "other-fixture.dll");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
await writeFile(otherPath, buildManagedPeFixture({ methodName: "Other" }));
|
||||
const session = composeBinarySession(
|
||||
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
|
||||
new ManagedStaticProvider(),
|
||||
@@ -50,6 +56,12 @@ it("runs every managed static inspection independently of an active native targe
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const managedMembersTool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "inspect_managed_members",
|
||||
);
|
||||
expect(managedMembersTool?.inputSchema).toMatchObject({
|
||||
additionalProperties: false,
|
||||
});
|
||||
const artifact = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
@@ -63,6 +75,11 @@ it("runs every managed static inspection independently of an active native targe
|
||||
subject: { local_path: path, format: "pe" },
|
||||
},
|
||||
});
|
||||
const misspelledPath = await client.callTool({
|
||||
name: "inspect_managed_members",
|
||||
arguments: { pth: otherPath },
|
||||
});
|
||||
expect(misspelledPath.isError).toBe(true);
|
||||
const invalidSelection = await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
arguments: { path: join(directory, "missing.dll") },
|
||||
@@ -78,6 +95,24 @@ it("runs every managed static inspection independently of an active native targe
|
||||
subject: { local_path: path, format: "pe" },
|
||||
},
|
||||
});
|
||||
const otherArtifact = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
arguments: { path: otherPath },
|
||||
}),
|
||||
);
|
||||
expect(otherArtifact).toMatchObject({
|
||||
evidence: { subject: { local_path: otherPath, format: "pe" } },
|
||||
});
|
||||
const reusedOtherTarget = structured(
|
||||
await client.callTool({ name: "inspect_managed_members", arguments: {} }),
|
||||
);
|
||||
expect(reusedOtherTarget).toMatchObject({
|
||||
evidence: {
|
||||
operation: "inspect_managed_members",
|
||||
subject: { local_path: otherPath, format: "pe" },
|
||||
},
|
||||
});
|
||||
const boundaries = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_native_boundaries",
|
||||
@@ -126,9 +161,19 @@ it("opens a managed PE and executes the managed static provider through MCP", as
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verifyManagedCatalogAndNativeWorkflow(client, session);
|
||||
const members = await inspectManagedStaticWorkflow(client, path);
|
||||
await verifyManagedComparisonAndReconstruction(client, members, rightPath);
|
||||
const assertOutput = await createOutputAssertion(client);
|
||||
await verifyManagedCatalogAndNativeWorkflow(client, session, assertOutput);
|
||||
const members = await inspectManagedStaticWorkflow(
|
||||
client,
|
||||
path,
|
||||
assertOutput,
|
||||
);
|
||||
await verifyManagedComparisonAndReconstruction(
|
||||
client,
|
||||
members,
|
||||
rightPath,
|
||||
assertOutput,
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
await session.close();
|
||||
@@ -138,9 +183,9 @@ it("opens a managed PE and executes the managed static provider through MCP", as
|
||||
const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
outputAssertion: ManagedOutputAssertion,
|
||||
): Promise<void> => {
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).toEqual(
|
||||
expect(outputAssertion.names).toEqual(
|
||||
expect.arrayContaining([
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
@@ -166,6 +211,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
},
|
||||
}),
|
||||
);
|
||||
await outputAssertion.assert("verify_managed_native_boundaries", verified);
|
||||
expect(verified).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
result: {
|
||||
@@ -195,6 +241,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
const inspectManagedStaticWorkflow = async (
|
||||
client: Client,
|
||||
path: string,
|
||||
outputAssertion: ManagedOutputAssertion,
|
||||
): Promise<Record<string, unknown>> => {
|
||||
const inspected = structured(
|
||||
await client.callTool({
|
||||
@@ -202,6 +249,7 @@ const inspectManagedStaticWorkflow = async (
|
||||
arguments: { path },
|
||||
}),
|
||||
);
|
||||
await outputAssertion.assert("inspect_managed_artifact", inspected);
|
||||
expect(inspected).toMatchObject({
|
||||
result: {
|
||||
classification: { status: "managed", runtime_family: "modern-dotnet" },
|
||||
@@ -221,6 +269,11 @@ const inspectManagedStaticWorkflow = async (
|
||||
}),
|
||||
),
|
||||
);
|
||||
await outputAssertion.assert("inspect_managed_members", {
|
||||
result: members.normalized_result,
|
||||
evidence_id: members.evidence_id,
|
||||
evidence: members,
|
||||
});
|
||||
expect(members).toMatchObject({
|
||||
operation: "inspect_managed_members",
|
||||
provider: { id: "rea-dotnet-static" },
|
||||
@@ -242,6 +295,7 @@ const inspectManagedStaticWorkflow = async (
|
||||
arguments: { path },
|
||||
}),
|
||||
);
|
||||
await outputAssertion.assert("inspect_managed_native_boundaries", boundaries);
|
||||
expect(boundaries).toMatchObject({
|
||||
result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
@@ -292,6 +346,7 @@ const verifyManagedComparisonAndReconstruction = async (
|
||||
client: Client,
|
||||
members: Record<string, unknown>,
|
||||
rightPath: string,
|
||||
outputAssertion: ManagedOutputAssertion,
|
||||
): Promise<void> => {
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
@@ -316,6 +371,11 @@ const verifyManagedComparisonAndReconstruction = async (
|
||||
}),
|
||||
),
|
||||
);
|
||||
await outputAssertion.assert("compare_managed_members", {
|
||||
result: compared.normalized_result,
|
||||
evidence_id: compared.evidence_id,
|
||||
evidence: compared,
|
||||
});
|
||||
expect(compared).toMatchObject({
|
||||
operation: "compare_managed_members",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
@@ -394,6 +454,31 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
|
||||
const createOutputAssertion = async (client: Client) => {
|
||||
const tools = (await client.listTools()).tools;
|
||||
const ajv = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
});
|
||||
return {
|
||||
names: tools.map(({ name }) => name),
|
||||
assert: (
|
||||
name: Parameters<typeof toolContract>[0],
|
||||
output: Record<string, unknown>,
|
||||
): void => {
|
||||
const contract = toolContract(name);
|
||||
const wire = tools.find((tool) => tool.name === name);
|
||||
if (wire?.outputSchema === undefined)
|
||||
throw new Error(`Missing advertised output schema for ${name}`);
|
||||
const valid = ajv.compile(
|
||||
z.record(z.string(), z.unknown()).parse(wire.outputSchema),
|
||||
);
|
||||
expect(valid(output), `${name} advertised output`).toBe(true);
|
||||
expect(contract.outputSchema.safeParse(output).success).toBe(true);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const inlineEvidence = (
|
||||
value: Readonly<Record<string, unknown>>,
|
||||
): Record<string, unknown> => {
|
||||
|
||||
@@ -1,25 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MCP_STARTUP_POLICY } from "../../../src/mcpStartupPolicy.js";
|
||||
import {
|
||||
createEsmModuleProfileCollector,
|
||||
parseLinuxVmRssBytes,
|
||||
} from "../../../scripts/lib/mcp-startup-probe.mjs";
|
||||
|
||||
describe("MCP startup policy", () => {
|
||||
it("preserves headroom beneath the configured Codex timeout", () => {
|
||||
const codexTimeoutMs =
|
||||
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds * 1_000;
|
||||
|
||||
expect(MCP_STARTUP_POLICY.initializeBudgetMs).toBeLessThan(codexTimeoutMs);
|
||||
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBeLessThan(
|
||||
codexTimeoutMs,
|
||||
);
|
||||
expect(MCP_STARTUP_POLICY.doctorDeadlineMs).toBeGreaterThanOrEqual(
|
||||
codexTimeoutMs,
|
||||
);
|
||||
});
|
||||
|
||||
it("parses Linux resident memory without accepting other fields", () => {
|
||||
expect(
|
||||
parseLinuxVmRssBytes("Name:\tnode\nVmRSS:\t 12345 kB\nThreads:\t7\n"),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../../../src/contracts/native/nativeToolContracts.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const provider = {
|
||||
id: "fixture-native",
|
||||
name: "Fixture native provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
const plistResult = {
|
||||
format: "xml",
|
||||
value: {},
|
||||
bundle: {
|
||||
identifier: null,
|
||||
executable: null,
|
||||
name: null,
|
||||
version: null,
|
||||
short_version: null,
|
||||
},
|
||||
source_path: "/Applications/Fixture.app/Contents/Info.plist",
|
||||
provenance: [],
|
||||
limitations: [],
|
||||
};
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
const connect = async (
|
||||
execute: AnalysisOperationPort["execute"],
|
||||
): Promise<Client> => {
|
||||
const server = createServer({ execute });
|
||||
const client = new Client({ name: "native-contract-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
describe("native MCP input contracts", () => {
|
||||
it("rejects a misspelled plist path before dispatch and preserves omission", async () => {
|
||||
const calls: Array<{
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
}> = [];
|
||||
const client = await connect((operation, parameters) => {
|
||||
calls.push({ operation, parameters });
|
||||
return Promise.resolve(
|
||||
ok(createAnalysisExecution(plistResult, provider)),
|
||||
);
|
||||
});
|
||||
|
||||
const tools = new Map(
|
||||
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
|
||||
);
|
||||
for (const nativeContract of NATIVE_TOOL_CONTRACTS)
|
||||
expect(tools.get(nativeContract.name)?.inputSchema).toHaveProperty(
|
||||
"additionalProperties",
|
||||
false,
|
||||
);
|
||||
|
||||
const contract = NATIVE_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "inspect_plist",
|
||||
);
|
||||
const advertised = tools.get("inspect_plist");
|
||||
if (contract === undefined || advertised === undefined)
|
||||
throw new Error("inspect_plist was not registered");
|
||||
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(advertised.inputSchema);
|
||||
const typoInput = { pth: "/tmp/Other.plist" };
|
||||
expect(validate(typoInput)).toBe(false);
|
||||
expect(contract.inputSchema.safeParse(typoInput).success).toBe(false);
|
||||
expect(validate({})).toBe(true);
|
||||
expect(contract.inputSchema.safeParse({}).success).toBe(true);
|
||||
|
||||
const defaulted = await client.callTool({
|
||||
name: "inspect_plist",
|
||||
arguments: {},
|
||||
});
|
||||
expect(defaulted.isError).not.toBe(true);
|
||||
expect(calls[0]).toEqual({ operation: "inspect_plist", parameters: {} });
|
||||
|
||||
const selectedPath = "/tmp/Other.plist";
|
||||
const explicit = await client.callTool({
|
||||
name: "inspect_plist",
|
||||
arguments: { path: selectedPath },
|
||||
});
|
||||
expect(explicit.isError).not.toBe(true);
|
||||
expect(calls[1]).toEqual({
|
||||
operation: "inspect_plist",
|
||||
parameters: { path: selectedPath },
|
||||
});
|
||||
|
||||
const beforeTypo = calls.length;
|
||||
const rejected = await client.callTool({
|
||||
name: "inspect_plist",
|
||||
arguments: typoInput,
|
||||
});
|
||||
expect(rejected.isError).toBe(true);
|
||||
expect(calls).toHaveLength(beforeTypo);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
@@ -11,52 +10,6 @@ import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const VALID_INPUTS: Readonly<
|
||||
Record<string, Readonly<Record<string, JsonValue>>>
|
||||
> = {
|
||||
annotate_native_function: { procedure: "0x1000", name: "entry" },
|
||||
inspect_native_load_image: {},
|
||||
address_name: {},
|
||||
inspect_native_instruction: { address: "0x1000" },
|
||||
resolve_native_call_targets: { address: "0x1000" },
|
||||
inspect_native_data_type: { type: "/Missing" },
|
||||
comment: {},
|
||||
current_address: {},
|
||||
current_procedure: {},
|
||||
current_document: {},
|
||||
goto_address: { address: "0x1000" },
|
||||
inline_comment: {},
|
||||
list_bookmarks: {},
|
||||
list_documents: {},
|
||||
list_names: {},
|
||||
list_procedures: {},
|
||||
list_segments: {},
|
||||
list_strings: {},
|
||||
next_address: {},
|
||||
prev_address: {},
|
||||
procedure_address: { procedure: "main" },
|
||||
procedure_assembly: { procedure: "main" },
|
||||
procedure_callees: { procedure: "main" },
|
||||
procedure_callers: { procedure: "main" },
|
||||
procedure_info: { procedure: "main" },
|
||||
read_function_instructions: { procedure: "main" },
|
||||
read_bytes: { address: "0x1000", length: 4 },
|
||||
address_to_file_offset: { address: "0x1000" },
|
||||
procedure_references: { procedure: "main" },
|
||||
procedure_pseudo_code: { procedure: "main" },
|
||||
resolve_containing_procedure: { address: "0x1000" },
|
||||
search_procedures: { pattern: "main" },
|
||||
search_strings: { pattern: "hello" },
|
||||
set_address_name: { address: "0x1000", name: "entry" },
|
||||
set_addresses_names: { names: { "0x1000": "entry" } },
|
||||
set_bookmark: { address: "0x1000" },
|
||||
set_comment: { address: "0x1000", comment: "entry point" },
|
||||
set_current_document: { document: "fixture" },
|
||||
set_inline_comment: { address: "0x1000", comment: "entry point" },
|
||||
unset_bookmark: { address: "0x1000" },
|
||||
xrefs: {},
|
||||
};
|
||||
|
||||
interface Invocation {
|
||||
readonly name: string;
|
||||
readonly arguments_: Readonly<Record<string, JsonValue>>;
|
||||
@@ -128,204 +81,54 @@ const connect = async (analysis: AnalysisOperationPort) => {
|
||||
return client;
|
||||
};
|
||||
|
||||
const inventory: JsonValue = [];
|
||||
|
||||
const outputFor = (name: string): JsonValue => {
|
||||
if (name === "annotate_native_function") {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
return {
|
||||
annotations: {
|
||||
address: dossier.procedure.address,
|
||||
name: dossier.procedure.name,
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
},
|
||||
dossier,
|
||||
effects: {
|
||||
scope: "session-analysis-database",
|
||||
source_bytes_modified: false,
|
||||
persists_after_close: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (name === "inspect_native_load_image")
|
||||
return {
|
||||
status: "unsupported",
|
||||
reason: "Fixture provider has no load-image verifier",
|
||||
observations: {
|
||||
executable_format: "ELF",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x0",
|
||||
default_address_space: "ram",
|
||||
source_files: [],
|
||||
mappings: [],
|
||||
relocations: [],
|
||||
entry_context: [],
|
||||
entry_points: [],
|
||||
},
|
||||
limitations: ["Transport fixture only"],
|
||||
};
|
||||
if (name === "inspect_native_instruction")
|
||||
return {
|
||||
address: "0x1000",
|
||||
status: "decoded",
|
||||
procedure: "0x1000",
|
||||
architecture: "x86:LE:64:default",
|
||||
mode: "default",
|
||||
bytes: "c3",
|
||||
length: 1,
|
||||
mnemonic: "RET",
|
||||
raw_disassembly: "RET",
|
||||
operands: [],
|
||||
flow: {
|
||||
kind: "terminal",
|
||||
conditional: false,
|
||||
computed: false,
|
||||
direct_destinations: [],
|
||||
},
|
||||
references: [],
|
||||
limitations: ["Provider decoder observation"],
|
||||
};
|
||||
if (name === "resolve_native_call_targets")
|
||||
return {
|
||||
call_site: "0x1000",
|
||||
procedure: "0x1000",
|
||||
status: "not-call",
|
||||
mechanism: "unavailable",
|
||||
targets: [],
|
||||
limitations: [],
|
||||
};
|
||||
if (name === "inspect_native_data_type")
|
||||
return {
|
||||
status: "unavailable",
|
||||
reason: "Type absent",
|
||||
id: null,
|
||||
name: null,
|
||||
kind: "unavailable",
|
||||
source: "analysis-database",
|
||||
source_archive: null,
|
||||
address: null,
|
||||
size_bytes: null,
|
||||
alignment_bytes: null,
|
||||
packing_enabled: null,
|
||||
referenced_type: null,
|
||||
array_count: null,
|
||||
array_stride_bytes: null,
|
||||
fields: [],
|
||||
members: [],
|
||||
total_fields: 0,
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
};
|
||||
if (["list_procedures", "list_names", "list_strings"].includes(name))
|
||||
return inventory;
|
||||
if (["address_name", "comment", "inline_comment"].includes(name)) return null;
|
||||
if (["procedure_callees", "procedure_callers", "xrefs"].includes(name))
|
||||
return [];
|
||||
if (["list_bookmarks", "list_documents", "list_segments"].includes(name))
|
||||
return [];
|
||||
if (
|
||||
[
|
||||
"set_address_name",
|
||||
"set_bookmark",
|
||||
"set_comment",
|
||||
"set_inline_comment",
|
||||
"unset_bookmark",
|
||||
].includes(name)
|
||||
)
|
||||
return true;
|
||||
if (name === "set_addresses_names") return { "0x1000": true };
|
||||
if (["search_procedures", "search_strings"].includes(name)) return inventory;
|
||||
if (name === "procedure_info")
|
||||
return {
|
||||
name: "main",
|
||||
entrypoint: "0x1000",
|
||||
basicblock_count: 1,
|
||||
length: 4,
|
||||
signature: null,
|
||||
locals: [],
|
||||
};
|
||||
if (name === "resolve_containing_procedure")
|
||||
return {
|
||||
query_address: "0x1000",
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
};
|
||||
if (name === "read_function_instructions")
|
||||
return {
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
instructions: ["0x1000: ret"],
|
||||
limitations: ["Provider-specific instruction text."],
|
||||
};
|
||||
if (name === "read_bytes")
|
||||
return {
|
||||
address: "0x1000",
|
||||
requested_bytes: 4,
|
||||
returned_bytes: 4,
|
||||
bytes_hex: "c3c3c3c3",
|
||||
complete: true,
|
||||
};
|
||||
if (name === "address_to_file_offset")
|
||||
return { address: "0x1000", file_offset: 0 };
|
||||
if (name === "procedure_references")
|
||||
return {
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
direction: "outgoing",
|
||||
references: [],
|
||||
};
|
||||
return name.includes("address") ? "0x1000" : "fixture";
|
||||
};
|
||||
|
||||
describe("official Hopper proxy tools", () => {
|
||||
it("executes every handler and projects omitted Python optionals to null", async () => {
|
||||
describe("official tool input contracts", () => {
|
||||
it("rejects misspelled top-level inputs before dispatch and keeps record keys open", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
invocations.push({ name, arguments_ });
|
||||
return Promise.resolve(ok(outputFor(name)));
|
||||
return Promise.resolve(ok(null));
|
||||
},
|
||||
});
|
||||
|
||||
const { tools } = await client.listTools();
|
||||
const advertisedByName = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
|
||||
const result = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: VALID_INPUTS[contract.name],
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(advertisedByName.get(contract.name)?.inputSchema).toHaveProperty(
|
||||
"additionalProperties",
|
||||
false,
|
||||
);
|
||||
}
|
||||
const advertised = tools.find(({ name }) => name === "address_name");
|
||||
const recordTool = tools.find(({ name }) => name === "set_addresses_names");
|
||||
if (advertised === undefined || recordTool === undefined)
|
||||
throw new Error("Official tools were not advertised");
|
||||
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "annotate_native_function")
|
||||
?.arguments_,
|
||||
).toEqual({ procedure: "0x1000", name: "entry" });
|
||||
expect(invocations.map(({ name }) => name)).toEqual(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const validateAddressName = ajv.compile(advertised.inputSchema);
|
||||
const validateRecordInput = ajv.compile(recordTool.inputSchema);
|
||||
const typoInput = { adress: "0x1234" };
|
||||
expect(advertised.inputSchema).toHaveProperty(
|
||||
"additionalProperties",
|
||||
false,
|
||||
);
|
||||
expect(validateAddressName(typoInput)).toBe(false);
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "address_name")?.arguments_,
|
||||
).toEqual({
|
||||
document: null,
|
||||
address: null,
|
||||
});
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "search_procedures")?.arguments_,
|
||||
).toEqual({
|
||||
pattern: "main",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
document: null,
|
||||
});
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "search_strings")?.arguments_,
|
||||
).toEqual({
|
||||
pattern: "hello",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
document: null,
|
||||
});
|
||||
});
|
||||
OFFICIAL_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "address_name",
|
||||
)?.inputSchema.safeParse(typoInput).success,
|
||||
).toBe(false);
|
||||
expect(validateRecordInput({ names: { "0x1000": "entry" } })).toBe(true);
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "address_name",
|
||||
arguments: typoInput,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(invocations).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("official Hopper proxy tools", () => {
|
||||
it("returns stable safe MCP error content", async () => {
|
||||
const client = await connect({
|
||||
execute: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
|
||||
@@ -341,7 +144,7 @@ describe("official Hopper proxy tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("returns every procedure inline without caller-authored page calls", async () => {
|
||||
it("binds list_procedures and projects its omitted Python document option", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
@@ -367,6 +170,7 @@ describe("official Hopper proxy tools", () => {
|
||||
],
|
||||
});
|
||||
expect(invocations).toHaveLength(1);
|
||||
expect(invocations[0]?.name).toBe("list_procedures");
|
||||
expect(invocations[0]?.arguments_).toEqual({ document: null });
|
||||
expect(
|
||||
(await client.listTools()).tools.find(
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import {
|
||||
managedNativeVerificationInputSchema,
|
||||
managedNativeVerificationResultSchema,
|
||||
verifyManagedNativeBoundaries,
|
||||
} from "../../../src/domain/managed/managedNativeVerification.js";
|
||||
import { nativeUiResultSchema } from "../../../src/domain/native/nativeUiObservation.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
throw new Error("Expected a schema object");
|
||||
return value as Record<string, unknown>;
|
||||
};
|
||||
|
||||
it("advertises semantic output invariants and keeps producers aligned with Zod", async () => {
|
||||
const contracts = [
|
||||
toolContract("capture_native_ui_scenario"),
|
||||
toolContract("capture_process_scenario"),
|
||||
toolContract("verify_managed_native_boundaries"),
|
||||
];
|
||||
const server = new McpServer({
|
||||
name: "output-schema-semantics",
|
||||
version: "1",
|
||||
});
|
||||
const client = new Client({ name: "output-schema-semantics", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
for (const contract of contracts)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({ content: [] }),
|
||||
);
|
||||
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = new Map(
|
||||
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
|
||||
);
|
||||
const outputResultSchema = (name: (typeof contracts)[number]["name"]) => {
|
||||
const tool = advertised.get(name);
|
||||
if (tool?.outputSchema === undefined)
|
||||
throw new Error(`${name} output schema missing`);
|
||||
const outputSchema = record(tool.outputSchema);
|
||||
const result = record(record(outputSchema.properties).result);
|
||||
const standaloneResultSchema = z.record(z.string(), z.unknown()).parse({
|
||||
...result,
|
||||
...(typeof outputSchema.$schema === "string"
|
||||
? { $schema: outputSchema.$schema }
|
||||
: {}),
|
||||
...(outputSchema.$defs === undefined
|
||||
? {}
|
||||
: { $defs: outputSchema.$defs }),
|
||||
});
|
||||
return {
|
||||
result,
|
||||
validate: new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(standaloneResultSchema),
|
||||
};
|
||||
};
|
||||
|
||||
const native = outputResultSchema("capture_native_ui_scenario");
|
||||
const initial = record(record(native.result.properties).initial);
|
||||
const screenshotUnion = record(record(initial.properties).screenshot);
|
||||
const screenshotVariants = screenshotUnion.anyOf;
|
||||
if (!Array.isArray(screenshotVariants))
|
||||
throw new Error("Expected nullable screenshot schema");
|
||||
const screenshotProperties = record(
|
||||
record(screenshotVariants[0]).properties,
|
||||
);
|
||||
expect(record(screenshotProperties.base64).description).toContain(
|
||||
"PNG signature",
|
||||
);
|
||||
expect(record(screenshotProperties.sha256).description).toContain(
|
||||
"decoded PNG bytes",
|
||||
);
|
||||
const pngBytes = Buffer.from("not a PNG");
|
||||
const invalidScreenshot = {
|
||||
target_sha256: "a".repeat(64),
|
||||
initial: {
|
||||
window: {
|
||||
pid: 1,
|
||||
window_id: 1,
|
||||
executable: "app",
|
||||
launch_time: 0,
|
||||
title: "",
|
||||
},
|
||||
nodes: [],
|
||||
truncated: false,
|
||||
screenshot: {
|
||||
mime_type: "image/png",
|
||||
base64: pngBytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(pngBytes).digest("hex"),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
gaps: [],
|
||||
},
|
||||
steps: [],
|
||||
restore: "leave-as-is",
|
||||
limitations: [],
|
||||
};
|
||||
expect(native.validate(invalidScreenshot)).toBe(true);
|
||||
expect(nativeUiResultSchema.safeParse(invalidScreenshot).success).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
const process = outputResultSchema("capture_process_scenario");
|
||||
expect(process.result.description).toContain("canonical scenario");
|
||||
expect(process.result.description).toContain(
|
||||
"older input without an event journal",
|
||||
);
|
||||
const validCapture = processCaptureSchema.parse(
|
||||
EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
);
|
||||
expect(validCapture.event_journal).toEqual([]);
|
||||
expect(process.validate(validCapture)).toBe(true);
|
||||
expect(
|
||||
processCaptureSchema.safeParse(EMPTY_PROCESS_CAPTURE_EXAMPLE).success,
|
||||
).toBe(true);
|
||||
const invalidCapture = {
|
||||
...validCapture,
|
||||
manifest: {
|
||||
...validCapture.manifest,
|
||||
full_scenario_sha256: "0".repeat(64),
|
||||
},
|
||||
};
|
||||
expect(process.validate(invalidCapture)).toBe(true);
|
||||
expect(processCaptureSchema.safeParse(invalidCapture).success).toBe(false);
|
||||
|
||||
const managed = outputResultSchema("verify_managed_native_boundaries");
|
||||
expect(managed.result.description).toContain(
|
||||
"accepted plus unsupported equals total",
|
||||
);
|
||||
const validVerification = verifyManagedNativeBoundaries(
|
||||
managedNativeVerificationInputSchema.parse(
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
|
||||
),
|
||||
);
|
||||
expect(managed.validate(validVerification)).toBe(true);
|
||||
const invalidVerification = structuredClone(validVerification);
|
||||
invalidVerification.summary.verified += 1;
|
||||
expect(managed.validate(invalidVerification)).toBe(true);
|
||||
expect(
|
||||
managedNativeVerificationResultSchema.safeParse(invalidVerification)
|
||||
.success,
|
||||
).toBe(false);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
@@ -5,14 +5,14 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
|
||||
import {
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
INVESTIGATION_EXAMPLES,
|
||||
} from "../../../src/contracts/investigationExamples.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/process/processCaptureExample.js";
|
||||
import { findChangedBehavior } from "../../../src/domain/changedBehavior.js";
|
||||
import {
|
||||
createEvidence,
|
||||
|
||||
@@ -6,12 +6,12 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/process/processCaptureExample.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import type { ProcessTraceSpecification } from "../../../src/domain/processTraceComparison.js";
|
||||
import type { ProcessTraceSpecification } from "../../../src/domain/process/processTraceComparison.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AnalysisClient } from "../../../src/application/AnalysisProvider.j
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
|
||||
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createArtifactInspection } from "../../../src/domain/artifactInspection.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
@@ -57,6 +58,36 @@ describe("guided prompt completion from live analysis", () => {
|
||||
});
|
||||
|
||||
describe("guided prompt completion from investigation records", () => {
|
||||
it("completes process captures imported in the original v3 format", async () => {
|
||||
const session = createTestBinarySession(() => client([]));
|
||||
const {
|
||||
selected_executable_sha256: _selectedDigest,
|
||||
executable_identity: _identity,
|
||||
executable_sha256,
|
||||
...legacyManifest
|
||||
} = EMPTY_PROCESS_CAPTURE_EXAMPLE.manifest;
|
||||
const legacyCapture = {
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
manifest: { ...legacyManifest, executable_sha256 },
|
||||
};
|
||||
const evidence = createEvidence(undefined, fixtureProvider, {
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: legacyCapture,
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: fixtureEnvironment,
|
||||
});
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const completion = createPromptCompletionSource(session, session);
|
||||
|
||||
expect(
|
||||
await completion.complete("capture", evidence.evidence_id.slice(0, 8)),
|
||||
).toEqual([evidence.evidence_id]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("projects only validated typed identifiers from the evidence ledger", async () => {
|
||||
const session = createTestBinarySession(() => client([]));
|
||||
const invalidCapture = createEvidence(undefined, fixtureProvider, {
|
||||
|
||||
@@ -15,8 +15,8 @@ import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/process/processCaptureExample.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/server/sessionToolPolicies.js";
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -14,9 +15,10 @@ import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { probeProcessCaptureCapability } from "../../../src/application/ProcessHarness.js";
|
||||
import { probeProcessCaptureCapability } from "../../../src/process/capture/ProcessHarness.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
@@ -227,6 +229,37 @@ describe("target-free MCP workflow", () => {
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
describe("session filesystem path boundaries over MCP", () => {
|
||||
it("rejects relative snapshot and export paths with an absolute-path error", async () => {
|
||||
directory = await createTestTempDirectory("rea-mcp-path-boundary-");
|
||||
const { mcp, first } = await createSessionMcpHarness(
|
||||
directory,
|
||||
provider,
|
||||
resources,
|
||||
);
|
||||
|
||||
const exported = await mcp.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: "relative-bundle.json" },
|
||||
});
|
||||
expect(exported.isError, JSON.stringify(exported.content)).toBe(true);
|
||||
expect(JSON.stringify(exported.content)).toContain("absolute");
|
||||
|
||||
const opened = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: first },
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
|
||||
const closed = await mcp.callTool({
|
||||
name: "close_binary",
|
||||
arguments: { snapshot_path: "relative-analysis.json" },
|
||||
});
|
||||
expect(closed.isError, JSON.stringify(closed.content)).toBe(true);
|
||||
expect(JSON.stringify(closed.content)).toContain("absolute");
|
||||
await mcp.callTool({ name: "close_binary", arguments: {} });
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
describe("process residuals over MCP", () => {
|
||||
it("records process residuals linked to capture Evidence", async () => {
|
||||
if (!(await probeProcessCaptureCapability()).available) return;
|
||||
@@ -249,6 +282,21 @@ describe("process residuals over MCP", () => {
|
||||
},
|
||||
});
|
||||
expect(captured.isError, text(captured)).not.toBe(true);
|
||||
const contract = toolContract("capture_process_scenario");
|
||||
const wire = (await mcp.listTools()).tools.find(
|
||||
({ name }) => name === contract.name,
|
||||
);
|
||||
if (wire?.outputSchema === undefined)
|
||||
throw new Error("Missing process capture output schema");
|
||||
expect(
|
||||
new Ajv2020({ strict: false, validateFormats: false }).validate(
|
||||
z.record(z.string(), z.unknown()).parse(wire.outputSchema),
|
||||
captured.structuredContent,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
contract.outputSchema.safeParse(captured.structuredContent).success,
|
||||
).toBe(true);
|
||||
const listedUnknowns = await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { annotationsFromEffects } from "../../../src/contracts/toolEffects.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
describe("tool registration options", () => {
|
||||
it("generates the checked-in catalog from the SDK wire projection", async () => {
|
||||
const server = new McpServer({ name: "catalog-test", version: "0" });
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({
|
||||
content: [{ type: "text" as const, text: "catalog-only" }],
|
||||
isError: true as const,
|
||||
}),
|
||||
);
|
||||
const client = new Client({ name: "catalog-test", version: "0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = (await client.listTools()).tools.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
}));
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const tool = advertised.find(({ name }) => name === contract.name);
|
||||
expect(tool, contract.name).toBeDefined();
|
||||
expect(describesObject(tool?.inputSchema), contract.name).toBe(true);
|
||||
expect(describesObject(tool?.outputSchema), contract.name).toBe(true);
|
||||
expect(tool?.title?.trim().length, contract.name).toBeGreaterThan(0);
|
||||
expect(tool?.description?.trim().length, contract.name).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
expect(JSON.stringify(tool?.outputSchema), contract.name).not.toContain(
|
||||
'"result":{}',
|
||||
);
|
||||
expect(tool?.annotations, contract.name).toEqual(
|
||||
annotationsFromEffects(contract.effects),
|
||||
);
|
||||
expect(contract.examples.length, contract.name).toBeGreaterThan(0);
|
||||
for (const example of contract.examples) {
|
||||
expect(example.title.trim().length, contract.name).toBeGreaterThan(0);
|
||||
expect(
|
||||
contract.inputSchema.safeParse(example.input).success,
|
||||
`${contract.name}: ${example.title}`,
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
expect(tool?.inputSchema.examples, contract.name).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
);
|
||||
expect(
|
||||
missingPropertyDescriptions(tool?.inputSchema),
|
||||
contract.name,
|
||||
).toEqual([]);
|
||||
}
|
||||
expect(advertised).toEqual(
|
||||
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
})),
|
||||
);
|
||||
for (const [name, expected] of [
|
||||
["binary_session", { readOnlyHint: true, openWorldHint: false }],
|
||||
["read_bytes", { readOnlyHint: false, destructiveHint: false }],
|
||||
["set_comment", { readOnlyHint: false }],
|
||||
["unset_bookmark", { destructiveHint: true }],
|
||||
[
|
||||
"capture_process_scenario",
|
||||
{ readOnlyHint: false, openWorldHint: true },
|
||||
],
|
||||
["inspect_artifact", { readOnlyHint: false, openWorldHint: true }],
|
||||
["extract_artifact", { readOnlyHint: false, idempotentHint: false }],
|
||||
["compare_web_captures", { readOnlyHint: false, openWorldHint: false }],
|
||||
[
|
||||
"compare_web_screenshots",
|
||||
{ readOnlyHint: false, openWorldHint: false },
|
||||
],
|
||||
] as const) {
|
||||
expect(
|
||||
advertised.find((tool) => tool.name === name)?.annotations,
|
||||
name,
|
||||
).toMatchObject(expected);
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const missingPropertyDescriptions = (
|
||||
value: unknown,
|
||||
path = "inputSchema",
|
||||
): string[] => {
|
||||
if (Array.isArray(value))
|
||||
return value.flatMap((child, index) =>
|
||||
missingPropertyDescriptions(child, `${path}[${index}]`),
|
||||
);
|
||||
if (!isObject(value)) return [];
|
||||
|
||||
const missing: string[] = [];
|
||||
if (isObject(value.properties))
|
||||
for (const [property, schema] of Object.entries(value.properties)) {
|
||||
const propertyPath = `${path}.properties.${property}`;
|
||||
if (!isObject(schema) || typeof schema.description !== "string")
|
||||
missing.push(propertyPath);
|
||||
missing.push(...missingPropertyDescriptions(schema, propertyPath));
|
||||
}
|
||||
for (const [key, child] of Object.entries(value))
|
||||
if (
|
||||
key !== "properties" &&
|
||||
key !== "examples" &&
|
||||
key !== "default" &&
|
||||
key !== "const" &&
|
||||
key !== "enum"
|
||||
)
|
||||
missing.push(...missingPropertyDescriptions(child, `${path}.${key}`));
|
||||
return missing;
|
||||
};
|
||||
|
||||
const isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const describesObject = (schema: unknown): boolean => {
|
||||
if (!isObject(schema)) return false;
|
||||
return (
|
||||
schema.type === "object" ||
|
||||
[schema.oneOf, schema.anyOf].some(
|
||||
(variants) =>
|
||||
Array.isArray(variants) &&
|
||||
variants.length > 0 &&
|
||||
variants.every(
|
||||
(variant: unknown) => isObject(variant) && variant.type === "object",
|
||||
),
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -1,14 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { ToolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js";
|
||||
import { resolveProcessResult } from "../../../src/process/capture/ProcessCaptureLifecycle.js";
|
||||
import {
|
||||
toolContract,
|
||||
type ToolContract,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import { HopperProcessError } from "../../../src/domain/hopperErrors.js";
|
||||
import type { IncompleteProcessCaptureObservations } from "../../../src/domain/process/processCapture.js";
|
||||
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
|
||||
import { toCallToolResult } from "../../../src/server/toolResult.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { emptyProcessCapture } from "../../../src/domain/process/processCapture.fixture.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemas.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
const contract: ToolContract = {
|
||||
name: "provider_neutral_fixture",
|
||||
@@ -36,6 +46,215 @@ const contract: ToolContract = {
|
||||
examples: [{ title: "Example fixture request", input: {} }],
|
||||
};
|
||||
|
||||
describe("completed partial process capture MCP projection", () => {
|
||||
it("preserves partial capture details over the MCP SDK transport", async () => {
|
||||
const executionFailure = new Error("capture ended after a fixture error");
|
||||
const cleanup = {
|
||||
owned_process_group: {
|
||||
state: "unverified" as const,
|
||||
reason: "process ownership token could not be read",
|
||||
},
|
||||
terminal_renderer: { state: "cleaned" as const, reason: null },
|
||||
temporary_root: { state: "cleaned" as const, reason: null },
|
||||
};
|
||||
const capture = {
|
||||
...emptyProcessCapture(),
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "observed output" }],
|
||||
event_journal: [],
|
||||
};
|
||||
|
||||
let failure: ProcessCaptureError | undefined;
|
||||
try {
|
||||
resolveProcessResult(capture, executionFailure, cleanup);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ProcessCaptureError)) throw cause;
|
||||
failure = cause;
|
||||
}
|
||||
expect(failure).toBeDefined();
|
||||
if (failure === undefined)
|
||||
throw new Error("expected cleanup-incomplete result");
|
||||
|
||||
const captureContract = toolContract("capture_process_scenario");
|
||||
const server = new McpServer({
|
||||
name: "process-partial-error",
|
||||
version: "1",
|
||||
});
|
||||
server.registerTool(
|
||||
captureContract.name,
|
||||
toolRegistrationOptions(captureContract),
|
||||
async () => toCallToolResult(err(failure), captureContract),
|
||||
);
|
||||
const client = new Client({
|
||||
name: "process-partial-error-client",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: captureContract.name,
|
||||
arguments: captureContract.examples[0]?.input ?? {},
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
error: {
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
cleanup_report: cleanup,
|
||||
execution_failure: "capture ended after a fixture error",
|
||||
partial_observation: {
|
||||
capture: {
|
||||
frames: [{ data: "observed output" }],
|
||||
settlement: { cleanup_outcome: "failed" },
|
||||
},
|
||||
execution_failure: "capture ended after a fixture error",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const textContent = result.content.find((block) => block.type === "text");
|
||||
expect(textContent?.type === "text" ? textContent.text : undefined).toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("incomplete partial process observations MCP projection", () => {
|
||||
it("preserves normalized raw observations over the MCP SDK transport", async () => {
|
||||
const captureContract = toolContract("capture_process_scenario");
|
||||
const example = captureContract.examples[0];
|
||||
if (example === undefined)
|
||||
throw new Error("missing process scenario example");
|
||||
const scenario = processScenarioSchema.parse({
|
||||
...example.input,
|
||||
normalization: { pids: false },
|
||||
});
|
||||
const rootPid = 45678;
|
||||
const cleanup = {
|
||||
owned_process_group: {
|
||||
state: "unverified" as const,
|
||||
reason: "process ownership token could not be read",
|
||||
},
|
||||
terminal_renderer: { state: "cleaned" as const, reason: null },
|
||||
temporary_root: { state: "cleaned" as const, reason: null },
|
||||
};
|
||||
const observations: IncompleteProcessCaptureObservations = {
|
||||
target_pid: { state: "available", value: rootPid },
|
||||
frames: {
|
||||
state: "available",
|
||||
value: [{ sequence: 0, at_ms: 0, data: "partial output" }],
|
||||
},
|
||||
rendered_frames: {
|
||||
state: "unavailable",
|
||||
reason: "fixture renderer observation unavailable",
|
||||
},
|
||||
interaction_events: { state: "available", value: [] },
|
||||
exit: {
|
||||
state: "unavailable",
|
||||
reason: "fixture terminal exit unavailable",
|
||||
},
|
||||
settlement: {
|
||||
state: "unavailable",
|
||||
reason: "fixture process settlement unavailable",
|
||||
},
|
||||
process_samples: {
|
||||
state: "available",
|
||||
value: [
|
||||
{
|
||||
at_ms: 1,
|
||||
pid: rootPid,
|
||||
parent_pid: 1,
|
||||
command: `fixture ${String(rootPid)}`,
|
||||
process_group_id: rootPid,
|
||||
session_id: rootPid,
|
||||
},
|
||||
],
|
||||
},
|
||||
filesystem_snapshots: {
|
||||
before: { state: "available", value: { files: [], truncated: false } },
|
||||
after: {
|
||||
state: "unavailable",
|
||||
reason: "fixture final snapshot unavailable",
|
||||
},
|
||||
},
|
||||
event_journal: { state: "available", value: [] },
|
||||
manifest: {
|
||||
state: "unavailable",
|
||||
reason: "fixture capture manifest unavailable",
|
||||
},
|
||||
};
|
||||
|
||||
let failure: ProcessCaptureError | undefined;
|
||||
try {
|
||||
resolveProcessResult(
|
||||
undefined,
|
||||
new Error("capture failed before completion"),
|
||||
cleanup,
|
||||
observations,
|
||||
{ scenario, rootPid },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ProcessCaptureError)) throw cause;
|
||||
failure = cause;
|
||||
}
|
||||
if (failure === undefined)
|
||||
throw new Error("expected cleanup-incomplete result");
|
||||
|
||||
const server = new McpServer({
|
||||
name: "process-partial-observations",
|
||||
version: "1",
|
||||
});
|
||||
server.registerTool(
|
||||
captureContract.name,
|
||||
toolRegistrationOptions(captureContract),
|
||||
async () => toCallToolResult(err(failure), captureContract),
|
||||
);
|
||||
const client = new Client({
|
||||
name: "process-partial-observations-client",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: captureContract.name,
|
||||
arguments: example.input,
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
error: {
|
||||
details: {
|
||||
partial_observation: {
|
||||
observations: {
|
||||
target_pid: { state: "available", value: rootPid },
|
||||
frames: {
|
||||
state: "available",
|
||||
value: [{ data: "partial output" }],
|
||||
},
|
||||
process_samples: {
|
||||
state: "available",
|
||||
value: [{ pid: rootPid }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tool result projection", () => {
|
||||
it("exposes an actionable adapter code to MCP callers", () => {
|
||||
const result = toCallToolResult(err(new HopperProcessError(76)), contract);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { emptyArraySchema } from "../../../src/domain/emptyArraySchema.js";
|
||||
import { processScenarioSchema } from "../../../src/domain/processScenario.js";
|
||||
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
@@ -14,6 +14,7 @@ interface ToolSchemas {
|
||||
readonly name: string;
|
||||
readonly inputSchema: Record<string, unknown>;
|
||||
readonly outputSchema?: Record<string, unknown> | undefined;
|
||||
readonly annotations?: Record<string, unknown> | undefined;
|
||||
}
|
||||
|
||||
function schemaErrors(tools: readonly ToolSchemas[]): string[] {
|
||||
@@ -28,6 +29,155 @@ function schemaErrors(tools: readonly ToolSchemas[]): string[] {
|
||||
);
|
||||
}
|
||||
|
||||
function expectStrictInputSchemaParity(
|
||||
tools: readonly ToolSchemas[],
|
||||
ajv: Ajv2020,
|
||||
): void {
|
||||
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const names = [
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
"inspect_managed_native_boundaries",
|
||||
"list_browser_targets",
|
||||
"open_binary",
|
||||
"close_binary",
|
||||
"binary_session",
|
||||
"find_changed_behavior",
|
||||
"build_call_path",
|
||||
"record_unknown",
|
||||
"update_unknown",
|
||||
];
|
||||
for (const name of names) {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name: toolName }) => toolName === name,
|
||||
);
|
||||
const tool = advertised.get(name);
|
||||
const example = contract?.examples[0];
|
||||
if (contract === undefined || tool === undefined || example === undefined)
|
||||
throw new Error(`${name} did not have an advertised example`);
|
||||
const malformed = { ...example.input, __unexpected_root_key__: true };
|
||||
expect(contract.inputSchema.safeParse(malformed).success, name).toBe(false);
|
||||
expect(ajv.compile(tool.inputSchema)(malformed), name).toBe(false);
|
||||
}
|
||||
}
|
||||
|
||||
function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
|
||||
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const expected = {
|
||||
read_bytes: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
annotate_native_function: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true,
|
||||
},
|
||||
unset_bookmark: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
open_binary: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true,
|
||||
},
|
||||
close_binary: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
for (const [name, annotations] of Object.entries(expected))
|
||||
expect(advertised.get(name), name).toMatchObject({ annotations });
|
||||
}
|
||||
|
||||
function expectRecursivePropertyDescriptions(
|
||||
schema: unknown,
|
||||
path: string,
|
||||
): void {
|
||||
if (!isRecord(schema)) return;
|
||||
if (isRecord(schema.properties)) {
|
||||
for (const [property, child] of Object.entries(schema.properties)) {
|
||||
expect(child, `${path}.${property}`).toMatchObject({
|
||||
description: expect.any(String),
|
||||
});
|
||||
expectRecursivePropertyDescriptions(child, `${path}.${property}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of ["items", "additionalProperties"])
|
||||
if (schema[key] !== undefined)
|
||||
expectRecursivePropertyDescriptions(schema[key], path);
|
||||
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
|
||||
const children = schema[key];
|
||||
if (Array.isArray(children))
|
||||
children.forEach((child: unknown, index: number) =>
|
||||
expectRecursivePropertyDescriptions(child, `${path}.${key}[${index}]`),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
function resolveReference(schema: unknown, reference: string): unknown {
|
||||
if (reference === "#") return schema;
|
||||
if (!reference.startsWith("#/")) return undefined;
|
||||
let value = schema;
|
||||
for (const token of reference.slice(2).split("/")) {
|
||||
const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!Object.hasOwn(value, key)
|
||||
)
|
||||
return undefined;
|
||||
value = Reflect.get(value, key);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function recursiveReferences(tools: readonly ToolSchemas[]): string[] {
|
||||
return tools.flatMap((tool) =>
|
||||
(["inputSchema", "outputSchema"] as const).flatMap((kind) => {
|
||||
const schema = tool[kind];
|
||||
const found = new Set<string>();
|
||||
const visit = (node: unknown, active: readonly string[]): void => {
|
||||
if (typeof node !== "object" || node === null) return;
|
||||
for (const [key, child] of Object.entries(node)) {
|
||||
if (
|
||||
[
|
||||
"$defs",
|
||||
"definitions",
|
||||
"examples",
|
||||
"default",
|
||||
"const",
|
||||
"enum",
|
||||
].includes(key)
|
||||
)
|
||||
continue;
|
||||
if (key !== "$ref" || typeof child !== "string") visit(child, active);
|
||||
else if (active.includes(child)) found.add(child);
|
||||
else visit(resolveReference(schema, child), [...active, child]);
|
||||
}
|
||||
};
|
||||
visit(schema, []);
|
||||
return [...found].map(
|
||||
(reference) => `${tool.name}.${kind}: ${reference}`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const advertiseAndEnforceProcessEnvironmentKeyConstraint =
|
||||
async (): Promise<void> => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
@@ -118,15 +268,6 @@ describe("MCP JSON Schema validity", () => {
|
||||
expect(validate(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses an oracle that rejects empty prefixItems under Draft 2020-12", () => {
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
expect(ajv.defaultMeta()).toBe(
|
||||
"https://json-schema.org/draft/2020-12/schema",
|
||||
);
|
||||
expect(ajv.validateSchema({ type: "array", prefixItems: [] })).toBe(false);
|
||||
expect(ajv.validateSchema({ type: "array", maxItems: 0 })).toBe(true);
|
||||
});
|
||||
|
||||
it("advertises valid input and output schemas for every canonical tool", async () => {
|
||||
const server = new McpServer({ name: "schema-validation", version: "0" });
|
||||
const client = new Client({ name: "schema-validation", version: "0" });
|
||||
@@ -148,6 +289,41 @@ describe("MCP JSON Schema validity", () => {
|
||||
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
||||
);
|
||||
expect(schemaErrors(tools)).toEqual([]);
|
||||
expect(recursiveReferences(tools)).toEqual([]);
|
||||
expectKnownAuthorityHints(tools);
|
||||
const byName = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const catalogProjection = tools.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
}));
|
||||
expect(catalogProjection).toEqual(
|
||||
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
})),
|
||||
);
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const tool = byName.get(contract.name);
|
||||
expect(tool?.title?.trim(), contract.name).toBeTruthy();
|
||||
expect(tool?.description?.trim(), contract.name).toBeTruthy();
|
||||
expect(tool?.inputSchema.examples, contract.name).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
);
|
||||
for (const example of contract.examples)
|
||||
expect(
|
||||
contract.inputSchema.safeParse(example.input).success,
|
||||
`${contract.name}: ${example.title}`,
|
||||
).toBe(true);
|
||||
expectRecursivePropertyDescriptions(tool?.inputSchema, contract.name);
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
@@ -190,6 +366,8 @@ describe("MCP JSON Schema validity", () => {
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
expectStrictInputSchemaParity(tools, ajv);
|
||||
|
||||
const nativeObservation = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "observe_native_ui",
|
||||
);
|
||||
@@ -220,13 +398,98 @@ describe("MCP JSON Schema validity", () => {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("ships valid input and output schemas in the generated catalog", () => {
|
||||
expect(schemaErrors(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it(
|
||||
"advertises and enforces the process-owned environment key constraint",
|
||||
advertiseAndEnforceProcessEnvironmentKeyConstraint,
|
||||
);
|
||||
|
||||
describe("MCP process input JSON Schema", () => {
|
||||
it("advertises process strings without weakening terminal input", async () => {
|
||||
const server = new McpServer({
|
||||
name: "process-schema-validation",
|
||||
version: "0",
|
||||
});
|
||||
const client = new Client({
|
||||
name: "process-schema-validation",
|
||||
version: "0",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({ content: [] }),
|
||||
);
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const processContract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "capture_process_scenario",
|
||||
);
|
||||
const processTool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "capture_process_scenario",
|
||||
);
|
||||
if (processContract === undefined || processTool === undefined)
|
||||
throw new Error("Process scenario tool was not advertised");
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(processTool.inputSchema);
|
||||
const base = { executable: "/usr/bin/true" };
|
||||
for (const input of [
|
||||
{ ...base, executable: "/usr/bin/true\0" },
|
||||
{ ...base, arguments: ["\0"] },
|
||||
{ ...base, working_directory: "/tmp\0" },
|
||||
{ ...base, environment: { KEY: "value\0" } },
|
||||
{ ...base, filesystem_observation_paths: ["/tmp\0"] },
|
||||
]) {
|
||||
expect(processContract.inputSchema.safeParse(input).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(validate(input)).toBe(false);
|
||||
}
|
||||
const terminalInput = {
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 0, data: "\0" }],
|
||||
};
|
||||
expect(processContract.inputSchema.safeParse(terminalInput).success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(validate(terminalInput)).toBe(true);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("ships nonrecursive input and output schemas in the generated catalog", () => {
|
||||
expect(schemaErrors(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
expect(recursiveReferences(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
|
||||
it("distinguishes recursive references from shared definitions", () => {
|
||||
const diamond = {
|
||||
type: "object",
|
||||
properties: {
|
||||
left: { $ref: "#/$defs/shared" },
|
||||
right: { $ref: "#/$defs/shared" },
|
||||
},
|
||||
$defs: { shared: { type: "string" } },
|
||||
};
|
||||
expect(
|
||||
recursiveReferences([{ name: "diamond", inputSchema: diamond }]),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
recursiveReferences([{ name: "root", inputSchema: { $ref: "#" } }]),
|
||||
).toEqual(["root.inputSchema: #"]);
|
||||
const escaped = {
|
||||
$ref: "#/$defs/a~1b",
|
||||
$defs: { "a/b": { $ref: "#/$defs/a~1b" } },
|
||||
};
|
||||
expect(
|
||||
recursiveReferences([{ name: "escaped", inputSchema: escaped }]),
|
||||
).toEqual(["escaped.inputSchema: #/$defs/a~1b"]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
|
||||
it("publishes valid SDK schemas and retains historical inline Evidence with the supplied session", async () => {
|
||||
const service = new WebNetworkCaptureService({
|
||||
inspect: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
artifact: { path: "/capture.har", sha256: "a".repeat(64), bytes: 10 },
|
||||
format: "har",
|
||||
decoder: { id: "test-capture-port", name: "test port", version: "1" },
|
||||
container: {
|
||||
reported: { creator: "fixture" },
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
records_pointer: "/log/entries",
|
||||
},
|
||||
total_records: 0,
|
||||
records: [],
|
||||
runtime_attribution: "unknown",
|
||||
limitations: ["synthetic application port, no real decoder claim"],
|
||||
}),
|
||||
),
|
||||
});
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Binary provider must not start");
|
||||
});
|
||||
const server = createServer(session, session, { webNetworkCapture: service });
|
||||
const client = new Client({
|
||||
name: "historical-capture-contract",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_web_network_capture",
|
||||
);
|
||||
if (advertised?.outputSchema === undefined)
|
||||
throw new Error("Capture inspection must advertise both schemas");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = advertised.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = advertised.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const args = { capture_path: "/capture.har", format: "har" };
|
||||
expect(ajv.validate(inputSchema, args)).toBe(true);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: args,
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(
|
||||
ajv.validate(outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
).toBe(true);
|
||||
const parsed = toolContract("inspect_web_network_capture").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
const evidence = parseEvidence(parsed.evidence);
|
||||
expect(parsed.result).toEqual(evidence.normalized_result);
|
||||
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
|
||||
const invalid = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: { ...args, capture_path: "relative.har" },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
const invalidSensitive = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: { ...args, sensitive_values: ["secret"], mysecret: true },
|
||||
});
|
||||
expect(invalidSensitive.isError).toBe(true);
|
||||
expect(invalidSensitive.structuredContent).toMatchObject({
|
||||
error: { code: "invalid_request", details: { issues: [{ path: [] }] } },
|
||||
});
|
||||
expect(JSON.stringify(invalidSensitive)).not.toContain("secret");
|
||||
expect(ajv.validate(inputSchema, { ...args, mysecret: true })).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { browserCaptureComparisonInputSchema } from "../../../src/domain/browserCaptureComparison.js";
|
||||
import { webPageInspectionSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
function resolveLocalReference(root: unknown, reference: string): unknown {
|
||||
if (reference === "#") return root;
|
||||
if (!reference.startsWith("#/")) return undefined;
|
||||
let current = root;
|
||||
for (const part of reference.slice(2).split("/")) {
|
||||
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
if (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;
|
||||
current = current[key];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
// Count object/array and composition levels, following references per path.
|
||||
// Definitions, property maps, and literal example/default data are not levels.
|
||||
function inputDepth(
|
||||
schema: unknown,
|
||||
root: unknown = schema,
|
||||
activeReferences: readonly string[] = [],
|
||||
): number {
|
||||
if (!isRecord(schema)) return 0;
|
||||
let referenceDepth = 0;
|
||||
if (typeof schema.$ref === "string") {
|
||||
if (activeReferences.includes(schema.$ref)) return Number.POSITIVE_INFINITY;
|
||||
const target = resolveLocalReference(root, schema.$ref);
|
||||
if (target === undefined) return Number.POSITIVE_INFINITY;
|
||||
referenceDepth = inputDepth(target, root, [
|
||||
...activeReferences,
|
||||
schema.$ref,
|
||||
]);
|
||||
}
|
||||
const childDepths: number[] = [];
|
||||
for (const key of ["properties", "patternProperties", "dependentSchemas"]) {
|
||||
const group = schema[key];
|
||||
if (isRecord(group))
|
||||
for (const child of Object.values(group))
|
||||
childDepths.push(inputDepth(child, root, activeReferences));
|
||||
}
|
||||
for (const key of [
|
||||
"items",
|
||||
"additionalProperties",
|
||||
"contains",
|
||||
"not",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"propertyNames",
|
||||
"unevaluatedProperties",
|
||||
"unevaluatedItems",
|
||||
])
|
||||
childDepths.push(inputDepth(schema[key], root, activeReferences));
|
||||
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
|
||||
const children = schema[key];
|
||||
if (Array.isArray(children))
|
||||
for (const child of children)
|
||||
childDepths.push(inputDepth(child, root, activeReferences));
|
||||
}
|
||||
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
||||
const container = types.includes("object") || types.includes("array") ? 1 : 0;
|
||||
const composition = ["anyOf", "oneOf", "allOf"].some((key) =>
|
||||
Array.isArray(schema[key]),
|
||||
)
|
||||
? 1
|
||||
: 0;
|
||||
return Math.max(
|
||||
referenceDepth,
|
||||
container + composition + Math.max(0, ...childDepths),
|
||||
);
|
||||
}
|
||||
|
||||
function inputDepthViolations(
|
||||
tools: readonly { name: string; inputSchema: unknown }[],
|
||||
) {
|
||||
return tools.flatMap(({ name, inputSchema }) => {
|
||||
const depth = inputDepth(inputSchema);
|
||||
return depth > 10 ? [{ name, depth }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
async function withCatalog(
|
||||
verify: (client: Client, calls: ReadonlyMap<string, number>) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const server = new McpServer({ name: "wire-limits", version: "0" });
|
||||
const calls = new Map<string, number>();
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => {
|
||||
calls.set(contract.name, (calls.get(contract.name) ?? 0) + 1);
|
||||
return { content: [], isError: true };
|
||||
},
|
||||
);
|
||||
const client = new Client({ name: "wire-limits", version: "0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verify(client, calls);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
}
|
||||
|
||||
describe("complete catalog input compatibility profile (#919)", () => {
|
||||
it("follows shared and escaped references without treating data as schemas", () => {
|
||||
const diamond = {
|
||||
type: "object",
|
||||
properties: {
|
||||
left: { $ref: "#/$defs/a~1b~0c" },
|
||||
right: { $ref: "#/$defs/a~1b~0c" },
|
||||
},
|
||||
$defs: {
|
||||
"a/b~c": { type: "object", properties: { id: { type: "string" } } },
|
||||
unused: { $ref: "#/$defs/unused" },
|
||||
},
|
||||
examples: [{ $ref: "#" }],
|
||||
default: { $ref: "#" },
|
||||
};
|
||||
expect(inputDepth(diamond)).toBe(2);
|
||||
expect(
|
||||
inputDepth({ type: "object", properties: { child: { $ref: "#" } } }),
|
||||
).toBe(Number.POSITIVE_INFINITY);
|
||||
expect(
|
||||
inputDepth({
|
||||
type: "object",
|
||||
properties: {
|
||||
values: {
|
||||
anyOf: [
|
||||
{ type: "array", items: { type: "object" } },
|
||||
{ type: "null" },
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
it("keeps every live and generated input within ten structural levels", async () => {
|
||||
await withCatalog(async (client) => {
|
||||
const { tools } = await client.listTools();
|
||||
expect(tools.map(({ name }) => name).sort()).toEqual(
|
||||
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
||||
);
|
||||
expect(inputDepthViolations(tools)).toEqual([]);
|
||||
expect(inputDepthViolations(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("describes capture round trips without altering domain or scenario schemas", () => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "compare_web_captures",
|
||||
);
|
||||
if (contract === undefined)
|
||||
throw new Error("Missing capture comparison contract");
|
||||
const original = z.toJSONSchema(browserCaptureComparisonInputSchema, {
|
||||
io: "input",
|
||||
});
|
||||
const projected = z.toJSONSchema(contract.inputSchema, { io: "input" });
|
||||
expect(inputDepth(original)).toBeGreaterThan(10);
|
||||
expect(inputDepth(projected)).toBeLessThanOrEqual(10);
|
||||
expect(isRecord(original.properties)).toBe(true);
|
||||
expect(isRecord(projected.properties)).toBe(true);
|
||||
if (!isRecord(original.properties) || !isRecord(projected.properties))
|
||||
throw new Error("Missing comparison properties");
|
||||
for (const key of ["normalization"])
|
||||
expect(projected.properties[key], key).toEqual(original.properties[key]);
|
||||
expect(z.toJSONSchema(webPageInspectionSchema).properties).toHaveProperty(
|
||||
"network",
|
||||
);
|
||||
for (const example of contract.examples)
|
||||
expect(contract.inputSchema.parse(example.input)).toEqual(
|
||||
browserCaptureComparisonInputSchema.parse(example.input),
|
||||
);
|
||||
const example = contract.examples[0];
|
||||
if (example === undefined) throw new Error("Missing scenario example");
|
||||
for (const malformed of [
|
||||
{ before_scenario: {}, after_scenario: {} },
|
||||
{
|
||||
...example.input,
|
||||
before: { inspection: {} },
|
||||
after: { inspection: {} },
|
||||
},
|
||||
{ ...example.input, __unexpected_root_key__: true },
|
||||
]) {
|
||||
const originalResult =
|
||||
browserCaptureComparisonInputSchema.safeParse(malformed);
|
||||
const projectedResult = contract.inputSchema.safeParse(malformed);
|
||||
expect(originalResult.success).toBe(false);
|
||||
expect(projectedResult.success).toBe(false);
|
||||
if (!originalResult.success && !projectedResult.success)
|
||||
expect(projectedResult.error.issues).toEqual(
|
||||
originalResult.error.issues,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects incomplete round-trip payloads before invoking the handler", async () => {
|
||||
await withCatalog(async (client, calls) => {
|
||||
const tool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "compare_web_captures",
|
||||
);
|
||||
if (tool === undefined)
|
||||
throw new Error("Missing advertised comparison tool");
|
||||
const incomplete = {
|
||||
before: { inspection: {} },
|
||||
after: { inspection: {} },
|
||||
};
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(tool.inputSchema);
|
||||
expect(validate(incomplete)).toBe(true);
|
||||
expect(
|
||||
browserCaptureComparisonInputSchema.safeParse(incomplete).success,
|
||||
).toBe(false);
|
||||
const result = await client.callTool({
|
||||
name: tool.name,
|
||||
arguments: incomplete,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(calls.get(tool.name) ?? 0).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { emptyUnverifiedProcessCapture } from "../../../src/domain/process/processCapture.fixture.js";
|
||||
import { parseProcessCapture } from "../../../src/domain/process/processCapture.js";
|
||||
import { parseProcessScenario } from "../../../src/domain/process/processScenario.js";
|
||||
import { createProcessCaptureEvidence } from "../../../src/application/process/ProcessEvidence.js";
|
||||
import { observeSettlement } from "../../../src/process/capture/ProcessCaptureLifecycle.js";
|
||||
|
||||
it("stamps process Evidence from the capture manifest host", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
working_directory: process.cwd(),
|
||||
events: [],
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
platform: "linux",
|
||||
architecture: "arm64",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
createProcessCaptureEvidence(scenario, capture).environment,
|
||||
).toMatchObject({
|
||||
id: "linux-arm64",
|
||||
platform: "linux",
|
||||
architecture: "arm64",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the selected host platform for process settlement behavior", async () => {
|
||||
const events: string[] = [];
|
||||
const result = await observeSettlement(
|
||||
"run",
|
||||
[],
|
||||
0,
|
||||
(event) => events.push(event),
|
||||
"win32",
|
||||
);
|
||||
|
||||
expect(result).toEqual({ state: "unverifiable", elapsed_ms: 0 });
|
||||
expect(events).toEqual(["lifecycle"]);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createProcessCaptureEvidence } from "../../../src/application/process/ProcessEvidence.js";
|
||||
import {
|
||||
createRunManifest,
|
||||
observeLaunchedExecutable,
|
||||
observeSelectedExecutable,
|
||||
} from "../../../src/process/capture/ProcessCaptureLifecycle.js";
|
||||
import { emptyUnverifiedProcessCapture } from "../../../src/domain/process/processCapture.fixture.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
} from "../../../src/domain/process/processCapture.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
parseProcessScenario,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
} from "../../../src/domain/process/processScenario.js";
|
||||
|
||||
const captureEvidenceForSensitiveInput = (data: string) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/echo",
|
||||
working_directory: "/tmp",
|
||||
events: [{ type: "input", at_ms: 0, data, sensitive: true }],
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const executableSha256 = "0".repeat(64);
|
||||
const scenarioProjection = processScenarioCommitment(
|
||||
scenario,
|
||||
executableSha256,
|
||||
);
|
||||
const comparisonContract = processComparisonContract(scenario);
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "interaction",
|
||||
reason:
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.",
|
||||
},
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
],
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
scenario: scenarioProjection,
|
||||
comparison_contract: comparisonContract,
|
||||
full_scenario_sha256: digestProcessCommitment(scenarioProjection),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: executableSha256,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
},
|
||||
});
|
||||
return createProcessCaptureEvidence(scenario, capture);
|
||||
};
|
||||
|
||||
const captureEvidenceForEnvironmentSecret = async (value: string) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/echo",
|
||||
working_directory: "/tmp",
|
||||
environment: { API_TOKEN: value },
|
||||
events: [{ type: "input", at_ms: 0, data: value }],
|
||||
});
|
||||
const selectedExecutable = await observeSelectedExecutable(
|
||||
scenario.executable,
|
||||
);
|
||||
const executableIdentity = observeLaunchedExecutable(
|
||||
scenario.executable,
|
||||
selectedExecutable,
|
||||
);
|
||||
const manifest = await createRunManifest(
|
||||
scenario,
|
||||
new Date(0),
|
||||
new Date(1),
|
||||
executableIdentity,
|
||||
);
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const scenarioManifest = {
|
||||
...manifest,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
};
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "observed-output" }],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
],
|
||||
manifest: scenarioManifest,
|
||||
});
|
||||
return createProcessCaptureEvidence(scenario, capture);
|
||||
};
|
||||
|
||||
it("does not persist sensitive scripted input in process capture Evidence", () => {
|
||||
const secret = "top-secret-input";
|
||||
const evidence = captureEvidenceForSensitiveInput(secret);
|
||||
const serialized = JSON.stringify(evidence);
|
||||
const manifest = evidence.normalized_result;
|
||||
|
||||
expect(JSON.stringify(manifest)).not.toContain(secret);
|
||||
expect(JSON.stringify(evidence.parameters)).not.toContain(secret);
|
||||
expect(serialized).not.toContain(secret);
|
||||
});
|
||||
|
||||
it("does not treat captures with different redacted inputs as equivalent", () => {
|
||||
const left = captureEvidenceForSensitiveInput("secret-left");
|
||||
const right = captureEvidenceForSensitiveInput("secret-right");
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(
|
||||
parseProcessCapture(left.normalized_result),
|
||||
parseProcessCapture(right.normalized_result),
|
||||
),
|
||||
).toMatchObject({ status: "unknown", interaction: "unknown" });
|
||||
});
|
||||
|
||||
it("preserves selected local environment and input values", async () => {
|
||||
const left = await captureEvidenceForEnvironmentSecret("secret-left");
|
||||
const right = await captureEvidenceForEnvironmentSecret("secret-right");
|
||||
const serialized = JSON.stringify(left);
|
||||
const leftCapture = parseProcessCapture(left.normalized_result);
|
||||
const rightCapture = parseProcessCapture(right.normalized_result);
|
||||
|
||||
expect(serialized).toContain("secret-left");
|
||||
expect(leftCapture.manifest.scenario).toMatchObject({
|
||||
environment: { API_TOKEN: "secret-left" },
|
||||
});
|
||||
expect(leftCapture.manifest.scenario).not.toHaveProperty("PATH");
|
||||
expect(leftCapture.manifest.comparison_contract_sha256).not.toBe(
|
||||
rightCapture.manifest.comparison_contract_sha256,
|
||||
);
|
||||
|
||||
const changedOutput = parseProcessCapture({
|
||||
...leftCapture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "different-output" }],
|
||||
});
|
||||
expect(compareProcessCaptures(leftCapture, changedOutput)).toMatchObject({
|
||||
status: "changed",
|
||||
terminal: "changed",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,724 @@
|
||||
import { execFile, spawn, type ChildProcess } from "node:child_process";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { _electron as electron } from "playwright-core";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createSystemProcessOwnershipHost,
|
||||
systemProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnershipObservation.js";
|
||||
import { createDarwinProcessRunTokenReader } from "../../../src/process/DarwinProcessRunTokenReader.js";
|
||||
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
|
||||
import { normalizeCaptureFailure } from "../../../src/process/capture/ProcessHarness.js";
|
||||
import { PlaywrightElectronActiveProvider } from "../../../src/browser/PlaywrightElectronActiveProvider.js";
|
||||
import { electronActiveObservationInputSchema } from "../../../src/domain/javascript/electronActiveObservation.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const onDarwin = process.platform === "darwin";
|
||||
|
||||
const writeBlockingCompiler = async (directory: string) => {
|
||||
const executable = join(directory, "fake-xcrun");
|
||||
const statePath = join(directory, "compile-state.json");
|
||||
const releasePath = join(directory, "release-compiler");
|
||||
const source = `#!/usr/bin/env node
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const statePath = ${JSON.stringify(statePath)};
|
||||
const releasePath = ${JSON.stringify(releasePath)};
|
||||
const state = fs.existsSync(statePath)
|
||||
? JSON.parse(fs.readFileSync(statePath, "utf8"))
|
||||
: { calls: 0 };
|
||||
state.calls += 1;
|
||||
const moduleIndex = process.argv.indexOf("-module-cache-path");
|
||||
state.root = path.dirname(process.argv[moduleIndex + 1]);
|
||||
const outputIndex = process.argv.indexOf("-o");
|
||||
state.output = process.argv[outputIndex + 1];
|
||||
state.releasePath = releasePath;
|
||||
fs.writeFileSync(statePath, JSON.stringify(state));
|
||||
if (state.calls === 1) {
|
||||
const timer = setInterval(() => {
|
||||
if (!fs.existsSync(releasePath)) return;
|
||||
clearInterval(timer);
|
||||
fs.writeFileSync(state.output, "compiled");
|
||||
}, 10);
|
||||
} else {
|
||||
fs.writeFileSync(state.output, "compiled");
|
||||
}
|
||||
`;
|
||||
await writeFile(executable, source);
|
||||
await chmod(executable, 0o755);
|
||||
return { executable, statePath, releasePath };
|
||||
};
|
||||
|
||||
const writeBlockingIdentityCompiler = async (directory: string) => {
|
||||
const executable = join(directory, "fake-identity-xcrun");
|
||||
const statePath = join(directory, "identity-helper-state.json");
|
||||
const helperSource = `#!/usr/bin/env node
|
||||
const fs = require("node:fs");
|
||||
fs.writeFileSync(${JSON.stringify(statePath)}, JSON.stringify({
|
||||
root: __dirname,
|
||||
}));
|
||||
setInterval(() => {}, 1000);
|
||||
`;
|
||||
const compilerSource = `#!/usr/bin/env node
|
||||
const fs = require("node:fs");
|
||||
const outputIndex = process.argv.indexOf("-o");
|
||||
const output = process.argv[outputIndex + 1];
|
||||
fs.writeFileSync(output, ${JSON.stringify(helperSource)});
|
||||
fs.chmodSync(output, 0o755);
|
||||
`;
|
||||
await writeFile(executable, compilerSource);
|
||||
await chmod(executable, 0o755);
|
||||
return { executable, statePath };
|
||||
};
|
||||
|
||||
const waitForCompileState = async (statePath: string) => {
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await readFile(statePath, "utf8"));
|
||||
if (
|
||||
typeof parsed === "object" &&
|
||||
parsed !== null &&
|
||||
"calls" in parsed &&
|
||||
typeof parsed.calls === "number" &&
|
||||
"root" in parsed &&
|
||||
typeof parsed.root === "string" &&
|
||||
"output" in parsed &&
|
||||
typeof parsed.output === "string" &&
|
||||
"releasePath" in parsed &&
|
||||
typeof parsed.releasePath === "string"
|
||||
)
|
||||
return {
|
||||
calls: parsed.calls,
|
||||
root: parsed.root,
|
||||
output: parsed.output,
|
||||
releasePath: parsed.releasePath,
|
||||
};
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
throw new Error("fake compiler did not start");
|
||||
};
|
||||
|
||||
const waitForIdentityHelper = async (statePath: string) => {
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await readFile(statePath, "utf8"));
|
||||
if (
|
||||
typeof parsed === "object" &&
|
||||
parsed !== null &&
|
||||
"root" in parsed &&
|
||||
typeof parsed.root === "string"
|
||||
)
|
||||
return { root: parsed.root };
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
throw new Error("fake identity helper did not start");
|
||||
};
|
||||
|
||||
type ElectronCaptureResult = Awaited<
|
||||
ReturnType<PlaywrightElectronActiveProvider["capture"]>
|
||||
>;
|
||||
type ElectronCaptureOutcome =
|
||||
| { readonly state: "result"; readonly value: ElectronCaptureResult }
|
||||
| { readonly state: "rejected"; readonly cause: unknown };
|
||||
|
||||
it("reports an actionable missing Swift compiler without installing it", async () => {
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: join(tmpdir(), "rea-no-such-xcrun"),
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
reader.read([
|
||||
{
|
||||
pid: 1,
|
||||
parentPid: 0,
|
||||
processGroupId: 1,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
]),
|
||||
).rejects.toThrow(/requires the Apple Swift compiler via xcrun/u);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rethrows compile cancellation, removes its temporary root, and permits retry",
|
||||
async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-token-abort-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingCompiler(directory);
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: fakeCompiler.executable,
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const compilation = reader.prepare(controller.signal).then(
|
||||
() => ({ state: "fulfilled" as const }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
try {
|
||||
const firstAttempt = await waitForCompileState(fakeCompiler.statePath);
|
||||
controller.abort();
|
||||
const outcome = await compilation;
|
||||
|
||||
expect(outcome.state).toBe("rejected");
|
||||
if (outcome.state !== "rejected")
|
||||
throw new Error(
|
||||
"aborted native reader compilation unexpectedly succeeded",
|
||||
);
|
||||
expect(outcome.cause).toMatchObject({ name: "AbortError" });
|
||||
expect(
|
||||
normalizeCaptureFailure(outcome.cause, controller.signal),
|
||||
).toMatchObject({ reason: "cancelled", userCategory: "cancelled" });
|
||||
await expect(access(firstAttempt.root)).rejects.toThrow();
|
||||
|
||||
await reader.prepare();
|
||||
const retry = await waitForCompileState(fakeCompiler.statePath);
|
||||
expect(retry).toMatchObject({ calls: 2 });
|
||||
await expect(access(retry.output)).resolves.toBeUndefined();
|
||||
await reader.close();
|
||||
await expect(access(retry.root)).rejects.toThrow();
|
||||
} finally {
|
||||
if (!controller.signal.aborted) controller.abort();
|
||||
await compilation;
|
||||
await reader.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32").each(["first", "second"] as const)(
|
||||
"keeps shared compilation alive when the %s waiter cancels",
|
||||
async (cancelledWaiter) => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-token-shared-compile-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingCompiler(directory);
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: fakeCompiler.executable,
|
||||
});
|
||||
const firstController = new AbortController();
|
||||
const secondController = new AbortController();
|
||||
const firstWaiter = reader.prepare(firstController.signal).then(
|
||||
(value) => ({ state: "fulfilled" as const, value }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
const secondWaiterPromise = (async () => {
|
||||
const state = await waitForCompileState(fakeCompiler.statePath);
|
||||
const secondWaiter = reader.prepare(secondController.signal).then(
|
||||
(value) => ({ state: "fulfilled" as const, value }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
const cancelled =
|
||||
cancelledWaiter === "first" ? firstWaiter : secondWaiter;
|
||||
const surviving =
|
||||
cancelledWaiter === "first" ? secondWaiter : firstWaiter;
|
||||
(cancelledWaiter === "first"
|
||||
? firstController
|
||||
: secondController
|
||||
).abort();
|
||||
const firstOutcome = await cancelled;
|
||||
expect(firstOutcome.state).toBe("rejected");
|
||||
if (firstOutcome.state !== "rejected")
|
||||
throw new Error("cancelled compilation waiter unexpectedly succeeded");
|
||||
expect(firstOutcome.cause).toMatchObject({ name: "AbortError" });
|
||||
await expect(access(state.root)).resolves.toBeUndefined();
|
||||
await writeFile(fakeCompiler.releasePath, "release");
|
||||
return { state, outcome: await surviving };
|
||||
})();
|
||||
|
||||
try {
|
||||
const { state, outcome } = await secondWaiterPromise;
|
||||
expect(state.calls).toBe(1);
|
||||
expect(outcome.state).toBe("fulfilled");
|
||||
if (outcome.state !== "fulfilled") throw outcome.cause;
|
||||
expect(outcome.value).toBe(state.output);
|
||||
await reader.close();
|
||||
await expect(access(state.root)).rejects.toThrow();
|
||||
} finally {
|
||||
if (!firstController.signal.aborted) firstController.abort();
|
||||
if (!secondController.signal.aborted) secondController.abort();
|
||||
await Promise.allSettled([firstWaiter, secondWaiterPromise]);
|
||||
await reader.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"retains a failed compilation cleanup for a later close retry",
|
||||
async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-token-cleanup-retry-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingCompiler(directory);
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: fakeCompiler.executable,
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const preparation = reader.prepare(controller.signal).then(
|
||||
() => ({ state: "fulfilled" as const }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
let compilationRoot: string | undefined;
|
||||
try {
|
||||
const state = await waitForCompileState(fakeCompiler.statePath);
|
||||
compilationRoot = state.root;
|
||||
await writeFile(
|
||||
join(state.root, "retained.txt"),
|
||||
"cleanup must remain tracked",
|
||||
);
|
||||
await chmod(state.root, 0o000);
|
||||
controller.abort();
|
||||
expect((await preparation).state).toBe("rejected");
|
||||
await expect(reader.close()).rejects.toThrow();
|
||||
await chmod(state.root, 0o700);
|
||||
await reader.close();
|
||||
await expect(access(state.root)).rejects.toThrow();
|
||||
} finally {
|
||||
if (!controller.signal.aborted) controller.abort();
|
||||
await preparation;
|
||||
if (compilationRoot !== undefined)
|
||||
await chmod(compilationRoot, 0o700).catch(() => undefined);
|
||||
await reader.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"aborts and cleans an active compilation when the reader closes",
|
||||
async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-token-close-compile-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingCompiler(directory);
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: fakeCompiler.executable,
|
||||
});
|
||||
const preparation = reader.prepare().then(
|
||||
() => ({ state: "fulfilled" as const }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
try {
|
||||
const state = await waitForCompileState(fakeCompiler.statePath);
|
||||
await reader.close();
|
||||
const outcome = await preparation;
|
||||
expect(outcome.state).toBe("rejected");
|
||||
if (outcome.state !== "rejected")
|
||||
throw new Error("closed reader compilation unexpectedly succeeded");
|
||||
expect(outcome.cause).toMatchObject({ name: "AbortError" });
|
||||
await expect(access(state.root)).rejects.toThrow();
|
||||
await expect(reader.prepare()).rejects.toThrow(/reader is closed/u);
|
||||
await expect(reader.close()).resolves.toBeUndefined();
|
||||
} finally {
|
||||
await Promise.allSettled([preparation]);
|
||||
await reader.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"maps cancellation during native preparation before Electron path resolution",
|
||||
async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-electron-token-abort-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingCompiler(directory);
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: fakeCompiler.executable,
|
||||
});
|
||||
const prepareSpy = vi
|
||||
.spyOn(systemProcessOwnershipHost, "prepare")
|
||||
.mockImplementation(async (signal) => {
|
||||
await reader.prepare(signal);
|
||||
});
|
||||
const launchSpy = vi.spyOn(electron, "launch");
|
||||
const controller = new AbortController();
|
||||
let captureOutcome: Promise<ElectronCaptureOutcome> | undefined;
|
||||
try {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: "/missing/electron",
|
||||
application_path: "/missing/application.js",
|
||||
});
|
||||
captureOutcome = new PlaywrightElectronActiveProvider()
|
||||
.capture(input, { signal: controller.signal })
|
||||
.then(
|
||||
(value) => ({ state: "result" as const, value }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
const compileState = await waitForCompileState(fakeCompiler.statePath);
|
||||
controller.abort();
|
||||
const outcome = await captureOutcome;
|
||||
|
||||
expect(outcome.state).toBe("result");
|
||||
if (outcome.state !== "result") throw outcome.cause;
|
||||
expect(outcome.value).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "cancelled", userCategory: "cancelled" },
|
||||
});
|
||||
expect(launchSpy).not.toHaveBeenCalled();
|
||||
await expect(access(compileState.root)).rejects.toThrow();
|
||||
} finally {
|
||||
if (!controller.signal.aborted) controller.abort();
|
||||
if (captureOutcome !== undefined) await captureOutcome;
|
||||
prepareSpy.mockRestore();
|
||||
launchSpy.mockRestore();
|
||||
await reader.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves cancellation through system-host baseline identity inspection",
|
||||
async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-baseline-abort-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingIdentityCompiler(directory);
|
||||
const host = createSystemProcessOwnershipHost("darwin", process.env, {
|
||||
darwinXcrun: fakeCompiler.executable,
|
||||
});
|
||||
const controller = new AbortController();
|
||||
let helperRoot: string | undefined;
|
||||
const baseline =
|
||||
host.captureBaseline?.(controller.signal).then(
|
||||
() => ({ state: "fulfilled" as const }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
) ?? Promise.resolve({ state: "missing" as const });
|
||||
try {
|
||||
if (host.captureBaseline === undefined)
|
||||
throw new Error("Darwin host did not expose process baselines");
|
||||
const helper = await waitForIdentityHelper(fakeCompiler.statePath);
|
||||
helperRoot = helper.root;
|
||||
controller.abort();
|
||||
const outcome = await baseline;
|
||||
|
||||
expect(outcome.state).toBe("rejected");
|
||||
if (outcome.state !== "rejected")
|
||||
throw new Error("aborted identity inspection unexpectedly succeeded");
|
||||
expect(outcome.cause).toMatchObject({ name: "AbortError" });
|
||||
expect(
|
||||
normalizeCaptureFailure(outcome.cause, controller.signal),
|
||||
).toMatchObject({ reason: "cancelled", userCategory: "cancelled" });
|
||||
await expect(access(helper.root)).resolves.toBeUndefined();
|
||||
} finally {
|
||||
if (!controller.signal.aborted) controller.abort();
|
||||
await baseline;
|
||||
await host.close?.();
|
||||
if (helperRoot !== undefined)
|
||||
await expect(access(helperRoot)).rejects.toThrow();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"passes Electron cancellation into capture-local baseline inspection",
|
||||
async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-electron-baseline-abort-test-"),
|
||||
);
|
||||
const fakeCompiler = await writeBlockingIdentityCompiler(directory);
|
||||
const reader = createDarwinProcessRunTokenReader({
|
||||
xcrun: fakeCompiler.executable,
|
||||
});
|
||||
const prepareSpy = vi
|
||||
.spyOn(systemProcessOwnershipHost, "prepare")
|
||||
.mockResolvedValue();
|
||||
const baselineSpy = vi
|
||||
.spyOn(systemProcessOwnershipHost, "captureBaseline")
|
||||
.mockImplementation(async (signal) => {
|
||||
await reader.identities(
|
||||
[
|
||||
{
|
||||
pid: process.pid,
|
||||
parentPid: process.ppid,
|
||||
processGroupId: process.pid,
|
||||
state: "S",
|
||||
command: process.execPath,
|
||||
},
|
||||
],
|
||||
signal,
|
||||
);
|
||||
return [];
|
||||
});
|
||||
const launchSpy = vi.spyOn(electron, "launch");
|
||||
const controller = new AbortController();
|
||||
let captureOutcome: Promise<ElectronCaptureOutcome> | undefined;
|
||||
try {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: process.execPath,
|
||||
application_path: fileURLToPath(import.meta.url),
|
||||
application_root: process.cwd(),
|
||||
});
|
||||
captureOutcome = new PlaywrightElectronActiveProvider()
|
||||
.capture(input, { signal: controller.signal })
|
||||
.then(
|
||||
(value) => ({ state: "result" as const, value }),
|
||||
(cause: unknown) => ({ state: "rejected" as const, cause }),
|
||||
);
|
||||
const helper = await waitForIdentityHelper(fakeCompiler.statePath);
|
||||
controller.abort();
|
||||
const outcome = await captureOutcome;
|
||||
|
||||
expect(outcome.state).toBe("result");
|
||||
if (outcome.state !== "result") throw outcome.cause;
|
||||
expect(outcome.value).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "cancelled", userCategory: "cancelled" },
|
||||
});
|
||||
expect(launchSpy).not.toHaveBeenCalled();
|
||||
await expect(access(helper.root)).resolves.toBeUndefined();
|
||||
} finally {
|
||||
if (!controller.signal.aborted) controller.abort();
|
||||
if (captureOutcome !== undefined) await captureOutcome;
|
||||
prepareSpy.mockRestore();
|
||||
baselineSpy.mockRestore();
|
||||
launchSpy.mockRestore();
|
||||
await reader.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(!onDarwin)(
|
||||
"parses exact NUL-delimited token records and rejects truncated argv",
|
||||
async () => {
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-token-parser-test-"),
|
||||
);
|
||||
const executable = join(root, "parser-test");
|
||||
const core = fileURLToPath(
|
||||
new URL(
|
||||
"../../../bridge/process/ProcessRunTokenReader.swift",
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
const fixture = fileURLToPath(
|
||||
new URL(
|
||||
"../../fixtures/processRunTokenParserProbe.swift",
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
try {
|
||||
await execFileOutput(
|
||||
"/usr/bin/xcrun",
|
||||
[
|
||||
"swiftc",
|
||||
"-module-cache-path",
|
||||
join(root, "modules"),
|
||||
core,
|
||||
fixture,
|
||||
"-o",
|
||||
executable,
|
||||
],
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
const { stdout } = await execFileAsync(executable, [], {
|
||||
encoding: "utf8",
|
||||
timeout: 10_000,
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual({
|
||||
argvDecoyIgnored: true,
|
||||
alternatePaddingRead: true,
|
||||
appleVectorTokenFailsClosed: true,
|
||||
clearedAppleVectorTokenFailsClosed: true,
|
||||
callerPfzBeforeTokenRead: true,
|
||||
emptyLaterArgumentRead: true,
|
||||
emptyEnvironmentFailsClosed: true,
|
||||
emptyArgv0Read: true,
|
||||
emptyEnvironmentRecordsBeforeTokenFailClosed: true,
|
||||
duplicateTokenFailsClosed: true,
|
||||
finalAssignmentArgumentRead: true,
|
||||
missingAppleBoundaryFailsClosed: true,
|
||||
nonAsciiPathRead: true,
|
||||
realTokenRead: true,
|
||||
reservedArgumentIgnored: true,
|
||||
truncatedArgvFailsClosed: true,
|
||||
zeroArgumentsRead: true,
|
||||
});
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(!onDarwin)(
|
||||
"retries a growing process table after ENOMEM and preserves other sysctl errors",
|
||||
async () => {
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "rea-process-snapshot-retry-test-"),
|
||||
);
|
||||
const executable = join(root, "snapshot-probe");
|
||||
const core = fileURLToPath(
|
||||
new URL(
|
||||
"../../../bridge/process/ProcessRunTokenReader.swift",
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
const fixture = fileURLToPath(
|
||||
new URL(
|
||||
"../../fixtures/processRunTokenSnapshotProbe.swift",
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
try {
|
||||
await execFileOutput(
|
||||
"/usr/bin/xcrun",
|
||||
[
|
||||
"swiftc",
|
||||
"-module-cache-path",
|
||||
join(root, "modules"),
|
||||
core,
|
||||
fixture,
|
||||
"-o",
|
||||
executable,
|
||||
],
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
const { stdout } = await execFileAsync(executable, [], {
|
||||
encoding: "utf8",
|
||||
timeout: 10_000,
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual({
|
||||
preservedOtherErrno: true,
|
||||
retriedAfterFreshSize: true,
|
||||
});
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(!onDarwin)(
|
||||
"reads only the exact ownership key from live process environments",
|
||||
async () => {
|
||||
const host = createSystemProcessOwnershipHost("darwin");
|
||||
const decoy = await startNodeChild({
|
||||
DECOY: "words REA_PROCESS_RUN_ID=synthetic-decoy",
|
||||
});
|
||||
const owned = await startNodeChild({
|
||||
REA_PROCESS_RUN_ID: "synthetic-owned",
|
||||
});
|
||||
try {
|
||||
const processes = await host.listProcesses();
|
||||
const entries = [decoy, owned].map(({ pid }) => {
|
||||
const entry = processes.find((process) => process.pid === pid);
|
||||
if (entry === undefined)
|
||||
throw new Error("test child is absent from process table");
|
||||
return entry;
|
||||
});
|
||||
const observations = await host.runTokens?.(entries);
|
||||
const identities = await host.processIdentities?.(entries);
|
||||
expect(observations?.get(decoy.pid)).toEqual({
|
||||
state: "readable",
|
||||
runId: undefined,
|
||||
});
|
||||
expect(observations?.get(owned.pid)).toEqual({
|
||||
state: "readable",
|
||||
runId: "synthetic-owned",
|
||||
});
|
||||
expect(identities?.get(decoy.pid)?.state).toBe("readable");
|
||||
expect(identities?.get(owned.pid)?.state).toBe("readable");
|
||||
} finally {
|
||||
await stopNodeChild(decoy.child);
|
||||
await stopNodeChild(owned.child);
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(!onDarwin)(
|
||||
"reads owned tokens with empty later arguments across executable path padding",
|
||||
async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-process-token-padding-"));
|
||||
const host = createSystemProcessOwnershipHost("darwin");
|
||||
const children: Awaited<ReturnType<typeof startNodeChild>>[] = [];
|
||||
try {
|
||||
const executables = [join(root, "n"), join(root, "node")];
|
||||
for (const executable of executables)
|
||||
await symlink(process.execPath, executable);
|
||||
for (let index = 0; index < executables.length; index += 1) {
|
||||
const executable = executables[index];
|
||||
if (executable === undefined)
|
||||
throw new Error("test executable is missing");
|
||||
children.push(
|
||||
await startNodeChild(
|
||||
{ REA_PROCESS_RUN_ID: `synthetic-padding-${String(index)}` },
|
||||
executable,
|
||||
["-e", "setInterval(() => {}, 1_000)", "", "FOO=bar"],
|
||||
index === 0 ? "" : undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
const processes = await host.listProcesses();
|
||||
const entries = children.map(({ pid }) => {
|
||||
const entry = processes.find((process) => process.pid === pid);
|
||||
if (entry === undefined)
|
||||
throw new Error("owned test child is absent from process table");
|
||||
return entry;
|
||||
});
|
||||
const observations = await host.runTokens?.(entries);
|
||||
expect(children.map(({ pid }) => observations?.get(pid))).toEqual([
|
||||
{ state: "readable", runId: "synthetic-padding-0" },
|
||||
{ state: "readable", runId: "synthetic-padding-1" },
|
||||
]);
|
||||
} finally {
|
||||
for (const { child } of children) await stopNodeChild(child);
|
||||
await host.close?.();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const startNodeChild = async (
|
||||
environment: NodeJS.ProcessEnv,
|
||||
command = process.execPath,
|
||||
arguments_: readonly string[] = ["-e", "setInterval(() => {}, 1_000)"],
|
||||
argv0?: string,
|
||||
) => {
|
||||
const child = spawn(command, [...arguments_], {
|
||||
env: environment,
|
||||
stdio: "ignore",
|
||||
...(argv0 === undefined ? {} : { argv0 }),
|
||||
});
|
||||
if (child.pid === undefined)
|
||||
throw new Error("test child did not receive a PID");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("spawn", resolve);
|
||||
child.once("error", reject);
|
||||
});
|
||||
return { child, pid: child.pid };
|
||||
};
|
||||
|
||||
const stopNodeChild = async (child: ChildProcess) => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolve) =>
|
||||
child.once("exit", () => resolve()),
|
||||
);
|
||||
child.kill("SIGKILL");
|
||||
await exited;
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
spawnOwnedProviderProcess,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"does not block when an observed regular file is replaced by a FIFO",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-fifo-");
|
||||
const probe = fileURLToPath(
|
||||
new URL(
|
||||
"../../fixtures/filesystemSnapshotFifoProbe.mjs",
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
const snapshotModule = fileURLToPath(
|
||||
new URL(
|
||||
"../../../dist/process/capture/FilesystemSnapshot.js",
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
const launch = await spawnOwnedProviderProcess({
|
||||
command: process.execPath,
|
||||
arguments: [probe, snapshotModule, directory],
|
||||
runId: `rea-snapshot-fifo-${randomUUID()}`,
|
||||
cwd: tmpdir(),
|
||||
hostEnvironment: process.env,
|
||||
});
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
...launch,
|
||||
ownsProcessLifetime: true,
|
||||
});
|
||||
|
||||
try {
|
||||
const closed = await supervisor.waitForOutputClose(2_000);
|
||||
expect(closed).toBe(true);
|
||||
expect(supervisor.snapshot().stdout.text.trim()).toBe("rejected");
|
||||
} finally {
|
||||
const stopped = await supervisor.stop({
|
||||
terminationGraceMs: 100,
|
||||
killGraceMs: 500,
|
||||
});
|
||||
expect(stopped.status).not.toBe("incomplete");
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,186 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
OwnedCommandFailure,
|
||||
runOwnedCommand,
|
||||
} from "../../../src/process/OwnedCommand.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
|
||||
|
||||
const command = (script: string) => ({
|
||||
command: process.execPath,
|
||||
arguments: ["-e", script],
|
||||
runId: `rea-owned-command-test-${randomUUID()}`,
|
||||
});
|
||||
|
||||
it("includes ownership preparation in the command deadline before provider creation", async () => {
|
||||
let prepared = false;
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
command("process.exit(0)"),
|
||||
{
|
||||
timeoutMs: 20,
|
||||
diagnosticBytes: 1024,
|
||||
},
|
||||
{
|
||||
launcher: async (input) => {
|
||||
await delay(80, undefined, { signal: input.signal });
|
||||
prepared = true;
|
||||
throw new Error(
|
||||
"Slow preparation must be aborted before provider creation",
|
||||
);
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "timeout", snapshot: null });
|
||||
expect(prepared).toBe(false);
|
||||
});
|
||||
|
||||
it("passes cancellation into native ownership preparation before provider creation", async () => {
|
||||
const controller = new AbortController();
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
command("process.exit(0)"),
|
||||
{ timeoutMs: 2000, diagnosticBytes: 1024 },
|
||||
{
|
||||
signal: controller.signal,
|
||||
launcher: async (input) => {
|
||||
expect(input.signal?.aborted).toBe(false);
|
||||
controller.abort();
|
||||
input.signal?.throwIfAborted();
|
||||
throw new Error("Cancelled preparation must not launch a provider");
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "cancelled", snapshot: null });
|
||||
});
|
||||
|
||||
it("bounds retained diagnostics across both streams during a real output burst", async () => {
|
||||
try {
|
||||
await runOwnedCommand(
|
||||
command(
|
||||
'process.stdout.write("a".repeat(256 * 1024)); process.stderr.write("b".repeat(256 * 1024))',
|
||||
),
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
);
|
||||
throw new Error("An oversized producer must fail");
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof OwnedCommandFailure)) throw cause;
|
||||
expect(cause.reason).toBe("output-limit");
|
||||
expect(cause.snapshot).not.toBeNull();
|
||||
expect(
|
||||
(cause.snapshot?.stdout.bytes ?? 0) + (cause.snapshot?.stderr.bytes ?? 0),
|
||||
).toBeLessThanOrEqual(1024);
|
||||
}
|
||||
});
|
||||
|
||||
it("collects a real owned command and verifies its exit before returning diagnostics", async () => {
|
||||
const result = await runOwnedCommand(
|
||||
command('process.stdout.write("observed-output")'),
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
stdout: { text: "observed-output", bytes: 15 },
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels a real acquired process and independently releases it", async () => {
|
||||
const controller = new AbortController();
|
||||
let pid: number | undefined;
|
||||
const result = runOwnedCommand(
|
||||
command(
|
||||
'process.stdout.write("ready\\n"); setInterval(() => undefined, 1000)',
|
||||
),
|
||||
{ timeoutMs: 5_000, diagnosticBytes: 1024 },
|
||||
{
|
||||
signal: controller.signal,
|
||||
launcher: async (input) => {
|
||||
const process = await spawnOwnedProviderProcess(input);
|
||||
pid = process.process.pid;
|
||||
await waitForProviderProcessReady(process.process);
|
||||
setImmediate(() => controller.abort());
|
||||
return process;
|
||||
},
|
||||
},
|
||||
);
|
||||
await expect(result).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
cleanupFailure: null,
|
||||
});
|
||||
if (pid === undefined) throw new Error("Process was not acquired");
|
||||
const acquiredPid = pid;
|
||||
expect(() => process.kill(acquiredPid, 0)).toThrow();
|
||||
});
|
||||
|
||||
it("returns a timeout for a running process after independent cleanup", async () => {
|
||||
await expect(
|
||||
runOwnedCommand(command("setInterval(() => undefined, 1000)"), {
|
||||
timeoutMs: 50,
|
||||
diagnosticBytes: 1024,
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "timeout", cleanupFailure: null });
|
||||
});
|
||||
|
||||
it("honors cancellation during cleanup after a successful command", async () => {
|
||||
const controller = new AbortController();
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
command("process.exit(0)"),
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
{
|
||||
signal: controller.signal,
|
||||
launcher: async (input) => {
|
||||
const launched = await spawnOwnedProviderProcess(input);
|
||||
return {
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
const result = await cleanupOwnedProcessGroup(launched.ownership);
|
||||
controller.abort();
|
||||
return result;
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "cancelled", cleanupFailure: null });
|
||||
});
|
||||
|
||||
it("rejects oversized diagnostics even when the child exits immediately", async () => {
|
||||
await expect(
|
||||
runOwnedCommand(command('process.stdout.write("x".repeat(2048))'), {
|
||||
timeoutMs: 2_000,
|
||||
diagnosticBytes: 1024,
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "output-limit", cleanupFailure: null });
|
||||
});
|
||||
|
||||
it("preserves original command failure together with failed cleanup resource identities", async () => {
|
||||
const request = command("process.exit(2)");
|
||||
await expect(
|
||||
runOwnedCommand(
|
||||
request,
|
||||
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
|
||||
{
|
||||
launcher: async (input) => {
|
||||
const process = await spawnOwnedProviderProcess(input);
|
||||
return {
|
||||
...process,
|
||||
cleanup: async () => ({
|
||||
cleaned: false as const,
|
||||
reason: "synthetic cleanup could not be confirmed",
|
||||
}),
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
reason: "process",
|
||||
cleanupFailure: "synthetic cleanup could not be confirmed",
|
||||
resources: expect.arrayContaining([request.runId]),
|
||||
snapshot: { exitCode: 2 },
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
processCaptureProbeFailureReason,
|
||||
processCaptureOwnershipUnavailableReason,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessCaptureCapability.js";
|
||||
} from "../../../src/process/capture/ProcessCaptureCapability.js";
|
||||
|
||||
describe("process capture capability diagnostics", () => {
|
||||
it("distinguishes missing native modules from runtime ABI mismatches", () => {
|
||||
@@ -52,6 +52,31 @@ describe("process capture capability diagnostics", () => {
|
||||
).toContain("spawn EACCES");
|
||||
});
|
||||
|
||||
it("prepares Darwin ownership inspection before probing or admitting a PTY", async () => {
|
||||
let loaded = false;
|
||||
const capability = await probeProcessCaptureCapability({
|
||||
platform: "darwin",
|
||||
prepareOwnershipInspector: async () => {
|
||||
throw new Error(
|
||||
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
|
||||
);
|
||||
},
|
||||
loadPty: async () => {
|
||||
loaded = true;
|
||||
return await import("@lydell/node-pty");
|
||||
},
|
||||
});
|
||||
|
||||
expect(loaded).toBe(false);
|
||||
expect(capability).toEqual({
|
||||
available: false,
|
||||
backend: "node-pty",
|
||||
reason: expect.stringContaining(
|
||||
"requires the Apple Swift compiler via xcrun",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the ownership limitation separate from native PTY support", () => {
|
||||
expect(processCaptureOwnershipUnavailableReason("win32")).toContain(
|
||||
"Windows PTY process capture",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { it } from "vitest";
|
||||
|
||||
import { probeProcessCaptureCapability } from "../../../src/application/ProcessCaptureCapability.js";
|
||||
import { probeProcessCaptureCapability } from "../../../src/process/capture/ProcessCaptureCapability.js";
|
||||
|
||||
/**
|
||||
* Process-capture tests need real native PTY authority. Probing once at module
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm, symlink } from "node:fs/promises";
|
||||
import { access, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
@@ -7,14 +8,378 @@ import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { itWithCaptureCapability } from "./processCaptureCapability.js";
|
||||
|
||||
import { captureProcessScenario } from "../../../src/application/ProcessHarness.js";
|
||||
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
|
||||
import { captureProcessScenario } from "../../../src/process/capture/ProcessHarness.js";
|
||||
import { snapshotRoots } from "../../../src/process/capture/FilesystemSnapshot.js";
|
||||
import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js";
|
||||
import {
|
||||
type ProcessCaptureCleanupHost,
|
||||
observeLaunchedExecutable,
|
||||
observeSelectedExecutable,
|
||||
} from "../../../src/process/capture/ProcessCaptureLifecycle.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/process/processCapture.js";
|
||||
|
||||
const processFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFidelity.mjs", import.meta.url),
|
||||
);
|
||||
const snapshotCancellationFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processSnapshotCancellation.mjs", import.meta.url),
|
||||
);
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
type CaptureRun = Awaited<ReturnType<typeof captureProcessScenario>>;
|
||||
type PartialCapture = Extract<
|
||||
NonNullable<ProcessCaptureError["partialObservation"]>,
|
||||
{ readonly capture: unknown }
|
||||
>["capture"];
|
||||
const captureObservations = (
|
||||
result: CaptureRun,
|
||||
): {
|
||||
readonly capture: ProcessCapture | PartialCapture;
|
||||
readonly cleanupIncomplete: boolean;
|
||||
} => {
|
||||
if (result.ok) return { capture: result.value, cleanupIncomplete: false };
|
||||
if (!(result.error instanceof ProcessCaptureError)) throw result.error;
|
||||
const report = result.error.cleanupReport;
|
||||
const partial = result.error.partialObservation;
|
||||
expect(result.error.reason).toBe("cleanup_incomplete");
|
||||
expect(report?.owned_process_group.state).toBe("unverified");
|
||||
const [summary, breakdown] = (report?.owned_process_group.reason ?? "").split(
|
||||
": ",
|
||||
);
|
||||
expect(summary).toMatch(
|
||||
/^process ownership token could not be read for [1-9][0-9]* live process\(es\)$/u,
|
||||
);
|
||||
const categories = breakdown?.split(", ") ?? [];
|
||||
expect(categories.length).toBeGreaterThan(0);
|
||||
const expectedCategory =
|
||||
process.platform === "linux"
|
||||
? /^environment_errno_(?:EACCES|EPERM)=[1-9][0-9]*$/u
|
||||
: /^environment_unavailable=[1-9][0-9]*$/u;
|
||||
for (const category of categories) expect(category).toMatch(expectedCategory);
|
||||
expect(report?.terminal_renderer.state).toBe("cleaned");
|
||||
expect(report?.temporary_root.state).toBe("cleaned");
|
||||
if (partial === undefined || !("capture" in partial))
|
||||
throw new Error(
|
||||
"cleanup-incomplete capture omitted completed observations",
|
||||
);
|
||||
const capture = partial.capture;
|
||||
expect(capture.settlement.cleanup_outcome).toBe("failed");
|
||||
return { capture, cleanupIncomplete: true };
|
||||
};
|
||||
|
||||
const processState = async (pid: number): Promise<string | undefined> => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync("ps", [
|
||||
"-o",
|
||||
"stat=",
|
||||
"-p",
|
||||
String(pid),
|
||||
]);
|
||||
return stdout.trim() || undefined;
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === 1 &&
|
||||
"stdout" in cause &&
|
||||
cause.stdout === ""
|
||||
)
|
||||
return undefined;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const waitForProcessExit = async (pid: number): Promise<void> => {
|
||||
const deadline = Date.now() + 2_000;
|
||||
while (Date.now() < deadline) {
|
||||
const state = await processState(pid);
|
||||
if (state === undefined || state.startsWith("Z")) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
throw new Error(`Process ${String(pid)} did not exit within the test bound`);
|
||||
};
|
||||
|
||||
const readDetachedFixturePids = async (marker: string): Promise<number[]> => {
|
||||
let contents: string;
|
||||
try {
|
||||
contents = await readFile(marker, "utf8");
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return [];
|
||||
throw cause;
|
||||
}
|
||||
const parsed: unknown = JSON.parse(contents);
|
||||
if (typeof parsed !== "object" || parsed === null) return [];
|
||||
const candidatePids = [
|
||||
"ownedPid" in parsed ? parsed.ownedPid : undefined,
|
||||
"unownedPid" in parsed ? parsed.unownedPid : undefined,
|
||||
];
|
||||
return candidatePids.flatMap((pid) =>
|
||||
typeof pid === "number" && Number.isSafeInteger(pid) && pid > 1
|
||||
? [pid]
|
||||
: [],
|
||||
);
|
||||
};
|
||||
|
||||
const terminateFixtureProcess = async (pid: number): Promise<void> => {
|
||||
try {
|
||||
process.kill(pid, "SIGKILL");
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
|
||||
throw cause;
|
||||
}
|
||||
await waitForProcessExit(pid);
|
||||
};
|
||||
|
||||
itWithCaptureCapability(
|
||||
"cleans detached run-token children omitted by sampling and preserves an unowned neighbor",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-detached-cleanup-");
|
||||
const pidMarker = join(root, "children.json");
|
||||
let ownedPid: number | undefined;
|
||||
let unownedPid: number | undefined;
|
||||
try {
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "detached-cleanup", pidMarker],
|
||||
working_directory: root,
|
||||
settle_ms: 0,
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 5_000,
|
||||
limits: { processes: 1 },
|
||||
}),
|
||||
);
|
||||
const { capture, cleanupIncomplete } = captureObservations(result);
|
||||
const parsed: unknown = JSON.parse(await readFile(pidMarker, "utf8"));
|
||||
if (
|
||||
typeof parsed !== "object" ||
|
||||
parsed === null ||
|
||||
!("ownedPid" in parsed) ||
|
||||
typeof parsed.ownedPid !== "number" ||
|
||||
!("unownedPid" in parsed) ||
|
||||
typeof parsed.unownedPid !== "number"
|
||||
)
|
||||
throw new TypeError("detached-child fixture wrote invalid PIDs");
|
||||
// Register fixture children before assertions so teardown can clean them
|
||||
// even when a later expectation fails.
|
||||
ownedPid = parsed.ownedPid;
|
||||
unownedPid = parsed.unownedPid;
|
||||
expect(capture.process_samples.some(({ pid }) => pid === ownedPid)).toBe(
|
||||
false,
|
||||
);
|
||||
if (cleanupIncomplete)
|
||||
expect(capture.settlement.cleanup_outcome).toBe("failed");
|
||||
else
|
||||
expect(result.ok && result.value.cleanup.owned_process_group).toBe(
|
||||
"verified",
|
||||
);
|
||||
await waitForProcessExit(ownedPid);
|
||||
const unownedState = await processState(unownedPid);
|
||||
expect(unownedState).toBeDefined();
|
||||
expect(unownedState?.startsWith("Z")).toBe(false);
|
||||
} finally {
|
||||
try {
|
||||
let fixturePids: number[] = [];
|
||||
let teardownFailure: unknown;
|
||||
try {
|
||||
fixturePids = await readDetachedFixturePids(pidMarker);
|
||||
} catch (cause: unknown) {
|
||||
teardownFailure = cause;
|
||||
}
|
||||
for (const pid of new Set([
|
||||
...fixturePids,
|
||||
...(ownedPid === undefined ? [] : [ownedPid]),
|
||||
...(unownedPid === undefined ? [] : [unownedPid]),
|
||||
])) {
|
||||
try {
|
||||
await terminateFixtureProcess(pid);
|
||||
} catch (cause: unknown) {
|
||||
teardownFailure ??= cause;
|
||||
}
|
||||
}
|
||||
if (teardownFailure !== undefined) throw teardownFailure;
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"retains collected observations when completion and cleanup both fail",
|
||||
async () => {
|
||||
let snapshotCalls = 0;
|
||||
const captureSnapshot: typeof snapshotRoots = async () => {
|
||||
snapshotCalls += 1;
|
||||
if (snapshotCalls === 1) return { files: [], truncated: false };
|
||||
throw new Error("fixture final snapshot failure");
|
||||
};
|
||||
const cleanupHost: ProcessCaptureCleanupHost = {
|
||||
platform: process.platform,
|
||||
cleanupProcessGroup: async () => ({
|
||||
cleaned: false,
|
||||
reason: "fixture cleanup could not be verified",
|
||||
}),
|
||||
verifyTokenOwnedProcesses: async () => ({
|
||||
cleaned: false,
|
||||
reason: "fixture cleanup could not be verified",
|
||||
}),
|
||||
removeTemporaryRoot: async (path) =>
|
||||
rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "partial"],
|
||||
working_directory: dirname(processFixture),
|
||||
settle_ms: 0,
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
undefined,
|
||||
process.platform,
|
||||
process.env,
|
||||
captureSnapshot,
|
||||
cleanupHost,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected cleanup-incomplete failure");
|
||||
if (!(result.error instanceof ProcessCaptureError)) throw result.error;
|
||||
const partial = result.error.partialObservation;
|
||||
expect(result.error.reason).toBe("cleanup_incomplete");
|
||||
expect(result.error.executionFailure).toBe(
|
||||
"fixture final snapshot failure",
|
||||
);
|
||||
expect(partial).toBeDefined();
|
||||
if (partial === undefined || !("observations" in partial))
|
||||
throw new Error("expected incomplete process observations");
|
||||
const observations = partial.observations;
|
||||
expect(observations.frames.state).toBe("available");
|
||||
if (observations.frames.state !== "available")
|
||||
throw new Error("expected terminal output observations");
|
||||
expect(
|
||||
observations.frames.value.map(({ data }) => data).join(""),
|
||||
).toContain("partial-frame");
|
||||
expect(observations.rendered_frames.state).toBe("available");
|
||||
if (observations.rendered_frames.state !== "available")
|
||||
throw new Error("expected rendered terminal observations");
|
||||
expect(observations.rendered_frames.value.length).toBeGreaterThan(0);
|
||||
expect(observations.interaction_events.state).toBe("available");
|
||||
expect(observations.exit).toMatchObject({
|
||||
state: "available",
|
||||
value: { reason: "exited" },
|
||||
});
|
||||
expect(observations.settlement.state).toBe("available");
|
||||
expect(observations.process_samples.state).toBe("available");
|
||||
expect(observations.target_pid).toEqual({ state: "available", value: 1 });
|
||||
expect(observations.filesystem_snapshots.before.state).toBe("available");
|
||||
if (observations.filesystem_snapshots.before.state !== "available")
|
||||
throw new Error("expected initial filesystem snapshot");
|
||||
expect(observations.filesystem_snapshots.before.value.truncated).toBe(
|
||||
false,
|
||||
);
|
||||
expect(observations.filesystem_snapshots.after).toEqual({
|
||||
state: "unavailable",
|
||||
reason:
|
||||
"Final filesystem snapshot failed: fixture final snapshot failure",
|
||||
});
|
||||
expect(observations.event_journal.state).toBe("available");
|
||||
if (observations.event_journal.state !== "available")
|
||||
throw new Error("expected capture event journal");
|
||||
expect(
|
||||
observations.event_journal.value.some(
|
||||
({ collection }) => collection === "lifecycle",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(observations.manifest.state).toBe("unavailable");
|
||||
expect(snapshotCalls).toBe(2);
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"keeps selected executable evidence separate when the path identity changes before validation",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-executable-replaced-");
|
||||
const executable = join(root, "selected-executable");
|
||||
await symlink(process.execPath, executable);
|
||||
try {
|
||||
const selected = await observeSelectedExecutable(executable);
|
||||
expect(selected.sha256).toMatch(/^[a-f0-9]{64}$/u);
|
||||
await rm(executable);
|
||||
await symlink("/bin/sh", executable);
|
||||
expect(observeLaunchedExecutable(executable, selected)).toEqual({
|
||||
selectedSha256: selected.sha256,
|
||||
sha256: null,
|
||||
state: "unknown",
|
||||
reason: "Executable path metadata changed between sampling and spawn.",
|
||||
});
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"keeps the prelaunch executable sample when the selected path is replaced during capture",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-executable-identity-");
|
||||
const executable = join(root, "selected-executable");
|
||||
const readyMarker = join(root, "child-ready");
|
||||
await symlink(process.execPath, executable);
|
||||
const launchedDigest = createHash("sha256")
|
||||
.update(await readFile(process.execPath))
|
||||
.digest("hex");
|
||||
try {
|
||||
const capturePromise = captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable,
|
||||
arguments: [processFixture, "ready-hang", readyMarker],
|
||||
working_directory: root,
|
||||
timeout_ms: 1_500,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
);
|
||||
const deadline = Date.now() + 2_000;
|
||||
let ready = false;
|
||||
while (!ready && Date.now() < deadline) {
|
||||
try {
|
||||
await access(readyMarker);
|
||||
ready = true;
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
expect(ready).toBe(true);
|
||||
await rm(executable);
|
||||
await symlink("/bin/sh", executable);
|
||||
const result = await capturePromise;
|
||||
const { capture } = captureObservations(result);
|
||||
expect(capture.manifest).toMatchObject({
|
||||
selected_executable_sha256: launchedDigest,
|
||||
executable_sha256: launchedDigest,
|
||||
executable_identity: {
|
||||
state: "path_metadata_unchanged",
|
||||
reason: null,
|
||||
},
|
||||
});
|
||||
expect(capture.exit.reason).toBe("timeout");
|
||||
expect(capture.limitations).toContain(
|
||||
"The executable digest is a prelaunch file sample; matching path metadata immediately after spawn does not prove an atomic operating-system image binding.",
|
||||
);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"records external symlink metadata without following the target",
|
||||
async () => {
|
||||
@@ -28,16 +393,15 @@ itWithCaptureCapability(
|
||||
filesystem_observation_paths: [root],
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
const escaped = result.value.files_after.find((file) =>
|
||||
const { capture } = captureObservations(result);
|
||||
const escaped = capture.files_after.find((file) =>
|
||||
file.path.endsWith(":escape"),
|
||||
);
|
||||
expect(escaped?.symlink_target).toBe("/etc/passwd");
|
||||
expect(result.value.truncated).toBe(false);
|
||||
expect(JSON.stringify(result.value.files_after)).not.toContain(root);
|
||||
expect(capture.truncated).toBe(false);
|
||||
expect(JSON.stringify(capture.files_after)).not.toContain(root);
|
||||
expect(
|
||||
result.value.files_after.some((file) => file.path.includes("passwd")),
|
||||
capture.files_after.some((file) => file.path.includes("passwd")),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
@@ -57,13 +421,13 @@ itWithCaptureCapability(
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
);
|
||||
expect(timedOut.ok).toBe(true);
|
||||
if (!timedOut.ok) throw timedOut.error;
|
||||
expect(timedOut.value.exit.reason).toBe("timeout");
|
||||
expect(timedOut.value.cleanup).toEqual({
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
});
|
||||
const timedOutCapture = captureObservations(timedOut);
|
||||
expect(timedOutCapture.capture.exit.reason).toBe("timeout");
|
||||
if (!timedOutCapture.cleanupIncomplete && timedOut.ok)
|
||||
expect(timedOut.value.cleanup).toEqual({
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
});
|
||||
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), 50);
|
||||
@@ -83,6 +447,114 @@ itWithCaptureCapability(
|
||||
},
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"classifies cancellation raised by the initial filesystem snapshot",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-snapshot-initial-cancel-");
|
||||
const path = join(root, "input");
|
||||
await writeFile(path, "observed\n");
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const throwIfAborted = signal.throwIfAborted.bind(signal);
|
||||
Object.defineProperty(signal, "throwIfAborted", {
|
||||
value: () => {
|
||||
controller.abort();
|
||||
throwIfAborted();
|
||||
},
|
||||
});
|
||||
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [path],
|
||||
}),
|
||||
signal,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected initial snapshot cancellation");
|
||||
expect(result.error).toMatchObject({
|
||||
reason: "cancelled",
|
||||
userCategory: "cancelled",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"classifies cancellation raised by the final filesystem snapshot",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-snapshot-final-cancel-");
|
||||
const controller = new AbortController();
|
||||
let initialSnapshotCompleted = false;
|
||||
const captureSnapshot: typeof snapshotRoots = async (scenario, signal) => {
|
||||
if (initialSnapshotCompleted) controller.abort();
|
||||
const snapshot = await snapshotRoots(scenario, signal);
|
||||
initialSnapshotCompleted = true;
|
||||
return snapshot;
|
||||
};
|
||||
const resultPromise = captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [snapshotCancellationFixture, root],
|
||||
working_directory: dirname(snapshotCancellationFixture),
|
||||
filesystem_observation_paths: [root],
|
||||
settle_ms: 0,
|
||||
}),
|
||||
controller.signal,
|
||||
process.platform,
|
||||
process.env,
|
||||
captureSnapshot,
|
||||
);
|
||||
|
||||
const result = await resultPromise;
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected final snapshot cancellation");
|
||||
expect(initialSnapshotCompleted).toBe(true);
|
||||
expect(result.error).toMatchObject({
|
||||
reason: "cancelled",
|
||||
userCategory: "cancelled",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"preserves filesystem errors that are not caller cancellation",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-snapshot-io-error-");
|
||||
const obstruction = join(root, "not-a-directory");
|
||||
await writeFile(obstruction, "file");
|
||||
const controller = new AbortController();
|
||||
const captureSnapshot: typeof snapshotRoots = async (scenario, signal) => {
|
||||
try {
|
||||
return await snapshotRoots(scenario, signal);
|
||||
} catch (cause: unknown) {
|
||||
controller.abort();
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [join(obstruction, "child")],
|
||||
}),
|
||||
controller.signal,
|
||||
process.platform,
|
||||
process.env,
|
||||
captureSnapshot,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected filesystem observation failure");
|
||||
expect(result.error).toMatchObject({
|
||||
reason: "capture_failed",
|
||||
cause: { code: "ENOTDIR" },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"captures input, Unicode, and resize across PTY startup",
|
||||
async () => {
|
||||
@@ -100,17 +572,16 @@ itWithCaptureCapability(
|
||||
idle_timeout_ms: 10_000,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.ok).toBe(true);
|
||||
const output = result.value.frames.map(({ data }) => data).join("");
|
||||
const { capture } = captureObservations(result);
|
||||
const output = capture.frames.map(({ data }) => data).join("");
|
||||
expect(output).toContain("prompt>");
|
||||
expect(output).toContain("input:answer unicode:雪");
|
||||
expect(output).toContain("resize:100x40");
|
||||
expect(result.value.interaction_events).toMatchObject([
|
||||
expect(capture.interaction_events).toMatchObject([
|
||||
{ type: "resize", outcome: "dispatched", scheduled_at_ms: 0 },
|
||||
{ type: "input", outcome: "dispatched", scheduled_at_ms: 0 },
|
||||
]);
|
||||
const resized = result.value.rendered_frames.find(
|
||||
const resized = capture.rendered_frames.find(
|
||||
({ columns, rows, lines }) =>
|
||||
columns === 100 &&
|
||||
rows === 40 &&
|
||||
@@ -118,7 +589,7 @@ itWithCaptureCapability(
|
||||
);
|
||||
expect(resized).toBeDefined();
|
||||
expect(resized?.lines.join("\n")).toContain("input:answer unicode:雪");
|
||||
expect(result.value.exit.code).toBe(0);
|
||||
expect(capture.exit.code).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -135,12 +606,11 @@ itWithCaptureCapability(
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.interaction_events).toMatchObject([
|
||||
const { capture } = captureObservations(result);
|
||||
expect(capture.interaction_events).toMatchObject([
|
||||
{ type: "signal", data: "SIGTERM", outcome: "dispatched" },
|
||||
]);
|
||||
expect(result.value.exit).toMatchObject({ signal: 15, reason: "exited" });
|
||||
expect(capture.exit).toMatchObject({ signal: 15, reason: "exited" });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -160,24 +630,22 @@ itWithCaptureCapability(
|
||||
idle_timeout_ms: 20_000,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.frames.map(({ data }) => data).join("")).toContain(
|
||||
const { capture } = captureObservations(result);
|
||||
expect(capture.frames.map(({ data }) => data).join("")).toContain(
|
||||
"input:answer",
|
||||
);
|
||||
expect(result.value.interaction_events).toMatchObject([
|
||||
expect(capture.interaction_events).toMatchObject([
|
||||
{ type: "resize", scheduled_at_ms: 25, outcome: "dispatched" },
|
||||
{ type: "input", scheduled_at_ms: 50, outcome: "dispatched" },
|
||||
]);
|
||||
expect(
|
||||
result.value.interaction_events.every(
|
||||
capture.interaction_events.every(
|
||||
({ scheduled_at_ms, dispatched_at_ms }) =>
|
||||
dispatched_at_ms >= scheduled_at_ms,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.value.frames.find(({ data }) => data.includes("input:answer"))
|
||||
?.at_ms,
|
||||
capture.frames.find(({ data }) => data.includes("input:answer"))?.at_ms,
|
||||
).toBeGreaterThanOrEqual(50);
|
||||
},
|
||||
);
|
||||
@@ -194,13 +662,12 @@ itWithCaptureCapability(
|
||||
idle_timeout_ms: 20_000,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.exit).toMatchObject({ code: 0, reason: "exited" });
|
||||
expect(result.value.frames.map(({ data }) => data).join("")).toContain(
|
||||
const { capture } = captureObservations(result);
|
||||
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
|
||||
expect(capture.frames.map(({ data }) => data).join("")).toContain(
|
||||
"tree-ready",
|
||||
);
|
||||
const commands = result.value.process_samples.map(({ command }) => command);
|
||||
const commands = capture.process_samples.map(({ command }) => command);
|
||||
expect(commands.some((command) => command.includes("tree-child"))).toBe(
|
||||
true,
|
||||
);
|
||||
@@ -210,7 +677,7 @@ itWithCaptureCapability(
|
||||
expect(
|
||||
commands.some((command) => command.includes("tree-grandchild")),
|
||||
).toBe(true);
|
||||
expect(JSON.stringify(result.value.process_samples)).toContain(
|
||||
expect(JSON.stringify(capture.process_samples)).toContain(
|
||||
dirname(processFixture),
|
||||
);
|
||||
const { stdout } = await execFileAsync("ps", ["-axo", "command="]);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user