fix(ida): reconcile native bridge with main and verify function switching
Merge the PR 1544 native IDA bridge onto current main and validate two-function pseudocode identity with a unique second-body marker. Preserve current input-error and GUI-effect semantics, identify the adapter without implying an IDA edition, and document the upstream listener and navigation limits. Verified on Windows IDA Pro 9.3 through the attached legacy MCP workflow: production CLI/MCP analysis, distinct-function pseudocode, return to the original function, target identity, and cleanup. Native Windows plugin and IDA Free runtime workflows were not verified in this follow-up. No private target paths or license details are included.
This commit is contained in:
@@ -0,0 +1,260 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
const createModuleLookupFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-module-lookup-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": JSON.stringify({
|
||||
name: "module-lookup-fixture",
|
||||
type: "commonjs",
|
||||
}),
|
||||
"esm/entry.mjs": [
|
||||
'import "./extensionless";',
|
||||
'import "./directory";',
|
||||
'import "./explicit.js";',
|
||||
'import "./exact.js";',
|
||||
'import "./actual.cjs?cache=1";',
|
||||
'import fallback from "empty-main";',
|
||||
'import "nested-main";',
|
||||
'import "file-only";',
|
||||
'import "ancestor-empty";',
|
||||
'import "ancestor-blocked";',
|
||||
'import "ancestor-sub/parser";',
|
||||
"void fallback;",
|
||||
].join("\n"),
|
||||
"esm/extensionless.js": "module.exports = 1;",
|
||||
"esm/directory/index.js": "module.exports = 2;",
|
||||
"esm/explicit.js.js": "module.exports = 3;",
|
||||
"esm/exact.js": "module.exports = 4;",
|
||||
"esm/actual.cjs": "module.exports = 5;",
|
||||
"esm/typed.mts": 'import value from "./typed-dep.js"; void value;',
|
||||
"esm/typed-dep.ts": "export default 42;",
|
||||
"cjs/entry.cjs": [
|
||||
'require("./extensionless");',
|
||||
'require("./directory");',
|
||||
'require("./feature");',
|
||||
'require("./feature.cjs");',
|
||||
'require("./module-only");',
|
||||
'require("./valid-directory");',
|
||||
'require("./default-js");',
|
||||
'require("./default-json");',
|
||||
'require("./default-node");',
|
||||
'require("empty-main");',
|
||||
'require("nested-main");',
|
||||
'require("file-only");',
|
||||
'require("ancestor-empty");',
|
||||
'require("ancestor-blocked");',
|
||||
'require("ancestor-sub/parser");',
|
||||
].join("\n"),
|
||||
"cjs/directory/index.cjs": "module.exports = 6;",
|
||||
"cjs/extensionless.cjs": "module.exports = 1;",
|
||||
"cjs/feature.cjs": "module.exports = 2;",
|
||||
"cjs/module-only.mjs": "export default 42;",
|
||||
"cjs/valid-directory/index.js": "module.exports = 42;",
|
||||
"cjs/typed.cts":
|
||||
'const value = require("./typed-dep.cjs"); module.exports = value;',
|
||||
"cjs/typed-dep.cts": "module.exports = 42;",
|
||||
"cjs/default-js.js": "module.exports = 3;",
|
||||
"cjs/default-json.json": JSON.stringify({ value: 4 }),
|
||||
// Inventory-only placeholder: never pass this path to Node's runtime.
|
||||
"cjs/default-node.node": "source-owned opaque native-module placeholder",
|
||||
"node_modules/empty-main/package.json": JSON.stringify({ main: "" }),
|
||||
"node_modules/empty-main/index.js": "module.exports = 42;",
|
||||
"node_modules/nested-main/package.json": JSON.stringify({ main: "sub" }),
|
||||
"node_modules/nested-main/sub/package.json": JSON.stringify({
|
||||
main: "other",
|
||||
}),
|
||||
"node_modules/nested-main/sub/other.js": "module.exports = 99;",
|
||||
"node_modules/file-only.js": "module.exports = 7;",
|
||||
"node_modules/ancestor-empty/index.js": "module.exports = 8;",
|
||||
"node_modules/ancestor-blocked/index.js": "module.exports = 9;",
|
||||
"node_modules/ancestor-sub/parser.js": "module.exports = 10;",
|
||||
"esm/runtime-control.mjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
|
||||
"const results = [];",
|
||||
"for (const specifier of specifiers) {",
|
||||
" try { const value = (await import(specifier)).default; results.push({ specifier, ok: true, value }); }",
|
||||
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
|
||||
"}",
|
||||
"console.log(JSON.stringify(results));",
|
||||
].join("\n"),
|
||||
"cjs/runtime-control.cjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
|
||||
"const results = [];",
|
||||
"for (const specifier of specifiers) {",
|
||||
" try { const value = require(specifier); results.push({ specifier, ok: true, value }); }",
|
||||
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
|
||||
"}",
|
||||
"console.log(JSON.stringify(results));",
|
||||
].join("\n"),
|
||||
});
|
||||
for (const directory of ["esm", "cjs"])
|
||||
await writeFixtureFiles(root, {
|
||||
[`${directory}/node_modules/ancestor-empty/package.json`]: JSON.stringify(
|
||||
{ main: "" },
|
||||
),
|
||||
[`${directory}/node_modules/ancestor-blocked/package.json`]:
|
||||
JSON.stringify({ main: "missing" }),
|
||||
[`${directory}/node_modules/ancestor-sub/package.json`]: "{}",
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"matches Node module lookup for ESM and CommonJS through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createModuleLookupFixture();
|
||||
const [esmControl, cjsControl] = await Promise.all([
|
||||
execute(process.execPath, ["esm/runtime-control.mjs"], {
|
||||
cwd: root,
|
||||
timeout: 5_000,
|
||||
}),
|
||||
execute(process.execPath, ["cjs/runtime-control.cjs"], {
|
||||
cwd: root,
|
||||
timeout: 5_000,
|
||||
}),
|
||||
]);
|
||||
const esmResults = JSON.parse(esmControl.stdout) as Array<{
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
}>;
|
||||
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
}>;
|
||||
expect(esmResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./explicit.js",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./exact.js", ok: true, value: 4 },
|
||||
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{
|
||||
specifier: "ancestor-blocked",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "ancestor-sub/parser",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
]);
|
||||
expect(cjsResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./feature",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./feature.cjs", ok: true, value: 2 },
|
||||
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "./valid-directory", ok: true, value: 42 },
|
||||
{ specifier: "./default-js", ok: true, value: 3 },
|
||||
{ specifier: "./default-json", ok: true, value: { value: 4 } },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: true, value: 7 },
|
||||
{ specifier: "ancestor-empty", ok: true, value: 8 },
|
||||
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
|
||||
]);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const expectations = [
|
||||
["import", "./extensionless", null, "not-found"],
|
||||
["import", "./directory", null, "not-found"],
|
||||
["import", "./explicit.js", null, "not-found"],
|
||||
["import", "./exact.js", "esm/exact.js", "resolved"],
|
||||
["import", "./actual.cjs?cache=1", "esm/actual.cjs", "resolved"],
|
||||
["import", "./typed-dep.js", "esm/typed-dep.ts", "resolved"],
|
||||
["import", "empty-main", "node_modules/empty-main/index.js", "resolved"],
|
||||
["import", "nested-main", null, "not-found"],
|
||||
["import", "file-only", null, "external"],
|
||||
["import", "ancestor-empty", null, "not-found"],
|
||||
["import", "ancestor-blocked", null, "not-found"],
|
||||
["import", "ancestor-sub/parser", null, "not-found"],
|
||||
["require", "./extensionless", null, "not-found"],
|
||||
["require", "./directory", null, "not-found"],
|
||||
["require", "./feature", null, "not-found"],
|
||||
["require", "./feature.cjs", "cjs/feature.cjs", "resolved"],
|
||||
["require", "./module-only", null, "not-found"],
|
||||
[
|
||||
"require",
|
||||
"./valid-directory",
|
||||
"cjs/valid-directory/index.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", "./typed-dep.cjs", "cjs/typed-dep.cts", "resolved"],
|
||||
["require", "./default-js", "cjs/default-js.js", "resolved"],
|
||||
["require", "./default-json", "cjs/default-json.json", "resolved"],
|
||||
["require", "./default-node", "cjs/default-node.node", "resolved"],
|
||||
["require", "empty-main", "node_modules/empty-main/index.js", "resolved"],
|
||||
["require", "nested-main", null, "not-found"],
|
||||
["require", "file-only", "node_modules/file-only.js", "resolved"],
|
||||
[
|
||||
"require",
|
||||
"ancestor-empty",
|
||||
"node_modules/ancestor-empty/index.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", "ancestor-blocked", null, "not-found"],
|
||||
[
|
||||
"require",
|
||||
"ancestor-sub/parser",
|
||||
"node_modules/ancestor-sub/parser.js",
|
||||
"resolved",
|
||||
],
|
||||
] as const;
|
||||
|
||||
for (const [kind, specifier, resolvedPath, status] of expectations)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: kind,
|
||||
specifier,
|
||||
resolved_path: resolvedPath,
|
||||
resolution_status: status,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,120 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"keeps dependency manifests out of application roots and Electron entries through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-application-manifest-");
|
||||
const dependency = join(root, "node_modules", "dep");
|
||||
const nested = join(root, "a");
|
||||
await Promise.all([mkdir(dependency, { recursive: true }), mkdir(nested)]);
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(nested, "package.json"),
|
||||
JSON.stringify({ name: "nested" }),
|
||||
),
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ name: "app", main: "main.js" }),
|
||||
),
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
"throw new Error('source must remain inert');",
|
||||
),
|
||||
writeFile(
|
||||
join(dependency, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "dep",
|
||||
main: "index.js",
|
||||
browser: "browser.js",
|
||||
}),
|
||||
),
|
||||
writeFile(join(dependency, "index.js"), "module.exports = {};"),
|
||||
writeFile(join(dependency, "browser.js"), "export const browser = true;"),
|
||||
]);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(document).normalized_result;
|
||||
expect(
|
||||
graph.nodes
|
||||
.filter(({ node_id }) => graph.root_node_ids.includes(node_id))
|
||||
.flatMap(({ observations }) => observations.map(({ label }) => label)),
|
||||
).toEqual(["app"]);
|
||||
expect(
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "electron-main")
|
||||
.flatMap(({ observations }) =>
|
||||
observations.map(({ properties }) => properties.declared_path),
|
||||
),
|
||||
).toEqual(["main.js"]);
|
||||
expect(
|
||||
graph.nodes.filter(({ kind }) => kind === "electron-renderer"),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "package")
|
||||
.flatMap(({ observations }) => observations.map(({ label }) => label))
|
||||
.sort(),
|
||||
).toEqual(["app", "dep", "nested"]);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps the artifact root when only dependency manifests are present",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-dependency-only-");
|
||||
const dependency = join(root, "node_modules", "dep");
|
||||
await mkdir(dependency, { recursive: true });
|
||||
await writeFile(
|
||||
join(dependency, "package.json"),
|
||||
JSON.stringify({ name: "dep", main: "index.js" }),
|
||||
);
|
||||
await writeFile(join(dependency, "index.js"), "module.exports = {};");
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(response.json).normalized_result;
|
||||
expect(
|
||||
graph.nodes
|
||||
.filter(({ node_id }) => graph.root_node_ids.includes(node_id))
|
||||
.map(({ kind }) => kind),
|
||||
).toEqual(["artifact"]);
|
||||
expect(
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "package")
|
||||
.flatMap(({ observations }) => observations.map(({ label }) => label)),
|
||||
).toEqual(["dep"]);
|
||||
expect(
|
||||
graph.nodes.some(
|
||||
({ kind }) => kind === "electron-main" || kind === "electron-renderer",
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
@@ -1,37 +1,88 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { copyFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, relative, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { writeElectronApiAliasApplication } from "../../fixtures/electronApiAliasApplication.js";
|
||||
|
||||
import {
|
||||
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
|
||||
import { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "../../../src/contracts/javascript/javascriptExportShapeComparisonExample.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import {
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
type JavaScriptApplicationAnalysisResult,
|
||||
} from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { z } from "zod";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const temporary: string[] = [];
|
||||
import { ELECTRON_IDENTITY_LIMITATION } from "../../../src/domain/javascript/javascriptElectronMemberWrites.js";
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
const execute = promisify(execFile);
|
||||
const requireFixture = createRequire(import.meta.url);
|
||||
// Analysis requests are stateless; retain one compiled server and its SDK
|
||||
// validators while every scenario still owns a separate application directory.
|
||||
const mcpTransport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
mcpTransport.stderr?.on("data", () => undefined);
|
||||
const mcpClient = new Client({
|
||||
name: "application-workflow-parity",
|
||||
version: "1",
|
||||
});
|
||||
let mcpConnection: Promise<void> | undefined;
|
||||
const connectedMcpClient = async (): Promise<Client> => {
|
||||
await (mcpConnection ??= mcpClient.connect(mcpTransport));
|
||||
return mcpClient;
|
||||
};
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await mcpClient.close();
|
||||
} finally {
|
||||
await mcpTransport.close();
|
||||
}
|
||||
});
|
||||
const WEBPACK_FACTORY_BODY = `
|
||||
const key = "dynamic";
|
||||
const __webpack_require__ = {
|
||||
d(target, definitions) {
|
||||
for (const name of Object.keys(definitions))
|
||||
Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: definitions[name],
|
||||
});
|
||||
},
|
||||
};
|
||||
exports[key] = 1;
|
||||
exports["dot.key"] = 2;
|
||||
exports[""] = 3;
|
||||
exports.nested = {};
|
||||
exports.nested.child = 6;
|
||||
exports["nested.child"] = 7;
|
||||
module.exports["module.dot"] = 5;
|
||||
module["exports.decoy"] = 99;
|
||||
Object.defineProperty(exports, "", {
|
||||
value: 4,
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
});
|
||||
__webpack_require__.d(exports, { "from.helper": () => 7 });
|
||||
exports = function ignored() { return 8; };
|
||||
`;
|
||||
|
||||
const writeSelfImportFixture = async (root: string): Promise<void> => {
|
||||
await Promise.all([
|
||||
@@ -130,51 +181,442 @@ const expectSelfImportEvidence = (
|
||||
const analyzeThroughStdioMcp = async (
|
||||
inputPath: string,
|
||||
): Promise<JavaScriptApplicationAnalysisResult> => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
stderr: "pipe",
|
||||
const client = await connectedMcpClient();
|
||||
const response = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: inputPath },
|
||||
});
|
||||
const client = new Client({
|
||||
name: "javascript-self-import-parity",
|
||||
version: "1",
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(response.content).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ type: "text" })]),
|
||||
);
|
||||
const result = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(response.structuredContent).normalized_result;
|
||||
expect(result).toMatchObject({
|
||||
input_path: inputPath,
|
||||
format: "directory",
|
||||
});
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const response = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: inputPath },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(response.content).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ type: "text" })]),
|
||||
);
|
||||
const result = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(response.structuredContent).normalized_result;
|
||||
expect(result).toMatchObject({
|
||||
input_path: inputPath,
|
||||
format: "directory",
|
||||
});
|
||||
return result;
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const expectCliAnalysisParity = async (
|
||||
root: string,
|
||||
mcp: JavaScriptApplicationAnalysisResult,
|
||||
): Promise<void> => {
|
||||
const cli = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
).normalized_result;
|
||||
expect(cli).toEqual(mcp);
|
||||
};
|
||||
|
||||
describe("Electron alias identity through stdio MCP", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "CommonJS binding chains",
|
||||
cliParity: true,
|
||||
esm: false,
|
||||
main: 'const { BrowserWindow, ipcMain } = require("electron"); const First = BrowserWindow; const Win = First; const ipc = ipcMain;',
|
||||
preload:
|
||||
'const { contextBridge, ipcRenderer } = require("electron"); const First = contextBridge; const bridge = First; const ipc = ipcRenderer;',
|
||||
},
|
||||
{
|
||||
name: "static namespace members",
|
||||
esm: false,
|
||||
main: 'const electron = require("electron"); const copied = electron; copied.unrelated = {}; const Win = copied["BrowserWindow"]; const ipc = copied.ipcMain;',
|
||||
preload:
|
||||
'const electron = require("electron"); const copied = electron; const bridge = copied.contextBridge; const ipc = copied["ipcRenderer"];',
|
||||
},
|
||||
{
|
||||
name: "namespace destructuring",
|
||||
esm: false,
|
||||
main: 'const electron = require("electron"); const { BrowserWindow: Win, ipcMain: ipc } = electron;',
|
||||
preload:
|
||||
'const electron = require("electron"); const { contextBridge: bridge, ipcRenderer: ipc } = electron;',
|
||||
},
|
||||
{
|
||||
name: "unwritten let and var bindings",
|
||||
esm: false,
|
||||
main: 'const { BrowserWindow, ipcMain } = require("electron"); let Win = BrowserWindow; var ipc = ipcMain;',
|
||||
preload:
|
||||
'const { contextBridge, ipcRenderer } = require("electron"); var bridge = contextBridge; let ipc = ipcRenderer;',
|
||||
},
|
||||
{
|
||||
name: "ESM binding aliases",
|
||||
cliParity: true,
|
||||
esm: true,
|
||||
main: 'import { BrowserWindow, ipcMain } from "electron"; const Win = BrowserWindow; const ipc = ipcMain;',
|
||||
preload:
|
||||
'import { contextBridge, ipcRenderer } from "electron"; const bridge = contextBridge; const ipc = ipcRenderer;',
|
||||
},
|
||||
])(
|
||||
"recovers Electron boundaries through $name (#1656)",
|
||||
async ({ cliParity, main, preload, esm }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-alias-cli-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "alias-repro",
|
||||
version: "1.0.0",
|
||||
main: "main.js",
|
||||
type: esm ? "module" : "commonjs",
|
||||
}),
|
||||
),
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
`${main}\n${esm ? 'import { fileURLToPath } from "node:url";' : 'const path = require("node:path");'}\nnew Win({ webPreferences: { preload: ${esm ? 'fileURLToPath(new URL("./preload.js", import.meta.url))' : 'path.join(__dirname, "preload.js")'} } });\nipc.handle("ch:ping", async () => "pong");\nfunction shadow(Win, ipc) { new Win(); ipc.handle("ch:decoy", () => null); }\n`,
|
||||
),
|
||||
writeFile(
|
||||
join(root, "preload.js"),
|
||||
`${preload}\nbridge.exposeInMainWorld("api", { ping: () => ipc.invoke("ch:ping") });\nfunction shadow(bridge, ipc) { bridge.exposeInMainWorld("decoy", {}); ipc.invoke("ch:decoy"); }\n`,
|
||||
),
|
||||
]);
|
||||
const result = await analyzeThroughStdioMcp(root);
|
||||
// Keep CLI parity for both module formats; the other rows vary only AST
|
||||
// semantics already exercised by the same public analysis workflow.
|
||||
if (cliParity) await expectCliAnalysisParity(root, result);
|
||||
expect(result.summary).toMatchObject({
|
||||
browser_windows: 1,
|
||||
explicit_web_preferences: 1,
|
||||
preload_entrypoints: 1,
|
||||
context_bridge_apis: 1,
|
||||
exposed_api_members: 1,
|
||||
ipc: {
|
||||
operations: 2,
|
||||
literal_channels: 1,
|
||||
main_handlers: 1,
|
||||
renderer_transmissions: 1,
|
||||
paired_renderer_transmissions: 1,
|
||||
},
|
||||
});
|
||||
expect(result.limitations).toContain(ELECTRON_IDENTITY_LIMITATION);
|
||||
expect(result.graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "ipc-channel",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
channel: "ch:ping",
|
||||
operation: "handle",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
authority: "ast-static-analysis",
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({
|
||||
kind: "source-range",
|
||||
source: "main.js",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
channel: "ch:ping",
|
||||
operation: "invoke",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
authority: "ast-static-analysis",
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({
|
||||
kind: "source-range",
|
||||
source: "preload.js",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.graph.edges).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ relation: "handles" }),
|
||||
expect.objectContaining({ relation: "invokes" }),
|
||||
expect.objectContaining({ relation: "loads" }),
|
||||
expect.objectContaining({ relation: "exposes" }),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Electron unavailable identity through stdio MCP", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "reassigned aliases",
|
||||
cliParity: true,
|
||||
main: 'const { BrowserWindow, ipcMain } = require("electron"); let Win = BrowserWindow; let ipc = ipcMain; Win = class {}; ipc = { handle() {} };',
|
||||
preload:
|
||||
'const { contextBridge, ipcRenderer } = require("electron"); let bridge = contextBridge; let ipc = ipcRenderer; bridge = { exposeInMainWorld() {} }; ipc = { invoke() {} };',
|
||||
},
|
||||
{
|
||||
name: "conditional initializers",
|
||||
main: 'const { BrowserWindow, ipcMain } = require("electron"); if (enabled) { var Win = BrowserWindow; var ipc = ipcMain; }',
|
||||
preload:
|
||||
'const { contextBridge, ipcRenderer } = require("electron"); if (enabled) { var bridge = contextBridge; var ipc = ipcRenderer; }',
|
||||
},
|
||||
{
|
||||
name: "dynamic property selections",
|
||||
main: 'const electron = require("electron"); const Win = electron[windowKey]; const ipc = electron[ipcKey];',
|
||||
preload:
|
||||
'const electron = require("electron"); const bridge = electron[bridgeKey]; const ipc = electron[ipcKey];',
|
||||
},
|
||||
{
|
||||
name: "overwritten namespace exports",
|
||||
main: 'const electron = require("electron"); const copied = electron; copied.BrowserWindow = class {}; electron.ipcMain = { handle() {} }; const Win = electron.BrowserWindow; const ipc = copied.ipcMain;',
|
||||
preload:
|
||||
'const electron = require("electron"); electron.contextBridge = { exposeInMainWorld() {} }; electron.ipcRenderer = { invoke() {} }; const bridge = electron.contextBridge; const ipc = electron.ipcRenderer;',
|
||||
},
|
||||
{
|
||||
name: "overwritten API methods",
|
||||
main: 'const electron = require("electron"); const ipc = electron.ipcMain; ipc.handle = () => null; const Win = electron[windowKey];',
|
||||
preload:
|
||||
'const electron = require("electron"); const bridge = electron.contextBridge; delete bridge.exposeInMainWorld; const ipc = electron.ipcRenderer; ipc.invoke++;',
|
||||
},
|
||||
{
|
||||
name: "direct require namespace writes",
|
||||
main: 'require("electron").BrowserWindow = class {}; require("electron").ipcMain = {handle() {}}; const {BrowserWindow: Win, ipcMain: ipc} = require("electron");',
|
||||
preload:
|
||||
'require("electron").contextBridge = {}; require("electron").ipcRenderer = {}; const {contextBridge: bridge, ipcRenderer: ipc} = require("electron");',
|
||||
},
|
||||
{
|
||||
name: "unknown namespace write keys",
|
||||
main: 'const electron = require("electron"); electron[unknownKey] = {}; const {BrowserWindow: Win, ipcMain: ipc} = electron;',
|
||||
preload:
|
||||
'const electron = require("electron"); electron[unknownKey] = {}; const {contextBridge: bridge, ipcRenderer: ipc} = electron;',
|
||||
},
|
||||
{
|
||||
name: "destructuring assignment targets",
|
||||
main: 'const electron = require("electron"); ({ BrowserWindow: electron.BrowserWindow, ipcMain: electron.ipcMain } = replacement); const {BrowserWindow: Win, ipcMain: ipc} = electron;',
|
||||
preload:
|
||||
'const electron = require("electron"); [electron.contextBridge, electron.ipcRenderer] = replacements; const {contextBridge: bridge, ipcRenderer: ipc} = electron;',
|
||||
},
|
||||
{
|
||||
name: "loop assignment targets",
|
||||
main: 'const electron = require("electron"); for ({ BrowserWindow: electron.BrowserWindow, ipcMain: electron.ipcMain } of replacements) {} const {BrowserWindow: Win, ipcMain: ipc} = electron;',
|
||||
preload:
|
||||
'const electron = require("electron"); for (electron.contextBridge in replacements) {} for (electron.ipcRenderer of replacements) {} const {contextBridge: bridge, ipcRenderer: ipc} = electron;',
|
||||
},
|
||||
{
|
||||
name: "literal keys containing dots",
|
||||
main: 'const electron = require("electron"); const Win = electron["fake.BrowserWindow"]; const ipc = electron["fake.ipcMain"]; electron["ipcMain.handle"]("ch:literal", () => null);',
|
||||
preload:
|
||||
'const electron = require("electron"); const bridge = electron["fake.contextBridge"]; const ipc = electron["fake.ipcRenderer"];',
|
||||
},
|
||||
])(
|
||||
"keeps Electron identity unresolved for $name (#1656)",
|
||||
async ({ cliParity, main, preload }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-alias-unknown-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "alias-unknown",
|
||||
version: "1.0.0",
|
||||
main: "main.js",
|
||||
}),
|
||||
),
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
`${main}\nnew Win(); ipc.handle("ch:ping", () => "pong");\n`,
|
||||
),
|
||||
writeFile(
|
||||
join(root, "preload.js"),
|
||||
`${preload}\nbridge.exposeInMainWorld("api", { ping: () => ipc.invoke("ch:ping") });\n`,
|
||||
),
|
||||
]);
|
||||
const result = await analyzeThroughStdioMcp(root);
|
||||
if (cliParity) await expectCliAnalysisParity(root, result);
|
||||
expect(result.summary).toMatchObject({
|
||||
browser_windows: 0,
|
||||
context_bridge_apis: 0,
|
||||
ipc: { operations: 0 },
|
||||
});
|
||||
expect(
|
||||
result.graph.nodes.some(({ kind }) => kind === "ipc-channel"),
|
||||
).toBe(false);
|
||||
expect(result.limitations).toContain(ELECTRON_IDENTITY_LIMITATION);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves complete line-comment source-map URLs through CLI and MCP", async () => {
|
||||
const root = await createTestTempDirectory("rea-source-map-url-cli-");
|
||||
const directives = [
|
||||
"//# sourceMappingURL=app.js.map?variant=a*modern",
|
||||
"//@ sourceMappingURL=app.js.map?variant=a*legacy",
|
||||
"//# sourceMappingURL=app.js.map#first*section",
|
||||
];
|
||||
await writeFile(
|
||||
join(root, "app.js"),
|
||||
["export const value = 1;", ...directives, ""].join("\n"),
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "app.js.map"),
|
||||
JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }),
|
||||
);
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
).normalized_result;
|
||||
const map = graph.nodes.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "source-map" &&
|
||||
observations.some(({ properties }) => properties.path === "app.js.map"),
|
||||
);
|
||||
const references = map?.observations.filter(
|
||||
({ label }) => label === "source map reference",
|
||||
);
|
||||
expect(references).toHaveLength(directives.length);
|
||||
for (const [index, directive] of directives.entries()) {
|
||||
const declaredUrl = directive.slice(directive.indexOf("=") + 1);
|
||||
const digest = createHash("sha256").update(declaredUrl).digest("hex");
|
||||
expect(references).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: {
|
||||
declared_url: declaredUrl,
|
||||
declared_url_sha256: digest,
|
||||
resolved_path: "app.js.map",
|
||||
available: true,
|
||||
},
|
||||
evidence: expect.objectContaining({
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "app.js",
|
||||
start: { line: index + 2, column: 0 },
|
||||
end: { line: index + 2, column: directive.length },
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "maps_to",
|
||||
target_node_id: map?.node_id,
|
||||
properties: {
|
||||
declared_url_sha256: digest,
|
||||
resolved_path: "app.js.map",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect((await analyzeThroughStdioMcp(root)).graph).toEqual(graph);
|
||||
}, 20_000);
|
||||
|
||||
it("resolves source-map URL paths once without changing their declarations", async () => {
|
||||
const root = await createTestTempDirectory("rea-source-map-encoding-cli-");
|
||||
const cases = [
|
||||
["space%20part.js.map", "space part.js.map"],
|
||||
["literal%25.js.map", "literal%.js.map"],
|
||||
["encoded%2520.js.map", "encoded%20.js.map"],
|
||||
["space%20part.js.map?v=1#section", "space part.js.map"],
|
||||
["caf%C3%A9.js.map", "café.js.map"],
|
||||
["literal%ZZ.js.map", "literal%ZZ.js.map"],
|
||||
] as const;
|
||||
for (const path of new Set(cases.map(([, path]) => path))) {
|
||||
await writeFile(
|
||||
join(root, path),
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
file: path,
|
||||
sources: [],
|
||||
names: [],
|
||||
mappings: "",
|
||||
}),
|
||||
);
|
||||
}
|
||||
await writeFile(
|
||||
join(root, "app.js"),
|
||||
cases.map(([url]) => `//# sourceMappingURL=${url}\n`).join("") +
|
||||
'new Worker("./worker%20file.js");\n' +
|
||||
'navigator.serviceWorker.register("./service%20worker.js");\n',
|
||||
);
|
||||
await writeFile(join(root, "worker file.js"), "export const worker = 1;\n");
|
||||
await writeFile(
|
||||
join(root, "service worker.js"),
|
||||
"export const service = 2;\n",
|
||||
);
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
).normalized_result;
|
||||
for (const [index, [declaredUrl, path]] of cases.entries()) {
|
||||
const map = graph.nodes.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "source-map" &&
|
||||
observations.some(({ properties }) => properties.path === path),
|
||||
);
|
||||
const digest = createHash("sha256").update(declaredUrl).digest("hex");
|
||||
expect(map?.observations).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: {
|
||||
declared_url: declaredUrl,
|
||||
declared_url_sha256: digest,
|
||||
resolved_path: path,
|
||||
available: true,
|
||||
},
|
||||
evidence: expect.objectContaining({
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "app.js",
|
||||
start: { line: index + 1, column: 0 },
|
||||
end: {
|
||||
line: index + 1,
|
||||
column: "//# sourceMappingURL=".length + declaredUrl.length,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "maps_to",
|
||||
target_node_id: map?.node_id,
|
||||
properties: { declared_url_sha256: digest, resolved_path: path },
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const [kind, specifier, path] of [
|
||||
["worker", "./worker%20file.js", "worker file.js"],
|
||||
["service-worker", "./service%20worker.js", "service worker.js"],
|
||||
]) {
|
||||
const worker = graph.nodes.find((node) => node.kind === kind);
|
||||
expect(worker?.observations).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
declared_specifier: specifier,
|
||||
resolved_path: path,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: worker?.node_id,
|
||||
relation: "maps_to",
|
||||
properties: { resolved_path: path },
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect((await analyzeThroughStdioMcp(root)).graph).toEqual(graph);
|
||||
}, 20_000);
|
||||
|
||||
describe("JavaScript application path CLI", () => {
|
||||
it("accepts a relative local application path and preserves canonical Evidence identity", async () => {
|
||||
const root = await createTestTempDirectory("rea-relative-application-cli-");
|
||||
temporary.push(root);
|
||||
await writeFile(join(root, "app.js"), "export const value = 1;\n");
|
||||
const absolute = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!absolute.ok) throw absolute.error;
|
||||
@@ -202,7 +644,6 @@ describe("JavaScript application path CLI", () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-self-import-application-cli-",
|
||||
);
|
||||
temporary.push(root);
|
||||
await writeSelfImportFixture(root);
|
||||
|
||||
const analyzed = await runCli([
|
||||
@@ -221,6 +662,58 @@ describe("JavaScript application path CLI", () => {
|
||||
result.normalized_result.semantic_graph,
|
||||
);
|
||||
}, 20_000);
|
||||
|
||||
it("preserves canonical Electron API aliases through CLI and stdio MCP", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-api-alias-");
|
||||
await writeElectronApiAliasApplication(root);
|
||||
|
||||
const cliResult = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
).normalized_result;
|
||||
expect(cliResult.summary).toMatchObject({
|
||||
browser_windows: 1,
|
||||
explicit_web_preferences: 1,
|
||||
preload_entrypoints: 1,
|
||||
context_bridge_apis: 1,
|
||||
exposed_api_members: 1,
|
||||
ipc: {
|
||||
operations: 2,
|
||||
literal_channels: 1,
|
||||
main_handlers: 1,
|
||||
renderer_transmissions: 1,
|
||||
paired_renderer_transmissions: 1,
|
||||
unpaired_literal_renderer_transmissions: 0,
|
||||
},
|
||||
});
|
||||
const graph = parseJavaScriptApplicationGraph(cliResult.graph);
|
||||
const window = graph.nodes.find(({ kind }) => kind === "browser-window");
|
||||
expect(window?.observations[0]?.evidence.location).toMatchObject({
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "main.cjs",
|
||||
start: { line: 6 },
|
||||
},
|
||||
});
|
||||
const bridge = graph.nodes.find(
|
||||
({ kind }) => kind === "context-bridge-api",
|
||||
);
|
||||
expect(bridge?.observations[0]?.evidence.location).toMatchObject({
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "preload.cjs",
|
||||
start: { line: 5 },
|
||||
},
|
||||
});
|
||||
|
||||
const mcpResult = await analyzeThroughStdioMcp(root);
|
||||
expect(mcpResult.summary).toEqual(cliResult.summary);
|
||||
expect(mcpResult.graph).toEqual(cliResult.graph);
|
||||
expect(mcpResult.semantic_graph).toEqual(cliResult.semantic_graph);
|
||||
}, 20_000);
|
||||
});
|
||||
|
||||
describe("application workflow CLI parity", () => {
|
||||
@@ -255,7 +748,6 @@ describe("application workflow CLI parity", () => {
|
||||
});
|
||||
|
||||
const root = await createTestTempDirectory("rea-application-cli-");
|
||||
temporary.push(root);
|
||||
const comparisonPath = join(root, "comparison.json");
|
||||
await writeFile(
|
||||
comparisonPath,
|
||||
@@ -321,7 +813,6 @@ describe("application workflow CLI parity", () => {
|
||||
|
||||
it("traces the same authenticated semantic graph through the CLI", async () => {
|
||||
const root = await createTestTempDirectory("rea-semantic-cli-");
|
||||
temporary.push(root);
|
||||
await writeFile(
|
||||
join(root, "app.js"),
|
||||
"function add(value) { return value + 1; } add(2);",
|
||||
@@ -372,11 +863,9 @@ describe("rest parameter semantic trace CLI", () => {
|
||||
root,
|
||||
"--json",
|
||||
]);
|
||||
const analyzed = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!analyzed.ok) throw analyzed.error;
|
||||
const graph = javascriptApplicationAnalysisResultSchema.parse(
|
||||
analyzed.value.normalized_result,
|
||||
).semantic_graph;
|
||||
const graph = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(application).normalized_result.semantic_graph;
|
||||
for (const index of [1, 2]) {
|
||||
const argument = graph.nodes.find(
|
||||
({ kind, label }) =>
|
||||
@@ -441,6 +930,142 @@ describe("empty property key application CLI", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("Webpack factory CommonJS export keys", () => {
|
||||
it("keeps exact static keys and omits computed names through CLI and MCP", async () => {
|
||||
const root = await createTestTempDirectory("rea-webpack-export-keys-");
|
||||
const bundle = `globalThis.webpackChunkStaticExports.push([["main"], {
|
||||
1: function(module, exports, __webpack_require__) {${WEBPACK_FACTORY_BODY}},
|
||||
2: function(module) { module.exports = function realDefault() {}; },
|
||||
3: function(module, exports) { exports = function ignoredDefault() {}; },
|
||||
4: function(module) {
|
||||
const key = "dynamic";
|
||||
module.exports = { [key]: 1, stable: 2 };
|
||||
},
|
||||
5: function(module) { module.exports = { __proto__: {} }; },
|
||||
6: function(module) {
|
||||
module.exports = { ["__proto__"]: 1, __proto__() {} };
|
||||
}
|
||||
}]);`;
|
||||
await writeFile(join(root, "bundle.js"), bundle);
|
||||
|
||||
// Execute the same factory body as CommonJS, outside the analyzer, to
|
||||
// verify Node's alias behavior and the exact runtime object keys.
|
||||
const oracleRoot = await createTestTempDirectory(
|
||||
"rea-webpack-export-oracle-",
|
||||
);
|
||||
const oraclePath = join(oracleRoot, "oracle.cjs");
|
||||
await writeFile(oraclePath, WEBPACK_FACTORY_BODY);
|
||||
const actual = requireFixture(oraclePath) as Record<string, unknown>;
|
||||
expect(Reflect.ownKeys(actual).sort()).toEqual([
|
||||
"",
|
||||
"dot.key",
|
||||
"dynamic",
|
||||
"from.helper",
|
||||
"module.dot",
|
||||
"nested",
|
||||
"nested.child",
|
||||
]);
|
||||
expect(actual).toMatchObject({
|
||||
"": 4,
|
||||
"dot.key": 2,
|
||||
dynamic: 1,
|
||||
"from.helper": 7,
|
||||
"module.dot": 5,
|
||||
nested: { child: 6 },
|
||||
"nested.child": 7,
|
||||
});
|
||||
const prototypeSetterPath = join(oracleRoot, "prototype-setter.cjs");
|
||||
const ownPrototypeKeyPath = join(oracleRoot, "own-prototype-key.cjs");
|
||||
await Promise.all([
|
||||
writeFile(prototypeSetterPath, "module.exports = { __proto__: {} }"),
|
||||
writeFile(
|
||||
ownPrototypeKeyPath,
|
||||
'module.exports = { ["__proto__"]: 1, __proto__() {} }',
|
||||
),
|
||||
]);
|
||||
expect(
|
||||
Reflect.ownKeys(requireFixture(prototypeSetterPath) as object),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
Reflect.ownKeys(requireFixture(ownPrototypeKeyPath) as object),
|
||||
).toEqual(["__proto__"]);
|
||||
|
||||
const aliasPath = join(oracleRoot, "alias.cjs");
|
||||
const replacementPath = join(oracleRoot, "replacement.cjs");
|
||||
await Promise.all([
|
||||
writeFile(aliasPath, "exports = function ignored() {};"),
|
||||
writeFile(
|
||||
replacementPath,
|
||||
"module.exports = function actual() { return 42; };",
|
||||
),
|
||||
]);
|
||||
expect(requireFixture(aliasPath)).toEqual({});
|
||||
const replacement: unknown = requireFixture(replacementPath);
|
||||
if (typeof replacement !== "function")
|
||||
throw new Error("Expected Node to load the replacement export");
|
||||
expect(replacement()).toBe(42);
|
||||
|
||||
const applicationEvidenceSchema = z.object({
|
||||
evidence_id: z.string(),
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
});
|
||||
const cliEvidence = applicationEvidenceSchema.parse(
|
||||
await runCli([
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--artifact-format",
|
||||
"directory",
|
||||
"--json",
|
||||
]),
|
||||
);
|
||||
const client = await connectedMcpClient();
|
||||
const response = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root, format: "directory" },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const mcpEvidence = applicationEvidenceSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
expect(await client.ping()).toEqual({});
|
||||
expect(mcpEvidence.evidence_id).toBe(cliEvidence.evidence_id);
|
||||
|
||||
const expectBundleExports = (
|
||||
evidence: typeof cliEvidence,
|
||||
moduleKey: string,
|
||||
expected: readonly string[],
|
||||
) => {
|
||||
const module = evidence.normalized_result.graph.nodes.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "javascript-module" &&
|
||||
observations.some(
|
||||
({ properties }) =>
|
||||
properties.runtime === "webpackChunkStaticExports" &&
|
||||
properties.module_key === moduleKey,
|
||||
),
|
||||
);
|
||||
if (module === undefined)
|
||||
throw new Error(`Missing webpack factory ${moduleKey}`);
|
||||
expect(module.observations[0]?.properties.exports).toEqual(expected);
|
||||
};
|
||||
for (const evidence of [cliEvidence, mcpEvidence]) {
|
||||
expectBundleExports(evidence, "1", [
|
||||
"",
|
||||
"dot.key",
|
||||
"from.helper",
|
||||
"module.dot",
|
||||
"nested",
|
||||
"nested.child",
|
||||
]);
|
||||
expectBundleExports(evidence, "2", ["default"]);
|
||||
expectBundleExports(evidence, "3", []);
|
||||
expectBundleExports(evidence, "4", ["stable"]);
|
||||
expectBundleExports(evidence, "5", []);
|
||||
expectBundleExports(evidence, "6", ["__proto__"]);
|
||||
}
|
||||
}, 20_000);
|
||||
});
|
||||
|
||||
describe("application workflow CLI input", () => {
|
||||
it("rejects Evidence ID-only workflow inputs", async () => {
|
||||
const result = await runCli([
|
||||
@@ -460,7 +1085,6 @@ describe("application workflow CLI input", () => {
|
||||
describe("application workflow CLI copy boundaries", () => {
|
||||
it("compares source values excluded from escaped rest and spread copies", async () => {
|
||||
const root = await createTestTempDirectory("rea-copy-boundary-cli-");
|
||||
temporary.push(root);
|
||||
const sources = [
|
||||
`export default function make() {
|
||||
function mutate(value) { value.changed = true; }
|
||||
@@ -492,7 +1116,7 @@ describe("application workflow CLI copy boundaries", () => {
|
||||
};
|
||||
}`,
|
||||
];
|
||||
const [left, right] = await analyzeCliSources(root, sources);
|
||||
const [left, right] = await analyzeComparisonSources(root, sources);
|
||||
const inputPath = join(root, "comparison.json");
|
||||
await writeFile(
|
||||
inputPath,
|
||||
@@ -533,7 +1157,6 @@ describe("application workflow CLI copy boundaries", () => {
|
||||
describe("application workflow CLI and MCP capture lifetimes", () => {
|
||||
it("compares captured primitives and source values after aliases are replaced", async () => {
|
||||
const root = await createTestTempDirectory("rea-capture-lifetime-cli-");
|
||||
temporary.push(root);
|
||||
const fields = [
|
||||
"rebound",
|
||||
"rest",
|
||||
@@ -585,7 +1208,12 @@ describe("application workflow CLI and MCP capture lifetimes", () => {
|
||||
...Object.fromEntries(fields.map((field) => [field, "UPDATED"])),
|
||||
})}; }`,
|
||||
];
|
||||
const [left, right] = await analyzeCliSources(root, sources);
|
||||
// Retain a complete CLI analysis-to-comparison journey alongside MCP parity.
|
||||
const [left, right] = await Promise.all(
|
||||
(await writeComparisonSources(root, sources)).map((applicationRoot) =>
|
||||
runCli(["analyze-javascript-application", applicationRoot, "--json"]),
|
||||
),
|
||||
);
|
||||
// Execute the authored fixtures independently of static analysis.
|
||||
for (const [index, value] of ["TOKEN", "UPDATED"].entries()) {
|
||||
const { stdout } = await execute(process.execPath, [
|
||||
@@ -635,7 +1263,6 @@ describe("application workflow CLI and MCP capture lifetimes", () => {
|
||||
describe("application workflow CLI export Evidence", () => {
|
||||
it("preserves uncertainty after a helper can mutate an awaited return object", async () => {
|
||||
const root = await createTestTempDirectory("rea-awaited-export-shape-cli-");
|
||||
temporary.push(root);
|
||||
const sources = [
|
||||
`export default async function make() {
|
||||
const result = { kind: "record" };
|
||||
@@ -645,7 +1272,7 @@ describe("application workflow CLI export Evidence", () => {
|
||||
}`,
|
||||
'export default async function make() { return { kind: "record", extra: 1 }; }',
|
||||
];
|
||||
const [left, right] = await analyzeCliSources(root, sources);
|
||||
const [left, right] = await analyzeComparisonSources(root, sources);
|
||||
const compared = await runCli([
|
||||
"compare-javascript-export-shapes",
|
||||
JSON.stringify({
|
||||
@@ -672,7 +1299,6 @@ describe("application workflow CLI export Evidence", () => {
|
||||
|
||||
it("compares exact export shapes from file-backed Evidence", async () => {
|
||||
const root = await createTestTempDirectory("rea-export-shape-cli-");
|
||||
temporary.push(root);
|
||||
const leftRoot = join(root, "left");
|
||||
const rightRoot = join(root, "right");
|
||||
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
|
||||
@@ -736,7 +1362,6 @@ describe("application workflow CLI export property presence", () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-export-shape-presence-cli-",
|
||||
);
|
||||
temporary.push(root);
|
||||
const leftRoot = join(root, "left");
|
||||
const rightRoot = join(root, "right");
|
||||
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
|
||||
@@ -862,51 +1487,49 @@ describe("application workflow CLI validation", () => {
|
||||
const compareThroughStdioMcp = async (
|
||||
input: Record<string, unknown>,
|
||||
): Promise<unknown> => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
const client = await connectedMcpClient();
|
||||
const response = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: input,
|
||||
});
|
||||
const client = new Client({
|
||||
name: "javascript-capture-parity",
|
||||
version: "1",
|
||||
});
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const response = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: input,
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
return response.structuredContent;
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
expect(response.isError).not.toBe(true);
|
||||
return response.structuredContent;
|
||||
};
|
||||
|
||||
const analyzeCliSources = (
|
||||
const writeComparisonSources = (
|
||||
root: string,
|
||||
sources: readonly string[],
|
||||
): Promise<unknown[]> =>
|
||||
): Promise<string[]> =>
|
||||
Promise.all(
|
||||
sources.map(async (source, index) => {
|
||||
const applicationRoot = join(root, String(index));
|
||||
await mkdir(applicationRoot);
|
||||
await writeFile(join(applicationRoot, "parser.mjs"), source);
|
||||
return runCli([
|
||||
"analyze-javascript-application",
|
||||
applicationRoot,
|
||||
"--json",
|
||||
]);
|
||||
return applicationRoot;
|
||||
}),
|
||||
);
|
||||
|
||||
// Produce comparison inputs through the shared stateless stdio workflow;
|
||||
// each consumer still executes the real CLI with its own authored sources.
|
||||
const analyzeComparisonSources = async (
|
||||
root: string,
|
||||
sources: readonly string[],
|
||||
): Promise<unknown[]> => {
|
||||
const client = await connectedMcpClient();
|
||||
return Promise.all(
|
||||
(await writeComparisonSources(root, sources)).map(
|
||||
async (applicationRoot) => {
|
||||
const response = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: applicationRoot },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
return response.structuredContent;
|
||||
},
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: Readonly<Record<string, string>> = {},
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { ROLLDOWN_MODULE_INTEROP } from "../../../src/domain/javascript/javascriptModuleInterop.fixture.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const INTRINSIC_MUTATIONS = [
|
||||
["poisoned.cjs", "({Object} = replacements);"],
|
||||
[
|
||||
"projected.cjs",
|
||||
'const {defineProperty:change} = Object; change(Object,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"decorated.cjs",
|
||||
'@(() => Object) class metadata {}; Object.defineProperty(metadata,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"uncurried.cjs",
|
||||
'const change = Function.prototype.call.bind(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"generic-bind.cjs",
|
||||
'const change = Function.prototype.bind.call(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"replaced-apply.cjs",
|
||||
'Reflect.apply = Object.defineProperty; Reflect.apply(Object,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"bound.cjs",
|
||||
'const change = Object.defineProperty.bind(null,Object,"create"); change({value:customCreate});',
|
||||
],
|
||||
["receiver.cjs", 'Reflect.set({},"create",customCreate,Object);'],
|
||||
[
|
||||
"deep-call.cjs",
|
||||
'Function.prototype.call.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"deep-apply.cjs",
|
||||
'Function.prototype.apply.apply(Object.defineProperty,[null,[Object,"create",{value:customCreate}]]);',
|
||||
],
|
||||
] as const;
|
||||
|
||||
const writePoisonedModules = async (root: string): Promise<void> => {
|
||||
for (const [name, mutation] of INTRINSIC_MUTATIONS)
|
||||
await writeFile(
|
||||
join(root, name),
|
||||
`${mutation}
|
||||
${ROLLDOWN_MODULE_INTEROP}
|
||||
let poisoned = require("electron");
|
||||
poisoned = __toESM(poisoned, 1);
|
||||
new poisoned.BrowserWindow({});
|
||||
throw new Error("must not execute poisoned source");`,
|
||||
);
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains converted Electron windows and preload evidence through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-interop-");
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ main: "main.cjs" }),
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "preload.js"),
|
||||
'throw new Error("must stay inert");',
|
||||
);
|
||||
await writePoisonedModules(root);
|
||||
const source = `const metadata = {};
|
||||
Object.defineProperty(metadata,"x",{value:1});
|
||||
const decorateMetadata = Object.defineProperty.bind(null,metadata,"bound");
|
||||
decorateMetadata({value:1});
|
||||
const decorateViaCall = Function.prototype.call.bind(Object.defineProperty);
|
||||
decorateViaCall(null,metadata,"uncurried",{value:1});
|
||||
const localFunction = () => {};
|
||||
Object.defineProperty(localFunction,"x",{value:1});
|
||||
const localClass = class {};
|
||||
Object.defineProperty(localClass,"x",{value:1});
|
||||
const localRegExp = /local/;
|
||||
Object.defineProperty(localRegExp,"x",{value:1});
|
||||
Object.defineProperty(hoistedFunction,"x",{value:1});
|
||||
function hoistedFunction() {}
|
||||
const captured = Object.defineProperty;
|
||||
Object.defineProperty = custom;
|
||||
${ROLLDOWN_MODULE_INTEROP.replace("__defProp = Object.defineProperty", "__defProp = captured")}
|
||||
let electron = require("electron");
|
||||
electron = __toESM(electron, 1);
|
||||
new electron.BrowserWindow({webPreferences:{preload:"./preload.js"}});
|
||||
new electron.BrowserWindow({webPreferences:{preload:runtimePath}});
|
||||
var direct;
|
||||
var direct = require("electron");
|
||||
var direct;
|
||||
new direct.BrowserWindow({});
|
||||
const fresh = __toESM(require("electron"), 1);
|
||||
new fresh.BrowserWindow({});
|
||||
const {BrowserWindow: ProjectedWindow} = __toESM(require("electron"));
|
||||
new ProjectedWindow({});
|
||||
const nonNode = __toESM(require("electron"), 0);
|
||||
new nonNode.BrowserWindow({});
|
||||
function identity(mod) {return mod;}
|
||||
const passthrough = identity(require("electron"));
|
||||
new passthrough.BrowserWindow({});
|
||||
const __importStar = () => ({BrowserWindow:FakeWindow});
|
||||
const fake = __importStar(require("electron"));
|
||||
new fake.BrowserWindow({});
|
||||
function decoy(electron) {new electron.BrowserWindow({});}
|
||||
require("./poisoned.cjs");
|
||||
require("./projected.cjs");
|
||||
require("./decorated.cjs");
|
||||
require("./bound.cjs");
|
||||
require("./uncurried.cjs");
|
||||
require("./generic-bind.cjs");
|
||||
require("./replaced-apply.cjs");
|
||||
require("./receiver.cjs");
|
||||
require("./deep-call.cjs");
|
||||
require("./deep-apply.cjs");
|
||||
throw new Error("must not execute main");
|
||||
`;
|
||||
await writeFile(join(root, "main.cjs"), source);
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const result = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(document).normalized_result;
|
||||
expect(result.summary).toMatchObject({
|
||||
browser_windows: 7,
|
||||
preload_entrypoints: 1,
|
||||
});
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
expect(result.statistics.parsed_javascript_files).toBe(12);
|
||||
const windows = result.graph.nodes.filter(
|
||||
({ kind }) => kind === "browser-window",
|
||||
);
|
||||
expect(windows).toHaveLength(7);
|
||||
const expectedLines = source
|
||||
.split("\n")
|
||||
.flatMap((line, index) =>
|
||||
/^\s*new (?:(?:electron|direct|fresh|passthrough|nonNode)\.BrowserWindow|ProjectedWindow)\(/u.test(
|
||||
line,
|
||||
)
|
||||
? [index + 1]
|
||||
: [],
|
||||
);
|
||||
const observedLines = windows.flatMap((window) => {
|
||||
const location = window.observations[0]?.evidence.location;
|
||||
return location?.available && location.value.kind === "source-range"
|
||||
? [location.value.start.line]
|
||||
: [];
|
||||
});
|
||||
expect(observedLines.toSorted()).toEqual(expectedLines.toSorted());
|
||||
for (const window of windows) {
|
||||
expect(window.observations[0]?.evidence.location).toMatchObject({
|
||||
available: true,
|
||||
value: { kind: "source-range", source: "main.cjs" },
|
||||
});
|
||||
}
|
||||
expect(
|
||||
windows.flatMap((window) =>
|
||||
window.observations.map(({ properties }) => properties.web_preferences),
|
||||
),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "preload",
|
||||
value: {
|
||||
status: "dynamic",
|
||||
value: null,
|
||||
expression: "runtimePath",
|
||||
},
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -67,7 +67,10 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
`new BrowserWindow({webPreferences:{${preferences}}});`,
|
||||
);
|
||||
await Promise.all([
|
||||
writeFile(join(root, "main.js"), `${sourceLines.join("\n")}\n`),
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
`${sourceLines.join("\n")}\nimport { BrowserWindow } from "electron";\n`,
|
||||
),
|
||||
writeFile(join(root, "first.js"), 'throw new Error("inert preload");\n'),
|
||||
writeFile(join(root, "last.js"), 'throw new Error("inert preload");\n'),
|
||||
]);
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
@@ -13,11 +15,38 @@ import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const requireFixture = createRequire(import.meta.url);
|
||||
const comparisonEnvelope = z.object({
|
||||
normalized_result: javaScriptExportShapeComparisonResultSchema,
|
||||
});
|
||||
const applicationEnvelope = z.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
});
|
||||
// Source semantics use the real stdio workflow throughout the matrix. The
|
||||
// missing-export and count-change cases also check compiled CLI adapter parity.
|
||||
let mcpConnection:
|
||||
| {
|
||||
readonly client: Client;
|
||||
readonly transport: StdioClientTransport;
|
||||
readonly ready: Promise<void>;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
describe("exported function binding resolution through the CLI", () => {
|
||||
afterAll(async () => {
|
||||
if (mcpConnection === undefined) return;
|
||||
try {
|
||||
await mcpConnection.ready;
|
||||
} catch {
|
||||
// Keep the failed connection owned until both resources are closed below.
|
||||
}
|
||||
try {
|
||||
await mcpConnection.client.close();
|
||||
} finally {
|
||||
await mcpConnection.transport.close();
|
||||
}
|
||||
});
|
||||
|
||||
describe("exported function binding resolution through stdio MCP and CLI", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "a function declaration exported by a specifier",
|
||||
@@ -77,7 +106,7 @@ describe("exported function binding resolution through the CLI", () => {
|
||||
async ({ source, exportName }) => {
|
||||
const fixture = await analyzeVersions(source, exportName);
|
||||
await expectRuntimeExports(fixture, (count) => ({ count }));
|
||||
const result = await compareThroughCli(fixture);
|
||||
const result = await compareThroughMcp(fixture.input);
|
||||
expectUncertainComparison(result);
|
||||
for (const evidence of [fixture.input.left, fixture.input.right]) {
|
||||
const { normalized_result: analysis } = z
|
||||
@@ -98,7 +127,7 @@ describe("exported function binding resolution through the CLI", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("does not associate a private function name with a numeric export in CLI or MCP", async () => {
|
||||
it("does not associate a private function name with a numeric export through stdio MCP", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const hidden = function current() { return { count: 0 }; };
|
||||
@@ -107,13 +136,288 @@ describe("exported function binding resolution through the CLI", () => {
|
||||
"default",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => count);
|
||||
const cli = await compareThroughCli(fixture);
|
||||
expectUncertainComparison(cli);
|
||||
expect(await compareThroughMcp(fixture.input)).toEqual(cli);
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectUncertainComparison(comparison);
|
||||
});
|
||||
|
||||
it("does not treat rebinding the CommonJS exports alias as a default export", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`exports = function parse() { return { kind: "result", count: ${String(count)} }; };`,
|
||||
"default",
|
||||
"app.cjs",
|
||||
);
|
||||
|
||||
// This is a test-owned fixture, so Node's actual CommonJS loader is the
|
||||
// oracle for what the application exports.
|
||||
expect(requireFixture(fixture.leftPath)).toEqual({});
|
||||
expect(requireFixture(fixture.rightPath)).toEqual({});
|
||||
|
||||
const mcp = await compareThroughMcp(fixture.input);
|
||||
await expectCliAnalysisParity(fixture);
|
||||
expect(mcp).toMatchObject({
|
||||
left: { status: "missing" },
|
||||
right: { status: "missing" },
|
||||
summary: { added: 0, removed: 0, changed: 0 },
|
||||
});
|
||||
expect(await compareThroughCli(fixture)).toEqual(mcp);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the CommonJS exports alias", "exports"],
|
||||
["an ordinary object property", "holder.value"],
|
||||
])(
|
||||
"resolves exported callable values through = chains ending at %s",
|
||||
async (_, target) => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const holder = {};\nfunction parse() { return { kind: "result", count: ${String(count)} }; }\nmodule.exports = ${target} = parse;`,
|
||||
"default",
|
||||
"app.cjs",
|
||||
);
|
||||
expect(requireFixture(fixture.leftPath)()).toEqual({
|
||||
kind: "result",
|
||||
count: 1,
|
||||
});
|
||||
expect(requireFixture(fixture.rightPath)()).toEqual({
|
||||
kind: "result",
|
||||
count: 2,
|
||||
});
|
||||
for (const evidence of [fixture.input.left, fixture.input.right])
|
||||
expectExportedCallableBinding(evidence, "parse");
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectCountChange(comparison);
|
||||
if (target === "exports") {
|
||||
await expectCliAnalysisParity(fixture);
|
||||
expect(await compareThroughCli(fixture)).toEqual(comparison);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("CommonJS assignment-chain receiver identity through stdio MCP", () => {
|
||||
it("does not export a named write whose captured module.exports receiver is replaced", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const VERSION = ${String(count)};\nmodule.exports.parse = (module.exports = () => ({ count: VERSION }));`,
|
||||
"parse",
|
||||
"app.cjs",
|
||||
);
|
||||
for (const path of [fixture.leftPath, fixture.rightPath]) {
|
||||
const value = requireFixture(path);
|
||||
expect(typeof value).toBe("function");
|
||||
expect(Reflect.ownKeys(value)).toEqual(["length", "name"]);
|
||||
}
|
||||
for (const evidence of [fixture.input.left, fixture.input.right]) {
|
||||
const analysis = z
|
||||
.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
})
|
||||
.parse(evidence).normalized_result;
|
||||
expect(
|
||||
analysis.graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.filter(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.exported_name === "parse",
|
||||
),
|
||||
).toEqual([]);
|
||||
}
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expect(comparison).toMatchObject({
|
||||
left: { status: "missing" },
|
||||
right: { status: "missing" },
|
||||
summary: { added: 0, removed: 0, changed: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a named property export when its receiver remains stable through the RHS chain", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const holder = {};\nfunction parse() { return { kind: "result", count: ${String(count)} }; }\nmodule.exports.parse = holder.value = parse;`,
|
||||
"parse",
|
||||
"app.cjs",
|
||||
);
|
||||
for (const path of [fixture.leftPath, fixture.rightPath])
|
||||
expect(requireFixture(path).parse()).toEqual({
|
||||
kind: "result",
|
||||
count: path === fixture.leftPath ? 1 : 2,
|
||||
});
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectCountChange(comparison);
|
||||
});
|
||||
|
||||
it("keeps receiver identity unresolved when module.exports is reassigned to the same function", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const VERSION = ${String(count)};\nfunction parse() { return { count: VERSION }; }\nmodule.exports = parse;\nmodule.exports.parse = (module.exports = parse);`,
|
||||
"parse",
|
||||
"app.cjs",
|
||||
);
|
||||
for (const path of [fixture.leftPath, fixture.rightPath]) {
|
||||
const value = requireFixture(path);
|
||||
expect(value.parse).toBe(value);
|
||||
expect(value.parse()).toEqual({
|
||||
count: path === fixture.leftPath ? 1 : 2,
|
||||
});
|
||||
}
|
||||
for (const evidence of [fixture.input.left, fixture.input.right])
|
||||
expectUnresolvedExportBinding(evidence, "parse");
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expect(comparison).toMatchObject({
|
||||
left: { status: "unavailable" },
|
||||
right: { status: "unavailable" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps receiver replacement by an existing function unresolved", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const VERSION = ${String(count)};\nfunction parse() { return { count: VERSION }; }\nmodule.exports.parse = (module.exports = parse);`,
|
||||
"parse",
|
||||
"app.cjs",
|
||||
);
|
||||
for (const path of [fixture.leftPath, fixture.rightPath]) {
|
||||
const value = requireFixture(path);
|
||||
expect(typeof value).toBe("function");
|
||||
expect(value.parse).toBeUndefined();
|
||||
expect(value()).toEqual({
|
||||
count: path === fixture.leftPath ? 1 : 2,
|
||||
});
|
||||
}
|
||||
for (const evidence of [fixture.input.left, fixture.input.right])
|
||||
expectUnresolvedExportBinding(evidence, "parse");
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expect(comparison).toMatchObject({
|
||||
left: { status: "unavailable" },
|
||||
right: { status: "unavailable" },
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves a nested lexical parse binding in an ordinary module.exports chain", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`function parse() { return { count: VERSION }; }\nfunction configure() { const parse = () => ({ count: 7 }); let local; module.exports = local = parse; }\nconst VERSION = ${String(count)};\nconfigure();`,
|
||||
"default",
|
||||
"app.cjs",
|
||||
);
|
||||
for (const path of [fixture.leftPath, fixture.rightPath])
|
||||
expect(requireFixture(path)()).toEqual({ count: 7 });
|
||||
for (const evidence of [fixture.input.left, fixture.input.right])
|
||||
expectExportedCallableBinding(evidence, "parse");
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expect(comparison).toMatchObject({
|
||||
summary: { added: 0, removed: 0, changed: 0, unknown: 0 },
|
||||
changes: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("stable exported function bindings through the CLI", () => {
|
||||
describe("CommonJS export identity and scope regressions", () => {
|
||||
it("does not export a named write through the original exports alias after replacement", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const VERSION = ${String(count)};\nexports.parse = (module.exports = () => ({ count: VERSION }));`,
|
||||
"parse",
|
||||
"app.cjs",
|
||||
);
|
||||
for (const path of [fixture.leftPath, fixture.rightPath]) {
|
||||
const value = requireFixture(path);
|
||||
expect(typeof value).toBe("function");
|
||||
expect(Reflect.ownKeys(value)).toEqual(["length", "name"]);
|
||||
}
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expect(comparison).toMatchObject({
|
||||
left: { status: "missing" },
|
||||
right: { status: "missing" },
|
||||
summary: { added: 0, removed: 0, changed: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a dead var shadow of the alias-chain RHS unavailable", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`function parse() { return { count: ${String(count)} }; }\nfunction configure() { if (false) { var parse = () => ({ count: 7 }); } module.exports = exports = parse; }\nconfigure();`,
|
||||
"default",
|
||||
"app.cjs",
|
||||
);
|
||||
expect(requireFixture(fixture.leftPath)).toBeUndefined();
|
||||
expect(requireFixture(fixture.rightPath)).toBeUndefined();
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectUncertainComparison(comparison);
|
||||
});
|
||||
|
||||
it.each(["+=", "||=", "??="] as const)(
|
||||
"does not treat module.exports %s as a definite function export",
|
||||
async (operator) => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`module.exports ${operator} (() => ({ kind: "result", count: ${String(count)} }));`,
|
||||
"default",
|
||||
"app.cjs",
|
||||
);
|
||||
const left = requireFixture(fixture.leftPath);
|
||||
const right = requireFixture(fixture.rightPath);
|
||||
if (operator === "+=") {
|
||||
expect(typeof left).toBe("string");
|
||||
expect(typeof right).toBe("string");
|
||||
} else {
|
||||
expect(left).toEqual({});
|
||||
expect(right).toEqual({});
|
||||
}
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectUncertainComparison(comparison);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a parameter-default mutation unknown in a CommonJS return shape", async () => {
|
||||
const fixture = await analyzeVersions(
|
||||
(count) =>
|
||||
`const source = { value: 0 }; module.exports = exports = function current(arg = null, set = (arg = source)) { var arg; arg.value = ${String(count)}; return { kind: "result", count: source.value }; };`,
|
||||
"default",
|
||||
"app.cjs",
|
||||
);
|
||||
expect(requireFixture(fixture.leftPath)()).toEqual({
|
||||
kind: "result",
|
||||
count: 1,
|
||||
});
|
||||
expect(requireFixture(fixture.rightPath)()).toEqual({
|
||||
kind: "result",
|
||||
count: 2,
|
||||
});
|
||||
for (const evidence of [fixture.input.left, fixture.input.right]) {
|
||||
const analysis = z
|
||||
.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
})
|
||||
.parse(evidence).normalized_result;
|
||||
const shapes = analysis.graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.find(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-return-shapes" &&
|
||||
properties.exported_name === "default",
|
||||
)?.properties.static_return_shapes;
|
||||
expect(shapes).toEqual([
|
||||
expect.objectContaining({
|
||||
fields: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "/count", state: "unknown" }),
|
||||
]),
|
||||
}),
|
||||
]);
|
||||
}
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expect(comparison).toMatchObject({
|
||||
left: { status: "selected" },
|
||||
right: { status: "selected" },
|
||||
summary: { added: 0, removed: 0, changed: 0 },
|
||||
changes: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("stable exported function bindings through stdio MCP", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "an anonymous default",
|
||||
@@ -156,7 +460,7 @@ describe("stable exported function bindings through the CLI", () => {
|
||||
},
|
||||
])("retains exact comparison for $name", async ({ source }) => {
|
||||
const fixture = await analyzeVersions(source, "default");
|
||||
expectCountChange(await compareThroughCli(fixture));
|
||||
expectCountChange(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -177,7 +481,7 @@ describe("export bindings with loop and assignment-only writes", () => {
|
||||
return `${statement} export { current as default };`;
|
||||
}, "default");
|
||||
await expectRuntimeExports(fixture, () => undefined);
|
||||
expectUncertainComparison(await compareThroughCli(fixture));
|
||||
expectUncertainComparison(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it("retains a var initializer in an unconditional nested block", async () => {
|
||||
@@ -188,7 +492,7 @@ describe("export bindings with loop and assignment-only writes", () => {
|
||||
"default",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => ({ kind: "result", count }));
|
||||
expectCountChange(await compareThroughCli(fixture));
|
||||
expectCountChange(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -212,7 +516,7 @@ describe("export bindings with loop and assignment-only writes", () => {
|
||||
"app.cjs",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => ({ count }));
|
||||
expectUncertainComparison(await compareThroughCli(fixture));
|
||||
expectUncertainComparison(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it("does not associate a for-in key with the overwritten function", async () => {
|
||||
@@ -225,7 +529,7 @@ describe("export bindings with loop and assignment-only writes", () => {
|
||||
"app.cjs",
|
||||
);
|
||||
await expectRuntimeExports(fixture, String);
|
||||
expectUncertainComparison(await compareThroughCli(fixture));
|
||||
expectUncertainComparison(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it("preserves an outer export shadowed by a lexical loop declaration", async () => {
|
||||
@@ -236,7 +540,7 @@ describe("export bindings with loop and assignment-only writes", () => {
|
||||
"current",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => ({ kind: "result", count }));
|
||||
expectCountChange(await compareThroughCli(fixture));
|
||||
expectCountChange(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -269,9 +573,8 @@ describe("export bindings with loop and assignment-only writes", () => {
|
||||
])("does not infer $name from its only assignment", async ({ source }) => {
|
||||
const fixture = await analyzeVersions(source, "default", "app.cjs");
|
||||
await expectRuntimeExports(fixture, (count) => count);
|
||||
const cli = await compareThroughCli(fixture);
|
||||
expectUncertainComparison(cli);
|
||||
expect(await compareThroughMcp(fixture.input)).toEqual(cli);
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectUncertainComparison(comparison);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -293,7 +596,7 @@ describe("export binding lexical scope and declaration order", () => {
|
||||
])("keeps $name uncertain", async ({ source }) => {
|
||||
const fixture = await analyzeVersions(source, "current");
|
||||
await expectRuntimeExports(fixture, (count) => ({ count }));
|
||||
expectUncertainComparison(await compareThroughCli(fixture));
|
||||
expectUncertainComparison(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it("does not let a later local declaration contaminate the exported outer binding", async () => {
|
||||
@@ -308,7 +611,7 @@ describe("export binding lexical scope and declaration order", () => {
|
||||
"current",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => ({ kind: "result", count }));
|
||||
expectCountChange(await compareThroughCli(fixture));
|
||||
expectCountChange(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it("does not associate a nested CommonJS numeric export with an outer function", async () => {
|
||||
@@ -321,9 +624,8 @@ describe("export binding lexical scope and declaration order", () => {
|
||||
"app.cjs",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => count);
|
||||
const cli = await compareThroughCli(fixture);
|
||||
expectUncertainComparison(cli);
|
||||
expect(await compareThroughMcp(fixture.input)).toEqual(cli);
|
||||
const comparison = await compareThroughMcp(fixture.input);
|
||||
expectUncertainComparison(comparison);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -347,7 +649,7 @@ describe("export binding lexical scope and declaration order", () => {
|
||||
])("compares $name through its real CommonJS binding", async ({ source }) => {
|
||||
const fixture = await analyzeVersions(source, "default", "app.cjs");
|
||||
await expectRuntimeExports(fixture, (count) => ({ kind: "result", count }));
|
||||
expectCountChange(await compareThroughCli(fixture));
|
||||
expectCountChange(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -452,7 +754,7 @@ describe("export writes in function evaluation contexts", () => {
|
||||
])("keeps an outer export write in $name uncertain", async ({ source }) => {
|
||||
const fixture = await analyzeVersions(source, "current");
|
||||
await expectRuntimeExports(fixture, (count) => ({ count }));
|
||||
expectUncertainComparison(await compareThroughCli(fixture));
|
||||
expectUncertainComparison(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
|
||||
it("resolves a CommonJS export in a parameter default outside the function body", async () => {
|
||||
@@ -465,10 +767,177 @@ describe("export writes in function evaluation contexts", () => {
|
||||
"app.cjs",
|
||||
);
|
||||
await expectRuntimeExports(fixture, (count) => ({ kind: "result", count }));
|
||||
expectCountChange(await compareThroughCli(fixture));
|
||||
expectCountChange(await compareThroughMcp(fixture.input));
|
||||
});
|
||||
});
|
||||
|
||||
it("retains namespace re-export bindings and provenance through stdio MCP and CLI", async () => {
|
||||
const root = await createTestTempDirectory("rea-namespace-reexports-");
|
||||
const declarations = [
|
||||
{ clause: "* as ns", name: "ns", imported: "*" },
|
||||
{
|
||||
clause: '* as "namespace value"',
|
||||
name: "namespace value",
|
||||
imported: "*",
|
||||
},
|
||||
{ clause: "{ value as forwarded }", name: "forwarded", imported: "value" },
|
||||
{ clause: "*", name: "*", imported: "*" },
|
||||
];
|
||||
const source = declarations
|
||||
.map(({ clause }) => `export ${clause} from "./dependency.mjs";`)
|
||||
.join("\n");
|
||||
const path = join(root, "barrel.mjs");
|
||||
await Promise.all([
|
||||
writeFile(path, source),
|
||||
writeFile(join(root, "dependency.mjs"), "export const value = 42;"),
|
||||
]);
|
||||
// Node executes only this test-owned fixture to establish its actual exports.
|
||||
for (const name of ["ns", "namespace value"])
|
||||
expect(await runtimeExport(path, name)).toEqual({ value: 42 });
|
||||
for (const name of ["forwarded", "value"])
|
||||
expect(await runtimeExport(path, name)).toBe(42);
|
||||
|
||||
const documents = [
|
||||
await analyzeThroughMcp(root),
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
];
|
||||
const digest = createHash("sha256").update(source).digest("hex");
|
||||
for (const document of documents) {
|
||||
const { graph } = applicationEnvelope.parse(document).normalized_result;
|
||||
const sourceModule = graph.nodes.find(({ observations }) =>
|
||||
observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "source-module" &&
|
||||
properties.path === "barrel.mjs",
|
||||
),
|
||||
);
|
||||
expect(sourceModule?.observations[0]?.properties).toMatchObject({
|
||||
export_relationships: 4,
|
||||
export_names: ["*", "forwarded", "namespace value", "ns"],
|
||||
omitted_export_names: 0,
|
||||
});
|
||||
for (const [index, { clause, name, imported }] of declarations.entries()) {
|
||||
const exported = graph.nodes.find(({ observations }) =>
|
||||
observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.module_path === "barrel.mjs" &&
|
||||
properties.exported_name === name,
|
||||
),
|
||||
);
|
||||
const observation = exported?.observations[0];
|
||||
expect(observation?.properties).toMatchObject({
|
||||
relationship_kind: "re-export",
|
||||
declared_specifier: "./dependency.mjs",
|
||||
imported_name: imported,
|
||||
local_name: null,
|
||||
});
|
||||
if (imported === "*" && name !== "*")
|
||||
expect(observation?.evidence).toMatchObject({
|
||||
artifact: { available: true, sha256: digest },
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "barrel.mjs",
|
||||
start: { line: index + 1, column: 7 },
|
||||
end: { line: index + 1, column: 7 + clause.length },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: sourceModule?.node_id,
|
||||
target_node_id: exported?.node_id,
|
||||
relation: "exposes",
|
||||
properties: expect.objectContaining({ exported_name: name }),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: observation?.evidence.artifact,
|
||||
location: observation?.evidence.location,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: exported?.node_id,
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "re-export",
|
||||
imported_name: imported,
|
||||
exported_name: name,
|
||||
resolved_path: "dependency.mjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
omitted_count: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("excludes erased namespace type exports through stdio MCP and CLI", async () => {
|
||||
const root = await createTestTempDirectory("rea-namespace-type-exports-");
|
||||
const path = join(root, "barrel.mts");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
path,
|
||||
'export type * as Types from "./types.mjs";\nexport * as Values from "./values.mjs";',
|
||||
),
|
||||
writeFile(
|
||||
join(root, "types.mjs"),
|
||||
'throw new Error("Type-only dependency must not execute");',
|
||||
),
|
||||
writeFile(join(root, "values.mjs"), "export const value = 42;"),
|
||||
]);
|
||||
// Node strips the type-only declaration without loading its throwing target.
|
||||
expect(await runtimeExport(path, "Types")).toBeUndefined();
|
||||
expect(await runtimeExport(path, "Values")).toEqual({ value: 42 });
|
||||
|
||||
const documents = [
|
||||
await analyzeThroughMcp(root),
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
];
|
||||
for (const document of documents) {
|
||||
const { graph } = applicationEnvelope.parse(document).normalized_result;
|
||||
const observations = graph.nodes.flatMap(
|
||||
({ observations }) => observations,
|
||||
);
|
||||
expect(
|
||||
observations.find(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "source-module" &&
|
||||
properties.path === "barrel.mts",
|
||||
)?.properties,
|
||||
).toMatchObject({
|
||||
export_relationships: 1,
|
||||
export_names: ["Values"],
|
||||
omitted_export_names: 0,
|
||||
});
|
||||
expect(
|
||||
observations.filter(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.module_path === "barrel.mts" &&
|
||||
properties.exported_name === "Types",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ properties }) => properties.exported_name === "Types",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
omitted_count: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const expectRuntimeExports = async (
|
||||
fixture: Awaited<ReturnType<typeof analyzeVersions>>,
|
||||
expected: (count: number) => unknown,
|
||||
@@ -481,6 +950,58 @@ const expectRuntimeExports = async (
|
||||
expect(await runtimeExport(path, exportName)).toEqual(expected(count));
|
||||
};
|
||||
|
||||
const expectExportedCallableBinding = (
|
||||
evidence: unknown,
|
||||
localName: string,
|
||||
): void => {
|
||||
const analysis = z
|
||||
.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
})
|
||||
.parse(evidence).normalized_result;
|
||||
const exportBinding = analysis.graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.find(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.exported_name === "default",
|
||||
);
|
||||
expect(exportBinding?.properties.local_name).toBe(localName);
|
||||
expect(analysis.semantic_graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: "function", label: localName }),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
const expectUnresolvedExportBinding = (
|
||||
evidence: unknown,
|
||||
exportName: string,
|
||||
): void => {
|
||||
const analysis = z
|
||||
.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
})
|
||||
.parse(evidence).normalized_result;
|
||||
const observations = analysis.graph.nodes.flatMap(
|
||||
({ observations }) => observations,
|
||||
);
|
||||
expect(
|
||||
observations.filter(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.exported_name === exportName,
|
||||
),
|
||||
).not.toHaveLength(0);
|
||||
expect(
|
||||
observations.filter(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-return-shapes" &&
|
||||
properties.exported_name === exportName,
|
||||
),
|
||||
).toEqual([]);
|
||||
};
|
||||
|
||||
const expectUncertainComparison = (
|
||||
result: Awaited<ReturnType<typeof compareThroughCli>>,
|
||||
): void => {
|
||||
@@ -541,8 +1062,8 @@ const analyzeVersions = async (
|
||||
writeFile(rightPath, source(2)),
|
||||
]);
|
||||
const [left, right] = await Promise.all([
|
||||
runCli(["analyze-javascript-application", leftRoot, "--json"]),
|
||||
runCli(["analyze-javascript-application", rightRoot, "--json"]),
|
||||
analyzeThroughMcp(leftRoot),
|
||||
analyzeThroughMcp(rightRoot),
|
||||
]);
|
||||
return {
|
||||
root,
|
||||
@@ -559,6 +1080,31 @@ const analyzeVersions = async (
|
||||
};
|
||||
};
|
||||
|
||||
const analyzeThroughMcp = async (inputPath: string) => {
|
||||
const client = await getMcpClient();
|
||||
const response = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: inputPath, format: "auto" },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
return response.structuredContent;
|
||||
};
|
||||
|
||||
const expectCliAnalysisParity = async (
|
||||
fixture: Awaited<ReturnType<typeof analyzeVersions>>,
|
||||
): Promise<void> => {
|
||||
for (const [root, evidence] of [
|
||||
[join(fixture.root, "left"), fixture.input.left],
|
||||
[join(fixture.root, "right"), fixture.input.right],
|
||||
] as const) {
|
||||
const cli = applicationEnvelope.parse(
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
);
|
||||
const mcp = applicationEnvelope.parse(evidence);
|
||||
expect(cli.normalized_result).toEqual(mcp.normalized_result);
|
||||
}
|
||||
};
|
||||
|
||||
const compareThroughCli = async (
|
||||
fixture: Awaited<ReturnType<typeof analyzeVersions>>,
|
||||
) => {
|
||||
@@ -570,33 +1116,38 @@ const compareThroughCli = async (
|
||||
};
|
||||
|
||||
const compareThroughMcp = async (input: Record<string, unknown>) => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
const client = await getMcpClient();
|
||||
const response = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: input,
|
||||
});
|
||||
const client = new Client({
|
||||
name: "exported-function-bindings",
|
||||
version: "1",
|
||||
});
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const response = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: input,
|
||||
expect(response.isError).not.toBe(true);
|
||||
await client.ping();
|
||||
return comparisonEnvelope.parse(response.structuredContent).normalized_result;
|
||||
};
|
||||
|
||||
const getMcpClient = async (): Promise<Client> => {
|
||||
if (mcpConnection === undefined) {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
return comparisonEnvelope.parse(response.structuredContent)
|
||||
.normalized_result;
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
transport.stderr?.on("data", () => undefined);
|
||||
const client = new Client({
|
||||
name: "exported-function-bindings",
|
||||
version: "1",
|
||||
});
|
||||
mcpConnection = {
|
||||
client,
|
||||
transport,
|
||||
ready: client.connect(transport),
|
||||
};
|
||||
}
|
||||
await mcpConnection.ready;
|
||||
return mcpConnection.client;
|
||||
};
|
||||
|
||||
const runtimeExport = async (
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"keeps getter receiver mutations uncertain in exported Evidence through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-getter-receivers-");
|
||||
await writeFile(
|
||||
join(root, "app.mjs"),
|
||||
`
|
||||
export function self() {
|
||||
const box = { x: 1, get self() { return this; } };
|
||||
box.self.x = 2;
|
||||
return box.x;
|
||||
}
|
||||
export function property() {
|
||||
const shared = { x: 1 };
|
||||
const box = { s: shared, get v() { return this.s; } };
|
||||
box.v.x = 2;
|
||||
return shared.x;
|
||||
}
|
||||
export function privateField() {
|
||||
const shared = { x: 1 };
|
||||
class B { #s = shared; get v() { return this.#s; } }
|
||||
new B().v.x = 2;
|
||||
return shared.x;
|
||||
}
|
||||
export function superclass() {
|
||||
const shared = { x: 1 };
|
||||
class A { get v() { return shared; } }
|
||||
class B extends A { get v() { return super.v; } }
|
||||
new B().v.x = 2;
|
||||
return shared.x;
|
||||
}
|
||||
export function untouched() {
|
||||
const box = { x: 1, y: 1, get self() { return this; } };
|
||||
box.self.y = 2;
|
||||
return box.x;
|
||||
}
|
||||
`,
|
||||
);
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(document).normalized_result;
|
||||
for (const name of [
|
||||
"self",
|
||||
"property",
|
||||
"privateField",
|
||||
"superclass",
|
||||
"untouched",
|
||||
]) {
|
||||
const projection = graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.find(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-return-shapes" &&
|
||||
properties.exported_name === name,
|
||||
);
|
||||
expect(projection, name).toBeDefined();
|
||||
expect(projection?.properties.static_return_shapes).toMatchObject([
|
||||
{ value_status: name === "untouched" ? "literal" : "unknown" },
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -36,11 +36,30 @@ it("returns a nonzero exit for a streamed JSON analysis failure", async () => {
|
||||
|
||||
// `analyze` routes a JavaScript directory to the same workflow and must keep
|
||||
// its typed cancellation contract.
|
||||
it
|
||||
.skipIf(process.platform === "win32")
|
||||
.each(["analyze-javascript-application", "analyze"])(
|
||||
"returns a typed cancelled CLI result and exit 130 after SIGINT through %s",
|
||||
async (command) => {
|
||||
it.skipIf(process.platform === "win32").each([
|
||||
{
|
||||
command: "analyze-javascript-application",
|
||||
phase: "analyze_javascript_application",
|
||||
parsedFiles: null,
|
||||
},
|
||||
{
|
||||
command: "analyze",
|
||||
phase: "analyze_javascript_application",
|
||||
parsedFiles: null,
|
||||
},
|
||||
{
|
||||
command: "analyze-javascript-application",
|
||||
phase: "build_javascript_application_graph",
|
||||
parsedFiles: 1,
|
||||
},
|
||||
{
|
||||
command: "analyze-javascript-application",
|
||||
phase: "hash_javascript_application_evidence",
|
||||
parsedFiles: 1,
|
||||
},
|
||||
])(
|
||||
"returns typed cancellation and exit 130 after SIGINT through $command during $phase",
|
||||
async ({ command, phase, parsedFiles }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-js-cancellation-");
|
||||
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
|
||||
const child = spawn(
|
||||
@@ -70,7 +89,11 @@ it
|
||||
const line = partial.slice(0, newline);
|
||||
partial = partial.slice(newline + 1);
|
||||
const parsed = progressSchema.safeParse(JSON.parse(line));
|
||||
if (parsed.success && !requested) {
|
||||
if (
|
||||
parsed.success &&
|
||||
parsed.data.rea_progress.phase === phase &&
|
||||
!requested
|
||||
) {
|
||||
requested = true;
|
||||
child.kill("SIGINT");
|
||||
}
|
||||
@@ -89,5 +112,18 @@ it
|
||||
code: "cancelled",
|
||||
details: { reason: "cancelled" },
|
||||
});
|
||||
if (parsedFiles !== null)
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
details: {
|
||||
partial_observation: {
|
||||
normalized_result: {
|
||||
statistics: {
|
||||
parsed_javascript_files: parsedFiles,
|
||||
parse_failures: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, 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 { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.skipIf(process.versions.bun !== undefined).for([
|
||||
{ laterSources: 1, heapMb: 640, methodsCount: 400, retainGraph: true },
|
||||
{ laterSources: 10, heapMb: 640, methodsCount: 400, retainGraph: true },
|
||||
// Even an otherwise empty parent cannot admit this graph after reserving
|
||||
// transient decoding and the next checkpoint, independent of GC timing.
|
||||
{ laterSources: 1, heapMb: 448, methodsCount: 600, retainGraph: false },
|
||||
])(
|
||||
"preserves evidence with $laterSources later checkpoints and a $heapMb MiB parent heap",
|
||||
{ timeout: 90_000 },
|
||||
async ({ laterSources, heapMb, methodsCount, retainGraph }, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-checkpoint-reserve-");
|
||||
const source = Array.from(
|
||||
{ length: methodsCount },
|
||||
(_, index) =>
|
||||
`export function method_${String(index)}(input) { const value = input + ${String(index)}; const pair = { value }; return pair.value; }`,
|
||||
).join("\n");
|
||||
const files: readonly (readonly [string, string])[] = [
|
||||
["a-large.mjs", source],
|
||||
...Array.from(
|
||||
{ length: laterSources },
|
||||
(_, index) =>
|
||||
[
|
||||
`z-tiny-${String(index)}.mjs`,
|
||||
`export const tiny${String(index)} = 1;\n`,
|
||||
] as const,
|
||||
),
|
||||
];
|
||||
for (const [name, text] of files) await writeFile(join(root, name), text);
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze", root, "--format", "json"],
|
||||
environment: {
|
||||
NODE_OPTIONS: `--max-old-space-size=${String(heapMb)} --max-semi-space-size=8`,
|
||||
},
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(response.json).normalized_result,
|
||||
);
|
||||
expect(result.statistics.parsed_javascript_files).toBe(laterSources + 1);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const failures = result.graph.nodes.flatMap(({ observations }) =>
|
||||
observations.flatMap(({ properties }) =>
|
||||
properties.analysis_failure === undefined
|
||||
? []
|
||||
: [properties.analysis_failure],
|
||||
),
|
||||
);
|
||||
const methods = result.semantic_graph.nodes.filter(
|
||||
({ kind, identity }) =>
|
||||
kind === "function" && identity.module_path === "a-large.mjs",
|
||||
);
|
||||
if (retainGraph)
|
||||
expect(methods.map(({ label }) => label).sort()).toEqual(
|
||||
Array.from(
|
||||
{ length: methodsCount },
|
||||
(_, index) => `method_${String(index)}`,
|
||||
).sort(),
|
||||
);
|
||||
else {
|
||||
expect(methods).toHaveLength(0);
|
||||
expect([
|
||||
result.graph.coverage.status,
|
||||
result.semantic_graph.coverage.status,
|
||||
]).toContain("partial");
|
||||
}
|
||||
expect(
|
||||
result.semantic_graph.nodes.some(
|
||||
({ identity, label }) =>
|
||||
identity.module_path === `z-tiny-${String(laterSources - 1)}.mjs` &&
|
||||
label === `tiny${String(laterSources - 1)}`,
|
||||
),
|
||||
).toBe(true);
|
||||
for (const [name, text] of files) {
|
||||
const digest = createHash("sha256").update(text).digest("hex");
|
||||
const node = result.graph.nodes.find(
|
||||
({ kind, identity }) =>
|
||||
kind === "javascript-asset" &&
|
||||
identity.strategy === "content-digest" &&
|
||||
identity.sha256 === digest,
|
||||
);
|
||||
expect(node?.observations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
path: name,
|
||||
parse_status: "complete",
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
if (retainGraph) expect(failures).toEqual([]);
|
||||
expect(await readFile(join(root, name), "utf8")).toBe(text);
|
||||
if (!retainGraph && name === "a-large.mjs") {
|
||||
const failure = z
|
||||
.object({
|
||||
code: z.literal("resource_constraint"),
|
||||
remediation: z.object({ action: z.string() }),
|
||||
details: z.object({
|
||||
reported_limits: z.object({
|
||||
parent_available_result_budget_bytes: z.number(),
|
||||
module_retention_estimate_bytes: z.number(),
|
||||
graph_retention_estimate_bytes: z.number(),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(failures[0]);
|
||||
const limits = failure.details.reported_limits;
|
||||
expect(
|
||||
limits.module_retention_estimate_bytes +
|
||||
limits.graph_retention_estimate_bytes,
|
||||
).toBeGreaterThan(limits.parent_available_result_budget_bytes);
|
||||
expect(failure.remediation.action).toContain("parent result budget");
|
||||
expect(failure.remediation.action).toContain(
|
||||
"retained static and module facts",
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(response.stderr).not.toMatch(/FATAL ERROR:.*heap/iu);
|
||||
},
|
||||
);
|
||||
@@ -42,6 +42,14 @@ const writes = {
|
||||
"const methods = [...[], () => shared]; methods[0]().x = 2;",
|
||||
classMethod:
|
||||
"class Box { get() { return shared; } } const box = new Box(); box.get().x = 2;",
|
||||
objectGetter:
|
||||
"const box = { get value() { return shared; } }; box.value.x = 2;",
|
||||
instanceGetter:
|
||||
"class Box { get value() { return shared; } } const box = new Box(); box.value.x = 2;",
|
||||
staticGetter:
|
||||
"class Box { static get value() { return shared; } } Box.value.x = 2;",
|
||||
copiedGetter:
|
||||
"const box = { get value() { return shared; } }; const alias = box.value; alias.x = 2;",
|
||||
staticMethod:
|
||||
"class Box { static get() { return shared; } } Box.get().x = 2;",
|
||||
constructor:
|
||||
@@ -57,6 +65,24 @@ const source = [
|
||||
([name, body]) =>
|
||||
`export ${name === "asyncAwait" ? "async " : ""}function ${name}(){ const shared = {x: 1}; ${body} return shared.x; }`,
|
||||
),
|
||||
"export function plainGetterRead(){ const shared = {x: 1}; const box = {get value() { return shared; }}; box.value; return shared.x; }",
|
||||
"export function objectGetterLastWins(){ const shared = {x: 1}; const box = {get value(){return shared;}, get value(){return {x: 2};}}; box.value.x = 3; return shared.x; }",
|
||||
"export function objectDataReplacesGetter(){ const shared = {x: 1}; const box = {get value(){return shared;}, value: {x: 2}}; box.value.x = 3; return shared.x; }",
|
||||
"export function objectSpreadReplacesGetter(){ const shared = {x: 1}; const box = {get value(){return shared;}, ...{value: {x: 2}}}; box.value.x = 3; return shared.x; }",
|
||||
"export function dynamicObjectGetter(){ const shared = {x: 1}; const key = 'value'; const box = {get value(){return {x: 2};}, get [key](){return shared;}}; box.value.x = 3; return shared.x; }",
|
||||
"export function dynamicClassGetter(){ const shared = {x: 1}; const key = getKey(); class Box { get value(){return shared;} } const box = new Box(); box[key].x = 2; return shared.x; }",
|
||||
"export function dynamicStaticGetter(){ const shared = {x: 1}; const key = getKey(); class Box { static get value(){return shared;} } Box[key].x = 2; return shared.x; }",
|
||||
"export function inheritedGetter(){ const shared = {x: 1}; class Base { get value(){return shared;} } class Derived extends Base {} new Derived().value.x = 2; return shared.x; }",
|
||||
"export function conditionalSuperGetter(){ const shared = {x: 1}; class Fresh { get value(){return {x: 2};} } class Shared { get value(){return shared;} } class Derived extends (flag ? Fresh : Shared) {} new Derived().value.x = 2; return shared.x; }",
|
||||
"export function computedClassGetterOverride(){ const shared = {x: 1}; const key = getKey(); class Box { get value(){return {x: 2};} get [key](){return shared;} } new Box().value.x = 3; return shared.x; }",
|
||||
"export function aliasedClassGetter(){ const shared = {x: 1}; class Box { get value(){return shared;} } const Alias = Box; new Alias().value.x = 2; return shared.x; }",
|
||||
"export function inlineClassGetter(){ const shared = {x: 1}; new (class { get value(){return shared;} })().value.x = 2; return shared.x; }",
|
||||
"export function instanceGetterAssignment(){ const shared = {x: 1}; class Box { get value(){return shared;} } const box = new Box(); try { box.value = {}; } catch {} return shared.x; }",
|
||||
"export function instanceGetterDeletion(){ const shared = {x: 1}; class Box { get value(){return shared;} } const box = new Box(); delete box.value; return shared.x; }",
|
||||
"export function staticGetterAssignment(){ const shared = {x: 1}; class Box { static get value(){return shared;} } try { Box.value = {}; } catch {} return shared.x; }",
|
||||
"export function staticGetterDeletion(){ const shared = {x: 1}; class Box { static get value(){return shared;} } delete Box.value; return shared.x; }",
|
||||
"export function freshGetterRead(){ const box = {get value(){return {x: 1};}}; const first = box.value; first.x = 2; return box.value.x; }",
|
||||
"export function savedFreshGetter(){ const box = {get value(){return {x: 1};}}; const saved = box.value; saved.x = 2; return saved.x; }",
|
||||
"export function directSibling(){ const shared = {x: 1}; const parent = {shared, keep: 7}; const get = () => parent.shared; get().x = 2; return {x: shared.x, keep: parent.keep}; }",
|
||||
"export function primitive(){ const n = 1; const get = () => n; const t = get(); return n; }",
|
||||
"export function copy(){ const shared = {x: 1}; const get = () => ({...shared}); get().x = 2; return shared.x; }",
|
||||
@@ -75,6 +101,44 @@ const assertReturns = (fields: JavaScriptReturnFields): void => {
|
||||
expect(field?.state, name).toMatch(/^(unknown|literal)$/);
|
||||
if (field?.state === "literal") expect(field.value, name).toBe(2);
|
||||
}
|
||||
for (const name of [
|
||||
"objectGetter",
|
||||
"instanceGetter",
|
||||
"staticGetter",
|
||||
"copiedGetter",
|
||||
])
|
||||
expect(fields(name), name).toContainEqual(
|
||||
expect.objectContaining({ path: "", state: "unknown" }),
|
||||
);
|
||||
for (const name of [
|
||||
"plainGetterRead",
|
||||
"objectGetterLastWins",
|
||||
"objectDataReplacesGetter",
|
||||
])
|
||||
expect(fields(name)).toContainEqual(
|
||||
expect.objectContaining({ path: "", state: "literal", value: 1 }),
|
||||
);
|
||||
for (const name of [
|
||||
"instanceGetterAssignment",
|
||||
"instanceGetterDeletion",
|
||||
"staticGetterAssignment",
|
||||
"staticGetterDeletion",
|
||||
])
|
||||
expect(fields(name), name).toContainEqual(
|
||||
expect.objectContaining({ path: "", state: "literal", value: 1 }),
|
||||
);
|
||||
for (const name of [
|
||||
"inheritedGetter",
|
||||
"aliasedClassGetter",
|
||||
"inlineClassGetter",
|
||||
])
|
||||
expect(fields(name)).toContainEqual(
|
||||
expect.objectContaining({ path: "", state: "unknown" }),
|
||||
);
|
||||
for (const name of ["freshGetterRead", "savedFreshGetter"])
|
||||
expect(fields(name)).toContainEqual(
|
||||
expect.objectContaining({ path: "", state: "unknown" }),
|
||||
);
|
||||
const changed = fields("directSibling").find(({ path }) => path === "/x");
|
||||
expect(changed?.state).toMatch(/^(unknown|literal)$/);
|
||||
if (changed?.state === "literal") expect(changed.value).toBe(2);
|
||||
@@ -115,3 +179,39 @@ cliTest(
|
||||
({ cli }) => verifyJavaScriptReturnShapes(cli, source, assertReturns),
|
||||
120_000,
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"analyzes wide receiver returns without losing escaped reference facts",
|
||||
({ cli }) => {
|
||||
const width = 160_000;
|
||||
const object = Array.from(
|
||||
{ length: width },
|
||||
(_, index) => `p${index}:0`,
|
||||
).join(",");
|
||||
const array = "0,".repeat(width);
|
||||
const wideSource = [
|
||||
["wideObject", `{${object},last:shared}`],
|
||||
["wideArray", `[${array}shared]`],
|
||||
]
|
||||
.map(
|
||||
([name, value]) =>
|
||||
`export function ${name}(){const shared={x:1};const box={wide(){return ${value}},noop(){}};box.noop();return {x:shared.x,keep:7};}`,
|
||||
)
|
||||
.join("\n");
|
||||
return verifyJavaScriptReturnShapes(cli, wideSource, (fields) => {
|
||||
for (const name of ["wideObject", "wideArray"]) {
|
||||
expect(fields(name)).toContainEqual(
|
||||
expect.objectContaining({ path: "/x", state: "unknown" }),
|
||||
);
|
||||
expect(fields(name)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "/keep",
|
||||
state: "literal",
|
||||
value: 7,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
120_000,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { writeJavaScriptSourceSelectionFixture } from "../../fixtures/javascriptSourceSelection.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.for([
|
||||
{ format: "directory", command: "analyze" },
|
||||
{ format: "asar", command: "analyze-javascript-application" },
|
||||
])(
|
||||
"analyzes selected $format sources through $command with complete artifact identity",
|
||||
{ timeout: 60_000 },
|
||||
async ({ format, command }, { cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-js-source-selection-");
|
||||
const files = await writeJavaScriptSourceSelectionFixture(directory);
|
||||
let input = directory;
|
||||
if (format === "asar") {
|
||||
input = join(
|
||||
await createTestTempDirectory("rea-js-selected-asar-"),
|
||||
"app.asar",
|
||||
);
|
||||
await createPackageWithOptions(directory, input, {});
|
||||
}
|
||||
const requested = ["main.mjs", "package.json", "main.mjs"];
|
||||
const response = await cli.run({
|
||||
arguments: [
|
||||
command,
|
||||
input,
|
||||
...requested.flatMap((path) => ["--source-path", path]),
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const evidence = parseEvidence(response.json);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(result.source_selection).toEqual({
|
||||
requested_paths: requested,
|
||||
unselected_files: 4,
|
||||
});
|
||||
expect(evidence.parameters.source_paths).toEqual(requested);
|
||||
expect(result.statistics).toMatchObject({
|
||||
relevant_files: 6,
|
||||
parsed_javascript_files: 1,
|
||||
invalid_utf8_files: 0,
|
||||
parse_failures: 0,
|
||||
text_bytes_read:
|
||||
files.get("main.mjs")!.length + files.get("package.json")!.length,
|
||||
});
|
||||
expect(result.graph.coverage.status).toBe("partial");
|
||||
expect(result.semantic_graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
});
|
||||
expect(
|
||||
result.semantic_graph.nodes.some(
|
||||
({ kind, label }) => kind === "function" && label === "selected",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.semantic_graph.unknowns.some(
|
||||
({ reason, detail }) =>
|
||||
reason === "incomplete-module" &&
|
||||
detail.includes("caller-selected source_paths"),
|
||||
),
|
||||
).toBe(true);
|
||||
for (const [path, bytes] of files) {
|
||||
const properties = result.graph.nodes
|
||||
.flatMap(({ observations }) =>
|
||||
observations.map(({ properties }) => properties),
|
||||
)
|
||||
.find(
|
||||
(properties) =>
|
||||
properties.path === path && properties.text_status !== undefined,
|
||||
);
|
||||
expect(properties?.text_status).toBe(
|
||||
requested.includes(path) ? "included" : "outside-analysis-scope",
|
||||
);
|
||||
expect(properties?.parse_status).toBe(
|
||||
path === "main.mjs" ? "complete" : null,
|
||||
);
|
||||
expect(await readFile(join(directory, path))).toEqual(bytes);
|
||||
}
|
||||
const fullResponse = await cli.run({
|
||||
arguments: [command, input, "--format", "json"],
|
||||
});
|
||||
expect(fullResponse.exitCode).toBe(0);
|
||||
const full = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(fullResponse.json).normalized_result,
|
||||
);
|
||||
expect(full.source_selection).toBeUndefined();
|
||||
expect(full.statistics.invalid_utf8_files).toBe(1);
|
||||
expect(full.statistics.parse_failures).toBeGreaterThan(0);
|
||||
expect([
|
||||
result.root_artifact_sha256,
|
||||
result.inventory_manifest_id,
|
||||
result.inventory_graph_sha256,
|
||||
]).toEqual([
|
||||
full.root_artifact_sha256,
|
||||
full.inventory_manifest_id,
|
||||
full.inventory_graph_sha256,
|
||||
]);
|
||||
if (format === "asar")
|
||||
expect(result.root_artifact_sha256).toBe(
|
||||
createHash("sha256")
|
||||
.update(await readFile(input))
|
||||
.digest("hex"),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects source selection when an explicit provider chooses the native lane",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-js-source-native-refusal-",
|
||||
);
|
||||
await writeJavaScriptSourceSelectionFixture(directory);
|
||||
const response = await cli.run({
|
||||
arguments: [
|
||||
"analyze",
|
||||
directory,
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--source-path",
|
||||
"main.mjs",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
});
|
||||
expect(response.exitCode).toBe(1);
|
||||
expect(response.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: ["source_paths"], reason: "invalid_value" }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,137 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
TextReader,
|
||||
Uint8ArrayReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipWriter,
|
||||
} from "@zip.js/zip.js";
|
||||
import { expect } from "vitest";
|
||||
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const android = {
|
||||
extension: "apk",
|
||||
operation: "project_android_application_graph",
|
||||
command: "project-android-application-graph",
|
||||
scripts: ["classes.dex", "extra.dex"],
|
||||
nativeBytes: Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]),
|
||||
libraries: {
|
||||
"lib/arm64-v8a/libcommunity.so": "jni-library-convention",
|
||||
"lib/arm64-v8a/libpreact.so": "jni-library-convention",
|
||||
"lib/arm64-v8a/libreactivity.so": "jni-library-convention",
|
||||
"lib/arm64-v8a/libhermesfake.so": "jni-library-convention",
|
||||
"lib/arm64-v8a/libflutter.so.backup.so": "jni-library-convention",
|
||||
},
|
||||
positives: {
|
||||
"lib/arm64-v8a/libreactnativejni.so": "react-native-convention",
|
||||
"lib/arm64-v8a/libhermes.so": "react-native-convention",
|
||||
"lib/arm64-v8a/libflutter.so": "flutter-convention",
|
||||
"lib/arm64-v8a/libunity.so": "unity-convention",
|
||||
},
|
||||
};
|
||||
const apple = {
|
||||
extension: "ipa",
|
||||
operation: "project_apple_application_graph",
|
||||
command: "project-apple-application-graph",
|
||||
scripts: ["Payload/Fixture.app/main.js", "Payload/Fixture.app/extra.js"],
|
||||
nativeBytes: Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
|
||||
libraries: {
|
||||
"Payload/Fixture.app/Frameworks/App.framework/App":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/MyApp.framework/MyApp":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/Community.framework/Community":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/Preact.framework/Preact":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/Reactivity.framework/Reactivity":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/HermesExtra.framework/HermesExtra":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/Flutter.framework.backup/Flutter":
|
||||
"javascript-and-native-content",
|
||||
"Payload/Fixture.app/Frameworks/plain.dylib":
|
||||
"javascript-and-native-content",
|
||||
},
|
||||
positives: {
|
||||
"Payload/Fixture.app/Frameworks/React.framework/React":
|
||||
"react-native-convention",
|
||||
"Payload/Fixture.app/Frameworks/hermes.framework/hermes":
|
||||
"react-native-convention",
|
||||
"Payload/Fixture.app/Frameworks/Flutter.framework/Flutter":
|
||||
"flutter-convention",
|
||||
"Payload/Fixture.app/Frameworks/UnityFramework.framework/UnityFramework":
|
||||
"unity-convention",
|
||||
},
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"bounds mobile conventions and preserves inference provenance through compiled CLI and real MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-mobile-conventions-");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const { runProviderAnalysis } = createDirectAnalysis({});
|
||||
for (const fixture of [android, apple]) {
|
||||
for (const positive of [false, true]) {
|
||||
const libraries = positive ? fixture.positives : fixture.libraries;
|
||||
const path = join(
|
||||
root,
|
||||
`${positive ? "positive" : "negative"}.${fixture.extension}`,
|
||||
);
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
for (const script of fixture.scripts)
|
||||
await writer.add(script, new TextReader("export const value = 1;"));
|
||||
for (const name of Object.keys(libraries))
|
||||
await writer.add(name, new Uint8ArrayReader(fixture.nativeBytes));
|
||||
await writeFile(path, await writer.close());
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const input = { inventory_evidence: [inventory] };
|
||||
const result = await cli.run({
|
||||
arguments: [fixture.command, JSON.stringify(input), "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = parseEvidence(result.json);
|
||||
const response = await call(fixture.operation, input);
|
||||
expect(response.isError).not.toBe(true);
|
||||
const mcp = parseEvidence(response.structuredContent);
|
||||
expect(mcp).toEqual(evidence);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
runtime_families: positive
|
||||
? fixture.extension === "apk"
|
||||
? ["dalvik-art", "flutter", "native", "react-native", "unity"]
|
||||
: ["flutter", "javascript", "native", "react-native", "unity"]
|
||||
: fixture.extension === "apk"
|
||||
? ["dalvik-art", "native"]
|
||||
: ["javascript", "native"],
|
||||
coverage: {
|
||||
status: "complete-within-inventory",
|
||||
inventory_complete: true,
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
"A bridge basis is inferred from the native path and is repeated for every managed component.",
|
||||
]),
|
||||
bridge_candidates: expect.arrayContaining(
|
||||
Object.entries(libraries).flatMap(([native_path, basis]) =>
|
||||
fixture.scripts.map((script) =>
|
||||
expect.objectContaining({
|
||||
native_path,
|
||||
basis,
|
||||
...(fixture.extension === "apk"
|
||||
? { managed_path: script }
|
||||
: { source_path: script }),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
@@ -0,0 +1,261 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const literalAliases = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
|
||||
const fallbackAliases = {
|
||||
"#tab-escape": ["./.\t./outside.cjs", "./config.cjs"],
|
||||
"#newline-escape": ["./.%\n2e/outside.cjs", "./config.cjs"],
|
||||
"#normalized-url": "./con\tfig.cjs",
|
||||
"#trimmed-url": "./config.cjs \t",
|
||||
"#url-suffix": "./config.cjs?selected=one#fragment",
|
||||
"#inactive-array": {
|
||||
node: [{ browser: "./browser.cjs" }],
|
||||
default: "./config.cjs",
|
||||
},
|
||||
"#nested-inactive-array": {
|
||||
node: [[{ browser: "./browser.cjs" }]],
|
||||
default: "./config.cjs",
|
||||
},
|
||||
"#parent": ["../outside.cjs", "./config.cjs"],
|
||||
"#absolute": { node: [["/outside.cjs"], "./config.cjs"] },
|
||||
"#url": {
|
||||
import: ["https://example.invalid/outside.cjs", "./config.cjs"],
|
||||
require: ["file:///outside.cjs", "./config.cjs"],
|
||||
},
|
||||
};
|
||||
const resolvedAliases = [...literalAliases, ...Object.keys(fallbackAliases)];
|
||||
const refusedAliases = {
|
||||
"#empty": {
|
||||
target: [],
|
||||
status: "external",
|
||||
limitation: "an empty imports target array",
|
||||
},
|
||||
"#empty-active": {
|
||||
target: { node: [] },
|
||||
status: "external",
|
||||
limitation: "an empty imports target array",
|
||||
},
|
||||
"#null-last": {
|
||||
target: [[], null],
|
||||
status: "external",
|
||||
limitation: "an explicit null imports target",
|
||||
},
|
||||
"#empty-last": {
|
||||
target: [null, []],
|
||||
status: "external",
|
||||
limitation: "an empty imports target array",
|
||||
},
|
||||
"#inactive": {
|
||||
target: [{ browser: "./browser.cjs" }],
|
||||
status: "external",
|
||||
limitation: "it declares browser.",
|
||||
},
|
||||
"#nested-inactive": {
|
||||
status: "external",
|
||||
target: [
|
||||
[{ browser: "./browser.cjs" }, { "rea-inactive": "./inactive.cjs" }],
|
||||
],
|
||||
limitation: "it declares browser, rea-inactive.",
|
||||
},
|
||||
"#escape": {
|
||||
target: "./.\t./outside.cjs",
|
||||
status: "rejected",
|
||||
limitation: "escapes the package root",
|
||||
},
|
||||
"#encoded-separator": {
|
||||
target: ["./con%2ffig.cjs", "./config.cjs"],
|
||||
status: "rejected",
|
||||
limitation: "separator bytes",
|
||||
},
|
||||
"#missing-url": {
|
||||
target: ["./miss\ting.cjs", "./config.cjs"],
|
||||
status: "not-found",
|
||||
limitation: JSON.stringify("./miss\ting.cjs"),
|
||||
},
|
||||
};
|
||||
const allAliases = [...resolvedAliases, ...Object.keys(refusedAliases)];
|
||||
|
||||
const createPackageImportAliasFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-package-import-aliases-");
|
||||
const mainSource = [
|
||||
'const config = require("#config");',
|
||||
'const nested = require("./node_modules/fixture/index.cjs");',
|
||||
'const missing = require("#missing");',
|
||||
...allAliases.map((specifier) => `require(${JSON.stringify(specifier)});`),
|
||||
].join("\n");
|
||||
const moduleSource = allAliases
|
||||
.map((specifier) => `import ${JSON.stringify(specifier)};`)
|
||||
.join("\n");
|
||||
const nestedSource = [
|
||||
'const config = require("#config");',
|
||||
"module.exports = config;",
|
||||
].join("\n");
|
||||
const files = {
|
||||
"package.json": JSON.stringify({
|
||||
name: "app",
|
||||
imports: {
|
||||
"#config": "./config.cjs",
|
||||
...Object.fromEntries(
|
||||
literalAliases.map((specifier) => [specifier, "./config.cjs"]),
|
||||
),
|
||||
...fallbackAliases,
|
||||
...Object.fromEntries(
|
||||
Object.entries(refusedAliases).map(([specifier, { target }]) => [
|
||||
specifier,
|
||||
target,
|
||||
]),
|
||||
),
|
||||
},
|
||||
}),
|
||||
"main.cjs": mainSource,
|
||||
"main.mjs": moduleSource,
|
||||
"config.cjs": "module.exports = 'app-config';",
|
||||
"node_modules/fixture/package.json": JSON.stringify({
|
||||
name: "fixture",
|
||||
imports: { "#config": "./local.cjs" },
|
||||
}),
|
||||
"node_modules/fixture/index.cjs": nestedSource,
|
||||
"node_modules/fixture/local.cjs": "module.exports = 'fixture-config';",
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, content]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, content);
|
||||
}),
|
||||
);
|
||||
return { root, mainSource, moduleSource, nestedSource };
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"resolves exact package import aliases with package scope through %s",
|
||||
async (surface, { cli }) => {
|
||||
const { root, mainSource, moduleSource, nestedSource } =
|
||||
await createPackageImportAliasFixture();
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve("#config")).replaceAll("\\", "/"),
|
||||
).toBe("config.cjs");
|
||||
expect(
|
||||
relative(
|
||||
root,
|
||||
createRequire(join(root, "node_modules/fixture/index.cjs")).resolve(
|
||||
"#config",
|
||||
),
|
||||
).replaceAll("\\", "/"),
|
||||
).toBe("node_modules/fixture/local.cjs");
|
||||
expect(() => nativeRequire.resolve("#missing")).toThrow(
|
||||
expect.objectContaining({ code: "ERR_PACKAGE_IMPORT_NOT_DEFINED" }),
|
||||
);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const specifier of resolvedAliases)
|
||||
for (const [moduleKind, sourcePath, source] of [
|
||||
["require", "main.cjs", mainSource],
|
||||
["import", "main.mjs", moduleSource],
|
||||
] as const)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: moduleKind,
|
||||
specifier,
|
||||
resolved_path: "config.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence(sourcePath, source),
|
||||
}),
|
||||
);
|
||||
const imports = graph.edges.filter(
|
||||
({ properties }) => properties.module_link_kind === "require",
|
||||
);
|
||||
for (const [specifier, { status, limitation }] of Object.entries(
|
||||
refusedAliases,
|
||||
))
|
||||
for (const [moduleKind, sourcePath, source] of [
|
||||
["require", "main.cjs", mainSource],
|
||||
["import", "main.mjs", moduleSource],
|
||||
] as const)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: moduleKind,
|
||||
specifier,
|
||||
resolved_path: null,
|
||||
resolution_status: status,
|
||||
}),
|
||||
evidence: sourceEvidence(sourcePath, source, limitation),
|
||||
}),
|
||||
);
|
||||
expect(imports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
specifier: "#config",
|
||||
resolved_path: "config.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence("main.cjs", mainSource),
|
||||
}),
|
||||
);
|
||||
expect(imports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
specifier: "#config",
|
||||
resolved_path: "node_modules/fixture/local.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence(
|
||||
"node_modules/fixture/index.cjs",
|
||||
nestedSource,
|
||||
),
|
||||
}),
|
||||
);
|
||||
expect(imports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
specifier: "#missing",
|
||||
resolved_path: null,
|
||||
resolution_status: "external",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("does not define package import alias"),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const sourceEvidence = (
|
||||
sourcePath: string,
|
||||
source: string,
|
||||
limitation?: string,
|
||||
): unknown =>
|
||||
expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
available: true,
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({
|
||||
kind: "source-range",
|
||||
source: sourcePath,
|
||||
}),
|
||||
}),
|
||||
...(limitation === undefined
|
||||
? {}
|
||||
: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(limitation),
|
||||
]),
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"reports JSON availability for imported package manifests through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-package-json-imports-");
|
||||
const files = {
|
||||
"main.cjs": [
|
||||
'const version = require("./package.json").version;',
|
||||
'const data = require("./data.json");',
|
||||
'const helper = require("./helper.cjs");',
|
||||
'const broken = require("./broken/package.json");',
|
||||
'const nonObject = require("./non-object/package.json");',
|
||||
'const unavailable = require("./unavailable/package.json");',
|
||||
].join("\n"),
|
||||
"package.json": '{"name":"app","version":"1.0.0"}',
|
||||
"data.json": "[]",
|
||||
"helper.cjs": "module.exports = 1;",
|
||||
"broken/package.json": "{",
|
||||
"non-object/package.json": "[]",
|
||||
"unavailable/package.json": Buffer.from([0xff]),
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, content]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, content);
|
||||
}),
|
||||
);
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
expect(nativeRequire("./package.json").version).toBe("1.0.0");
|
||||
expect(nativeRequire("./non-object/package.json")).toEqual([]);
|
||||
expect(nativeRequire("./data.json")).toEqual([]);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const { graph } = z
|
||||
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
|
||||
.parse(document).normalized_result;
|
||||
const imports = graph.edges.filter(
|
||||
({ properties }) => properties.module_link_kind === "require",
|
||||
);
|
||||
for (const [path, kind, status, metadataStatus] of [
|
||||
["package.json", "package-json", "included", "included"],
|
||||
["data.json", "json", "included", null],
|
||||
["helper.cjs", "javascript", null, null],
|
||||
["broken/package.json", "package-json", "invalid", "invalid"],
|
||||
["non-object/package.json", "package-json", "included", "invalid"],
|
||||
[
|
||||
"unavailable/package.json",
|
||||
"package-json",
|
||||
"unavailable",
|
||||
"unavailable",
|
||||
],
|
||||
]) {
|
||||
expect(imports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
specifier: `./${path}`,
|
||||
resolved_path: path,
|
||||
resolution_status: "resolved",
|
||||
target_file_kind: kind,
|
||||
target_json_status: status,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
if (kind === "package-json")
|
||||
expect(
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "package")
|
||||
.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
path,
|
||||
parse_status: metadataStatus,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,109 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const requests = [
|
||||
{ specifier: "legacy?x", plainName: "legacy", exports: false },
|
||||
{ specifier: "exported#entry", plainName: "exported", exports: true },
|
||||
{ specifier: "@scope/legacy?x", plainName: "@scope/legacy", exports: false },
|
||||
{ specifier: "@scope#entry/pkg", plainName: "@scope/pkg", exports: true },
|
||||
] as const;
|
||||
|
||||
// Windows cannot materialize the question-mark directories in this fixture.
|
||||
cliTest.skipIf(process.platform === "win32").for(["CLI", "stdio MCP"] as const)(
|
||||
"keeps ESM root URL suffixes out of dependency filesystem lookup through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-package-root-suffix-");
|
||||
const sources = {
|
||||
"main.mjs": requests
|
||||
.map(({ specifier }) => `import ${JSON.stringify(specifier)};`)
|
||||
.join("\n"),
|
||||
"main.cjs": requests
|
||||
.map(({ specifier }) => `require(${JSON.stringify(specifier)});`)
|
||||
.join("\n"),
|
||||
};
|
||||
const files: Record<string, string> = { ...sources };
|
||||
for (const item of requests)
|
||||
for (const name of [item.specifier, item.plainName]) {
|
||||
const directory = `node_modules/${name}`;
|
||||
files[`${directory}/package.json`] = JSON.stringify(
|
||||
item.exports ? { exports: "./entry.cjs" } : { main: "./entry.cjs" },
|
||||
);
|
||||
files[`${directory}/entry.cjs`] =
|
||||
`module.exports = ${JSON.stringify(name)};`;
|
||||
}
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, text]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, text);
|
||||
}),
|
||||
);
|
||||
if (surface === "CLI") {
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
`import { createRequire } from "node:module";
|
||||
const require = createRequire(new URL("./main.cjs", import.meta.url));
|
||||
const requests = ${JSON.stringify(requests.map(({ specifier }) => specifier))};
|
||||
const results = await Promise.all(requests.map(async (specifier) => {
|
||||
let esm;
|
||||
try { esm = { value: (await import(specifier)).default, error: null }; }
|
||||
catch (error) { esm = { value: null, error: error.code }; }
|
||||
return { esm, require: require(specifier) };
|
||||
}));
|
||||
console.log(JSON.stringify(results));`,
|
||||
],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
expect(JSON.parse(native.stdout)).toEqual(
|
||||
requests.map(({ specifier }) => ({
|
||||
esm: { value: null, error: "ERR_MODULE_NOT_FOUND" },
|
||||
require: specifier,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const { specifier } of requests)
|
||||
for (const [moduleKind, sourcePath] of [
|
||||
["import", "main.mjs"],
|
||||
["require", "main.cjs"],
|
||||
] as const)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: moduleKind,
|
||||
specifier,
|
||||
resolved_path:
|
||||
moduleKind === "import"
|
||||
? null
|
||||
: `node_modules/${specifier}/entry.cjs`,
|
||||
resolution_status:
|
||||
moduleKind === "import" ? "external" : "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256")
|
||||
.update(sources[sourcePath])
|
||||
.digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,207 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
type SelfNameCase = {
|
||||
readonly directory: string;
|
||||
readonly packageName: string;
|
||||
readonly exportKey: string;
|
||||
readonly specifier: string;
|
||||
readonly selfValue: string;
|
||||
readonly dependency?: {
|
||||
readonly packagePath: string;
|
||||
readonly exportKey: string;
|
||||
readonly value: string;
|
||||
};
|
||||
readonly esmTarget: string;
|
||||
readonly requireTarget: string;
|
||||
readonly esmValue: string;
|
||||
readonly requireValue: string;
|
||||
};
|
||||
|
||||
const cases = [
|
||||
{
|
||||
directory: "scope-prefix",
|
||||
packageName: "@scope",
|
||||
exportKey: "./pkg",
|
||||
specifier: "@scope/pkg",
|
||||
selfValue: "scope self",
|
||||
dependency: {
|
||||
packagePath: "node_modules/@scope/pkg",
|
||||
exportKey: ".",
|
||||
value: "scope dependency",
|
||||
},
|
||||
esmTarget: "scope-prefix/node_modules/@scope/pkg/dependency.cjs",
|
||||
requireTarget: "scope-prefix/self.cjs",
|
||||
esmValue: "scope dependency",
|
||||
requireValue: "scope self",
|
||||
},
|
||||
{
|
||||
directory: "slash-name",
|
||||
packageName: "fixture/sub",
|
||||
exportKey: "./feature",
|
||||
specifier: "fixture/sub/feature",
|
||||
selfValue: "slash self",
|
||||
dependency: {
|
||||
packagePath: "node_modules/fixture",
|
||||
exportKey: "./sub/feature",
|
||||
value: "slash dependency",
|
||||
},
|
||||
esmTarget: "slash-name/node_modules/fixture/dependency.cjs",
|
||||
requireTarget: "slash-name/self.cjs",
|
||||
esmValue: "slash dependency",
|
||||
requireValue: "slash self",
|
||||
},
|
||||
{
|
||||
directory: "slash-exact-name",
|
||||
packageName: "fixture/sub",
|
||||
exportKey: ".",
|
||||
specifier: "fixture/sub",
|
||||
selfValue: "slash exact self",
|
||||
dependency: {
|
||||
packagePath: "node_modules/fixture",
|
||||
exportKey: "./sub",
|
||||
value: "slash exact dependency",
|
||||
},
|
||||
esmTarget: "slash-exact-name/node_modules/fixture/dependency.cjs",
|
||||
requireTarget: "slash-exact-name/self.cjs",
|
||||
esmValue: "slash exact dependency",
|
||||
requireValue: "slash exact self",
|
||||
},
|
||||
{
|
||||
directory: "valid-scoped",
|
||||
packageName: "@scope/pkg",
|
||||
exportKey: "./feature",
|
||||
specifier: "@scope/pkg/feature",
|
||||
selfValue: "valid scoped self",
|
||||
esmTarget: "valid-scoped/self.cjs",
|
||||
requireTarget: "valid-scoped/self.cjs",
|
||||
esmValue: "valid scoped self",
|
||||
requireValue: "valid scoped self",
|
||||
},
|
||||
{
|
||||
directory: "query-self-name",
|
||||
packageName: "self?x",
|
||||
exportKey: ".",
|
||||
specifier: "self?x",
|
||||
selfValue: "query self",
|
||||
esmTarget: "query-self-name/self.cjs",
|
||||
requireTarget: "query-self-name/self.cjs",
|
||||
esmValue: "query self",
|
||||
requireValue: "query self",
|
||||
},
|
||||
{
|
||||
directory: "fragment-self-name",
|
||||
packageName: "@scope/self#entry",
|
||||
exportKey: ".",
|
||||
specifier: "@scope/self#entry",
|
||||
selfValue: "fragment self",
|
||||
esmTarget: "fragment-self-name/self.cjs",
|
||||
requireTarget: "fragment-self-name/self.cjs",
|
||||
esmValue: "fragment self",
|
||||
requireValue: "fragment self",
|
||||
},
|
||||
] satisfies readonly SelfNameCase[];
|
||||
|
||||
const sourceFor = (specifier: string, moduleKind: "import" | "require") =>
|
||||
moduleKind === "import"
|
||||
? `import value from ${JSON.stringify(specifier)};\nexport default value;`
|
||||
: `const value = require(${JSON.stringify(specifier)});\nmodule.exports = value;`;
|
||||
|
||||
const createSelfNameFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-package-self-name-boundary-");
|
||||
const files: Record<string, string> = {};
|
||||
for (const item of cases) {
|
||||
const prefix = item.directory;
|
||||
files[`${prefix}/package.json`] = JSON.stringify({
|
||||
name: item.packageName,
|
||||
exports: { [item.exportKey]: "./self.cjs" },
|
||||
});
|
||||
files[`${prefix}/main.mjs`] = sourceFor(item.specifier, "import");
|
||||
files[`${prefix}/main.cjs`] = sourceFor(item.specifier, "require");
|
||||
files[`${prefix}/self.cjs`] =
|
||||
`module.exports = ${JSON.stringify(item.selfValue)};`;
|
||||
if (item.dependency !== undefined) {
|
||||
const dependencyPrefix = `${prefix}/${item.dependency.packagePath}`;
|
||||
files[`${dependencyPrefix}/package.json`] = JSON.stringify({
|
||||
exports: { [item.dependency.exportKey]: "./dependency.cjs" },
|
||||
});
|
||||
files[`${dependencyPrefix}/dependency.cjs`] =
|
||||
`module.exports = ${JSON.stringify(item.dependency.value)};`;
|
||||
}
|
||||
}
|
||||
files["node-control.mjs"] = `import { createRequire } from "node:module";
|
||||
const cases = ${JSON.stringify(cases.map(({ directory, specifier }) => ({ directory, specifier })))};
|
||||
const esm = await Promise.all(
|
||||
cases.map(async ({ directory }) =>
|
||||
(await import(new URL(directory + "/main.mjs", import.meta.url))).default,
|
||||
),
|
||||
);
|
||||
const require = cases.map(({ directory, specifier }) =>
|
||||
createRequire(new URL(directory + "/main.cjs", import.meta.url))(specifier),
|
||||
);
|
||||
console.log(JSON.stringify({ esm, require }));`;
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, content]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, content);
|
||||
}),
|
||||
);
|
||||
return root;
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"matches self references by parsed ESM name and preserves CommonJS prefix matching through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createSelfNameFixture();
|
||||
if (surface === "CLI") {
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[join(root, "node-control.mjs")],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
expect(JSON.parse(native.stdout)).toEqual({
|
||||
esm: cases.map(({ esmValue }) => esmValue),
|
||||
require: cases.map(({ requireValue }) => requireValue),
|
||||
});
|
||||
}
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const item of cases)
|
||||
for (const [moduleKind, target] of [
|
||||
["import", item.esmTarget],
|
||||
["require", item.requireTarget],
|
||||
] as const) {
|
||||
const sourcePath = `${item.directory}/main.${moduleKind === "import" ? "mjs" : "cjs"}`;
|
||||
const source = sourceFor(item.specifier, moduleKind);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: moduleKind,
|
||||
specifier: item.specifier,
|
||||
resolved_path: target,
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,278 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
type PackageSpecifierCase = {
|
||||
readonly specifier: string;
|
||||
readonly target: string | null;
|
||||
readonly status: "resolved" | "external" | "rejected" | "not-found";
|
||||
readonly value: string | number | null;
|
||||
readonly error: string | null;
|
||||
};
|
||||
|
||||
const requests = [
|
||||
{
|
||||
specifier: "rea-self-fixture",
|
||||
target: "root.cjs",
|
||||
status: "resolved",
|
||||
value: 11,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature",
|
||||
target: "feature.cjs",
|
||||
status: "resolved",
|
||||
value: 22,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature?cache=1",
|
||||
target: "punctuated.cjs",
|
||||
status: "resolved",
|
||||
value: 33,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature?cache=2",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "rea-self-fixture/feature#entry",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "fixture/feature?cache=1",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "fixture/feature#entry",
|
||||
target: null,
|
||||
status: "external",
|
||||
value: null,
|
||||
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
specifier: "fixture/literal?cache=1",
|
||||
target: "node_modules/fixture/literal.cjs",
|
||||
status: "resolved",
|
||||
value: "literal",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/?cache=1",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/#entry",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/nested/?cache=1",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/nested/#entry",
|
||||
target: null,
|
||||
status: "rejected",
|
||||
value: null,
|
||||
error: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature.js",
|
||||
target: "node_modules/legacy/feature.js",
|
||||
status: "resolved",
|
||||
value: "legacy feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature.js?cache=1",
|
||||
target: "node_modules/legacy/feature.js",
|
||||
status: "resolved",
|
||||
value: "legacy feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature.js#entry",
|
||||
target: "node_modules/legacy/feature.js",
|
||||
status: "resolved",
|
||||
value: "legacy feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/with%20space.js?cache=1",
|
||||
target: "node_modules/legacy/with space.js",
|
||||
status: "resolved",
|
||||
value: "legacy spaced feature",
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
specifier: "legacy/feature",
|
||||
target: null,
|
||||
status: "not-found",
|
||||
value: null,
|
||||
error: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
] satisfies readonly PackageSpecifierCase[];
|
||||
|
||||
const createPackageSpecifierFixture = async (): Promise<{
|
||||
readonly root: string;
|
||||
readonly source: string;
|
||||
}> => {
|
||||
const root = await createTestTempDirectory("rea-package-specifier-suffix-");
|
||||
const packagePath = join(root, "node_modules", "fixture");
|
||||
const legacyPackagePath = join(root, "node_modules", "legacy");
|
||||
await Promise.all([
|
||||
mkdir(packagePath, { recursive: true }),
|
||||
mkdir(join(legacyPackagePath, "nested"), { recursive: true }),
|
||||
]);
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-self-fixture",
|
||||
exports: {
|
||||
".": { import: "./root.cjs", require: "./require.cjs" },
|
||||
"./feature": { import: "./feature.cjs", require: "./require.cjs" },
|
||||
"./feature?cache=1": {
|
||||
import: "./punctuated.cjs",
|
||||
require: "./require.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const source = requests
|
||||
.map(
|
||||
({ specifier }, index) =>
|
||||
`import value${index} from ${JSON.stringify(specifier)};`,
|
||||
)
|
||||
.join("\n");
|
||||
await Promise.all([
|
||||
writeFile(join(root, "main.mjs"), source),
|
||||
writeFile(join(root, "root.cjs"), "module.exports = 11;"),
|
||||
writeFile(join(root, "feature.cjs"), "module.exports = 22;"),
|
||||
writeFile(join(root, "punctuated.cjs"), "module.exports = 33;"),
|
||||
writeFile(join(root, "require.cjs"), "module.exports = -1;"),
|
||||
]);
|
||||
await writeFile(
|
||||
join(packagePath, "package.json"),
|
||||
JSON.stringify({
|
||||
exports: {
|
||||
"./feature": "./feature.cjs",
|
||||
"./literal?cache=1": "./literal.cjs",
|
||||
},
|
||||
}),
|
||||
);
|
||||
await Promise.all([
|
||||
writeFile(join(packagePath, "feature.cjs"), 'module.exports = "feature";'),
|
||||
writeFile(join(packagePath, "literal.cjs"), 'module.exports = "literal";'),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "package.json"),
|
||||
JSON.stringify({ name: "legacy", main: "./main.cjs" }),
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "main.cjs"),
|
||||
'module.exports = "legacy root";',
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "feature.js"),
|
||||
'module.exports = "legacy feature";',
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "with space.js"),
|
||||
'module.exports = "legacy spaced feature";',
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "nested", "package.json"),
|
||||
JSON.stringify({ main: "./main.cjs" }),
|
||||
),
|
||||
writeFile(
|
||||
join(legacyPackagePath, "nested", "main.cjs"),
|
||||
'module.exports = "legacy nested";',
|
||||
),
|
||||
]);
|
||||
return { root, source };
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"resolves package self references and suffix keys through %s",
|
||||
async (surface, { cli }) => {
|
||||
const { root, source } = await createPackageSpecifierFixture();
|
||||
if (surface === "CLI") {
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`const requests = ${JSON.stringify(requests.map(({ specifier }) => specifier))};
|
||||
const results = await Promise.all(requests.map(async (specifier) => {
|
||||
try {
|
||||
const result = await import(specifier);
|
||||
return { value: result.default, error: null };
|
||||
} catch (error) {
|
||||
return { value: null, error: error.code };
|
||||
}
|
||||
}));
|
||||
console.log(JSON.stringify(results));`,
|
||||
],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
expect(JSON.parse(native.stdout)).toEqual(
|
||||
requests.map(({ value, error }) => ({ value, error })),
|
||||
);
|
||||
}
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
for (const { specifier, target, status } of requests)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "import",
|
||||
specifier,
|
||||
resolved_path: target,
|
||||
resolution_status: status,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
...(specifier === "legacy/feature"
|
||||
? {
|
||||
limitations: expect.arrayContaining([
|
||||
"The selected package ESM subpath target node_modules/legacy/feature does not exist in the inventoried artifact container; ESM subpath targets are exact files, so no extension or directory index was tried.",
|
||||
]),
|
||||
}
|
||||
: {}),
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: "main.mjs" }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,226 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const createPackageSubpathFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-package-subpaths-");
|
||||
const source = [
|
||||
'const nearest = require("fixture/parser");',
|
||||
'const nested = require("nested/parser");',
|
||||
'const parser = require("exported/parser");',
|
||||
'const directory = require("exported/parser/");',
|
||||
'const hidden = require("exported/hidden");',
|
||||
'const missing = require("exported/missing");',
|
||||
'new BrowserWindow({webPreferences:{preload:"exported/parser"}});',
|
||||
'const file = require("fixture");',
|
||||
'const packageDirectory = require("fixture/");',
|
||||
'const selected = require("@scope/selected");',
|
||||
'const blocked = require("blocked");',
|
||||
'const literal = require("fi%xture");',
|
||||
'const scalar = require("scalar");',
|
||||
'const self = require("../node_modules/fi%xture/run.cjs");',
|
||||
].join("\n");
|
||||
const selfSource = 'const self = require("fi%xture"); module.exports = self;';
|
||||
const importSource = 'import literal from "fi%xture";';
|
||||
const files = {
|
||||
"src/main.cjs": source,
|
||||
"src/imports.mjs": importSource,
|
||||
"src/node_modules/fixture/parser.js": "module.exports = 1;",
|
||||
"src/node_modules/fixture.js": "module.exports = 'file';",
|
||||
"src/node_modules/fixture/index.js": "module.exports = 'directory';",
|
||||
"node_modules/fixture/package.json": "{}",
|
||||
"node_modules/fixture/parser.js": "module.exports = 2;",
|
||||
"node_modules/nested/package.json": "{}",
|
||||
"node_modules/nested/parser/package.json": JSON.stringify({
|
||||
main: "./entry.js",
|
||||
exports: "./decoy.js",
|
||||
}),
|
||||
"node_modules/nested/parser/entry.js": "module.exports = 3;",
|
||||
"node_modules/nested/parser/index.js": "module.exports = 4;",
|
||||
"node_modules/nested/parser/decoy.js": "module.exports = 5;",
|
||||
"node_modules/exported/package.json": JSON.stringify({
|
||||
exports: {
|
||||
"./parser": "./parser.cjs",
|
||||
"./parser/": "./parser.cjs",
|
||||
"./missing": "./missing.cjs",
|
||||
},
|
||||
}),
|
||||
"node_modules/exported/parser.cjs": "module.exports = 6;",
|
||||
"node_modules/exported/hidden.js": "module.exports = 7;",
|
||||
"node_modules/exported/missing/index.js": "module.exports = 8;",
|
||||
"node_modules/@scope/selected.js": "module.exports = 'sibling';",
|
||||
"node_modules/@scope/selected/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs" },
|
||||
}),
|
||||
"node_modules/@scope/selected/actual.cjs": "module.exports = 'export';",
|
||||
"node_modules/blocked.js": "module.exports = 'sibling';",
|
||||
"node_modules/blocked/package.json": JSON.stringify({
|
||||
exports: { ".": null },
|
||||
}),
|
||||
"node_modules/fi%xture.js": "module.exports = 'literal sibling';",
|
||||
"node_modules/fi%xture/package.json": JSON.stringify({
|
||||
name: "fi%xture",
|
||||
exports: "./actual.cjs",
|
||||
main: "./legacy.cjs",
|
||||
}),
|
||||
"node_modules/fi%xture/actual.cjs": "module.exports = 'export';",
|
||||
"node_modules/fi%xture/legacy.cjs": "module.exports = 'legacy';",
|
||||
"node_modules/fi%xture/run.cjs": selfSource,
|
||||
"node_modules/scalar.js": "module.exports = 'scalar sibling';",
|
||||
"node_modules/scalar/package.json": JSON.stringify({ exports: false }),
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, content]) => {
|
||||
const absolute = join(root, path);
|
||||
await mkdir(dirname(absolute), { recursive: true });
|
||||
await writeFile(absolute, content);
|
||||
}),
|
||||
);
|
||||
return { root, source, selfSource, importSource };
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"resolves package subpaths with source provenance through %s",
|
||||
async (surface, { cli }) => {
|
||||
const { root, source, selfSource, importSource } =
|
||||
await createPackageSubpathFixture();
|
||||
const nativeRequire = createRequire(join(root, "src/main.cjs"));
|
||||
const expectedTargets = {
|
||||
"fixture/parser": "src/node_modules/fixture/parser.js",
|
||||
fixture: "src/node_modules/fixture.js",
|
||||
"fixture/": "src/node_modules/fixture/index.js",
|
||||
"nested/parser": "node_modules/nested/parser/entry.js",
|
||||
"exported/parser": "node_modules/exported/parser.cjs",
|
||||
"@scope/selected": "node_modules/@scope/selected/actual.cjs",
|
||||
"fi%xture": "node_modules/fi%xture.js",
|
||||
scalar: "node_modules/scalar.js",
|
||||
"../node_modules/fi%xture/run.cjs": "node_modules/fi%xture/run.cjs",
|
||||
};
|
||||
for (const [specifier, target] of Object.entries(expectedTargets))
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(specifier)).replaceAll("\\", "/"),
|
||||
).toBe(target);
|
||||
for (const specifier of ["exported/parser/", "exported/hidden", "blocked"])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "ERR_PACKAGE_PATH_NOT_EXPORTED" }),
|
||||
);
|
||||
expect(() => nativeRequire.resolve("exported/missing")).toThrow(
|
||||
expect.objectContaining({ code: "MODULE_NOT_FOUND" }),
|
||||
);
|
||||
const selfPath = "node_modules/fi%xture/run.cjs";
|
||||
expect(
|
||||
relative(
|
||||
root,
|
||||
createRequire(join(root, selfPath)).resolve("fi%xture"),
|
||||
).replaceAll("\\", "/"),
|
||||
).toBe("node_modules/fi%xture/actual.cjs");
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const imports = graph.edges.filter(
|
||||
({ properties }) => properties.module_link_kind === "require",
|
||||
);
|
||||
for (const observation of [
|
||||
{ sourcePath: "src/main.cjs", source, targets: expectedTargets },
|
||||
{
|
||||
sourcePath: selfPath,
|
||||
source: selfSource,
|
||||
targets: { "fi%xture": "node_modules/fi%xture/actual.cjs" },
|
||||
},
|
||||
])
|
||||
expectResolvedImports(imports, observation);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "import",
|
||||
specifier: "fi%xture",
|
||||
resolved_path: null,
|
||||
resolution_status: "rejected",
|
||||
}),
|
||||
evidence: sourceEvidence("src/imports.mjs", importSource),
|
||||
}),
|
||||
);
|
||||
for (const [specifier, status] of [
|
||||
["exported/parser/", "external"],
|
||||
["exported/hidden", "external"],
|
||||
["exported/missing", "not-found"],
|
||||
["blocked", "external"],
|
||||
])
|
||||
expect(imports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
specifier,
|
||||
resolved_path: null,
|
||||
resolution_status: status,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const preloads = graph.nodes.filter(
|
||||
({ kind }) => kind === "electron-preload",
|
||||
);
|
||||
expect(preloads).toHaveLength(1);
|
||||
expect(preloads[0]?.identity).toMatchObject({
|
||||
key: "electron-preload:module-specifier:node_modules/exported/parser.cjs",
|
||||
});
|
||||
for (const observation of preloads[0]?.observations ?? [])
|
||||
expect(observation).toMatchObject({
|
||||
properties: {
|
||||
declared_path: "exported/parser",
|
||||
resolution_context: "module-specifier",
|
||||
resolved_path: "node_modules/exported/parser.cjs",
|
||||
},
|
||||
evidence: {
|
||||
location: {
|
||||
available: true,
|
||||
value: { source: "src/main.cjs", start: { line: 7 } },
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const expectResolvedImports = (
|
||||
imports: z.infer<
|
||||
typeof javascriptApplicationAnalysisResultSchema
|
||||
>["graph"]["edges"],
|
||||
observation: {
|
||||
readonly sourcePath: string;
|
||||
readonly source: string;
|
||||
readonly targets: Readonly<Record<string, string>>;
|
||||
},
|
||||
): void => {
|
||||
for (const [specifier, target] of Object.entries(observation.targets))
|
||||
expect.soft(imports).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
specifier,
|
||||
resolved_path: target,
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence(observation.sourcePath, observation.source),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const sourceEvidence = (sourcePath: string, source: string): unknown =>
|
||||
expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
available: true,
|
||||
sha256: createHash("sha256").update(source).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({
|
||||
kind: "source-range",
|
||||
source: sourcePath,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { peResourcesSchema } from "../../../src/domain/native/peResources.js";
|
||||
import { peResourceFixture } from "../../../src/native/pe/PeResources.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const expectPeInputFailureAcrossAdapters = async (input: {
|
||||
readonly cli: TestCli;
|
||||
readonly client: Client;
|
||||
readonly toolName: string;
|
||||
readonly path: string;
|
||||
readonly reason: "invalid_format" | "invalid_value";
|
||||
}) => {
|
||||
const { cli, client, toolName, path, reason } = input;
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-pe-resources", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
operation: "inspect_pe_resources",
|
||||
issues: [{ path: ["path"], reason }],
|
||||
},
|
||||
});
|
||||
const response = await client.callTool({
|
||||
name: toolName,
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response)).toEqual({ error: result.json });
|
||||
};
|
||||
|
||||
const expectPePaddingFailureAcrossAdapters = async (input: {
|
||||
readonly cli: TestCli;
|
||||
readonly client: Client;
|
||||
readonly toolName: string;
|
||||
readonly path: string;
|
||||
}) => {
|
||||
const { cli, client, toolName, path } = input;
|
||||
const fixture = peResourceFixture();
|
||||
const virtualSize = fixture.bytes.readUInt32LE(fixture.sectionAt + 8);
|
||||
fixture.bytes.writeUInt32LE(
|
||||
0x2000 + virtualSize,
|
||||
fixture.dataOffsets[0] ?? 0,
|
||||
);
|
||||
fixture.bytes.writeUInt32LE(4, (fixture.dataOffsets[0] ?? 0) + 4);
|
||||
await writeFile(path, fixture.bytes);
|
||||
const cliResult = await cli.run({
|
||||
arguments: ["inspect-pe-resources", path, "--json"],
|
||||
});
|
||||
expect(cliResult.exitCode).not.toBe(0);
|
||||
const mcpResult = await client.callTool({
|
||||
name: toolName,
|
||||
arguments: { path },
|
||||
});
|
||||
expect(mcpResult.isError).toBe(true);
|
||||
expect(peResourcesSchema.safeParse(mcpResult.structuredContent).success).toBe(
|
||||
false,
|
||||
);
|
||||
};
|
||||
|
||||
const expectPeInputFailuresAcrossAdapters = async (input: {
|
||||
readonly cli: TestCli;
|
||||
readonly client: Client;
|
||||
readonly toolName: string;
|
||||
readonly root: string;
|
||||
}) => {
|
||||
const { cli, client, toolName, root } = input;
|
||||
const malformedPath = join(root, "malformed.exe");
|
||||
await writeFile(malformedPath, Buffer.from("not a PE image"));
|
||||
for (const [path, reason] of [
|
||||
[join(root, "missing.exe"), "invalid_value"],
|
||||
[malformedPath, "invalid_format"],
|
||||
] as const)
|
||||
await expectPeInputFailureAcrossAdapters({
|
||||
cli,
|
||||
client,
|
||||
toolName,
|
||||
path,
|
||||
reason,
|
||||
});
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"inspects PE32/PE32+ resources through compiled CLI and real stdio MCP without an active target",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-pe-resource-acceptance-");
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
const client = new Client({ name: "pe-resource-acceptance", version: "1" });
|
||||
const contract = toolContract("inspect_pe_resources");
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const inventory = await client.listTools();
|
||||
expect(inventory.tools).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: contract.name,
|
||||
annotations: expect.objectContaining({
|
||||
readOnlyHint: false,
|
||||
openWorldHint: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const session = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(JSON.stringify(session.structuredContent)).toContain(
|
||||
"inspect_pe_resources",
|
||||
);
|
||||
for (const plus of [false, true]) {
|
||||
const fixture = peResourceFixture(plus);
|
||||
const path = join(root, plus ? "resource64.exe" : "resource32.exe");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-pe-resources", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const evidence = contract.outputSchema.parse(result.json);
|
||||
const report = peResourcesSchema.parse(evidence.normalized_result);
|
||||
expect(evidence.subject?.digest).toMatchObject({
|
||||
sha256: createHash("sha256").update(fixture.bytes).digest("hex"),
|
||||
});
|
||||
expect(report.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
resources: 5,
|
||||
});
|
||||
expect(report.resources[0]?.payload.sha256).toBe(
|
||||
createHash("sha256").update("ICON").digest("hex"),
|
||||
);
|
||||
expect(
|
||||
report.resources.find(({ name }) => name.kind === "name")?.name,
|
||||
).toMatchObject({ kind: "name", name: "7", utf16le_hex: "3700" });
|
||||
expect(report.icon_groups[0]?.images).toMatchObject([
|
||||
{
|
||||
resource_id: 1,
|
||||
candidate_resource_indices: [0, 1],
|
||||
same_language_resource_index: 0,
|
||||
},
|
||||
{
|
||||
resource_id: 99,
|
||||
candidate_resource_indices: [],
|
||||
same_language_resource_index: null,
|
||||
},
|
||||
]);
|
||||
const response = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const mcp = contract.outputSchema.parse(response.structuredContent);
|
||||
expect(mcp.evidence_id).toBe(evidence.evidence_id);
|
||||
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
const text = response.content.find(({ type }) => type === "text");
|
||||
if (text?.type !== "text") throw new Error("Missing MCP text Evidence");
|
||||
expect(
|
||||
contract.outputSchema.parse(JSON.parse(text.text)).evidence_id,
|
||||
).toBe(evidence.evidence_id);
|
||||
expect(await readFile(path)).toEqual(fixture.bytes);
|
||||
}
|
||||
await expectPePaddingFailureAcrossAdapters({
|
||||
cli,
|
||||
client,
|
||||
toolName: contract.name,
|
||||
path: join(root, "raw-padding.exe"),
|
||||
});
|
||||
await expectPeInputFailuresAcrossAdapters({
|
||||
cli,
|
||||
client,
|
||||
toolName: contract.name,
|
||||
root,
|
||||
});
|
||||
const absent = peResourceFixture();
|
||||
absent.bytes.fill(0, absent.directoryAt, absent.directoryAt + 8);
|
||||
const path = join(root, "absent.exe");
|
||||
await writeFile(path, absent.bytes);
|
||||
const empty = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: { path },
|
||||
});
|
||||
expect(empty.isError).not.toBe(true);
|
||||
expect(
|
||||
contract.outputSchema.parse(empty.structuredContent).normalized_result,
|
||||
).toMatchObject({
|
||||
directory: null,
|
||||
resources: [],
|
||||
coverage: { status: "complete", resources: 0 },
|
||||
});
|
||||
for (const arguments_ of [
|
||||
{ path, max_file_bytes: 64 },
|
||||
{ path: "relative.exe" },
|
||||
{ path, extra: true },
|
||||
]) {
|
||||
const rejected = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(rejected.isError).toBe(true);
|
||||
expect(
|
||||
contract.outputSchema.safeParse(rejected.structuredContent).success,
|
||||
).toBe(false);
|
||||
}
|
||||
const damaged = peResourceFixture();
|
||||
damaged.bytes.writeUInt32LE(17, damaged.directoryAt + 4);
|
||||
const badPath = join(root, "damaged.exe");
|
||||
await writeFile(badPath, damaged.bytes);
|
||||
const rejected = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: { path: badPath },
|
||||
});
|
||||
expect(rejected.isError).toBe(true);
|
||||
expect(
|
||||
contract.outputSchema.safeParse(rejected.structuredContent).success,
|
||||
).toBe(false);
|
||||
await client.ping();
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
@@ -7,7 +7,11 @@ import { z } from "zod";
|
||||
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import {
|
||||
evidenceResultOf,
|
||||
expandToolAvailability,
|
||||
toolAvailabilityInventory,
|
||||
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
|
||||
const mainPath = fileURLToPath(
|
||||
@@ -17,22 +21,28 @@ const fixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/fakeLauncher.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const expectAvailableToolInventory = async (client: Client) => {
|
||||
const listed = await client.listTools();
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
const expectAvailableToolInventory = async (
|
||||
client: Client,
|
||||
listed: Awaited<ReturnType<Client["listTools"]>>,
|
||||
) => {
|
||||
const binarySession = listed.tools.find(
|
||||
({ name }) => name === "binary_session",
|
||||
);
|
||||
if (binarySession === undefined)
|
||||
throw new Error("The compiled catalog omitted binary_session");
|
||||
const status = await client.callTool(
|
||||
{ name: "binary_session", arguments: {} },
|
||||
{ toolDefinition: binarySession },
|
||||
);
|
||||
expect(status.isError).not.toBe(true);
|
||||
const availability = z
|
||||
const inventory = z
|
||||
.object({
|
||||
result: z.object({
|
||||
tool_availability: z.array(
|
||||
z.object({ name: z.string(), available: z.boolean() }),
|
||||
),
|
||||
tool_availability: toolAvailabilityInventory,
|
||||
}),
|
||||
})
|
||||
.parse(status.structuredContent).result.tool_availability;
|
||||
const availability = expandToolAvailability(inventory);
|
||||
// This asserts the compiled entrypoint matches the source catalog. When it
|
||||
// fails, check that `dist/` is current (`npm run build:cached`) before
|
||||
// suspecting a registration bug -- a stale build is by far the likeliest
|
||||
@@ -161,6 +171,9 @@ describe("production stdio runtime", () => {
|
||||
15_000,
|
||||
);
|
||||
|
||||
// Use the suite's bounded acceptance deadline, including its coverage allowance.
|
||||
// This cold-start workflow computes the growing catalog's schema digests; it
|
||||
// verifies catalog and lifecycle behavior, not a 15-second performance target.
|
||||
it("serves the compiled catalog without an initial target or fatal record", async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
@@ -180,7 +193,10 @@ describe("production stdio runtime", () => {
|
||||
try {
|
||||
await client.connect(transport);
|
||||
// Keep catalog parity independent of initial target/provider startup.
|
||||
const status = await expectAvailableToolInventory(client);
|
||||
// Validate each called tool against its advertised definition without
|
||||
// asking the SDK to compile every unrelated output schema in the catalog.
|
||||
const listed = await client.listTools();
|
||||
const status = await expectAvailableToolInventory(client, listed);
|
||||
expect(
|
||||
z
|
||||
.object({ result: z.object({ open: z.boolean() }) })
|
||||
@@ -188,10 +204,15 @@ describe("production stdio runtime", () => {
|
||||
).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: {},
|
||||
});
|
||||
const closeBinary = listed.tools.find(
|
||||
({ name }) => name === "close_binary",
|
||||
);
|
||||
if (closeBinary === undefined)
|
||||
throw new Error("The compiled catalog omitted close_binary");
|
||||
const closed = await client.callTool(
|
||||
{ name: "close_binary", arguments: {} },
|
||||
{ toolDefinition: closeBinary },
|
||||
);
|
||||
expect(closed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
@@ -218,7 +239,7 @@ describe("production stdio runtime", () => {
|
||||
record.level >= 50,
|
||||
);
|
||||
expect(fatal).toEqual([]);
|
||||
}, 15_000);
|
||||
});
|
||||
|
||||
it.runIf(process.platform === "darwin")(
|
||||
"serves a database-kind initial target without a fatal record on macOS",
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
||||
import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"recovers retained prefixed source-map originals and byte identity through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-retained-map-prefix-");
|
||||
const original = "export const answer: number = 42;";
|
||||
const mapText = `\uFEFF)]}'retained response\r\n${JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["original.ts"],
|
||||
sourcesContent: [original],
|
||||
names: [],
|
||||
mappings: "AAAA",
|
||||
})}`;
|
||||
const mapPath = join(root, "bundle.js.map");
|
||||
await writeFile(
|
||||
join(root, "bundle.js"),
|
||||
"export const answer = 42;\n//# sourceMappingURL=bundle.js.map\n",
|
||||
);
|
||||
await writeFile(mapPath, mapText);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const mapDigest = createHash("sha256").update(mapText).digest("hex");
|
||||
const originalDigest = createHash("sha256").update(original).digest("hex");
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "source-module",
|
||||
identity: expect.objectContaining({
|
||||
strategy: "source-map-original",
|
||||
source_map_sha256: mapDigest,
|
||||
original_source: "original.ts",
|
||||
source_sha256: originalDigest,
|
||||
}),
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: expect.objectContaining({
|
||||
source_name: "original.ts",
|
||||
map_path: "bundle.js.map",
|
||||
}),
|
||||
properties: expect.objectContaining({
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source_name_available: true,
|
||||
content_available: true,
|
||||
content_sha256: originalDigest,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({ sha256: mapDigest }),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
expect(await readFile(mapPath, "utf8")).toBe(mapText);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains nullable source-map declarations and aligned content through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nullable-map-");
|
||||
const original = "export const answer: number = 42;";
|
||||
const unnamed = "retained source text without a declared name";
|
||||
const maps = {
|
||||
"absent.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["unembedded.ts"],
|
||||
sourcesContent: null,
|
||||
names: [],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
"mixed.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: [null, "original.ts"],
|
||||
sourcesContent: [unnamed, original],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
"unnamed-empty.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: [null, "original.ts"],
|
||||
sourcesContent: [null, original],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
};
|
||||
await writeFixtureFiles(root, {
|
||||
...maps,
|
||||
"absent.js":
|
||||
"export const absent = 1;\n//# sourceMappingURL=absent.js.map\n",
|
||||
"mixed.js":
|
||||
"export const answer = 42;\n//# sourceMappingURL=mixed.js.map\n",
|
||||
"unnamed-empty.js":
|
||||
"export const answer = 42;\n//# sourceMappingURL=unnamed-empty.js.map\n",
|
||||
});
|
||||
for (const [mapPath, expectedSource] of [
|
||||
["absent.js.map", "unembedded.ts"],
|
||||
["mixed.js.map", "original.ts"],
|
||||
["unnamed-empty.js.map", "original.ts"],
|
||||
] as const)
|
||||
expect(
|
||||
originalPositionFor(new TraceMap(maps[mapPath], `file:///${mapPath}`), {
|
||||
line: 1,
|
||||
column: 0,
|
||||
}).source,
|
||||
).toBe(`file:///${expectedSource}`);
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const digest = (text: string) =>
|
||||
createHash("sha256").update(text).digest("hex");
|
||||
expect(
|
||||
graph.nodes.filter(
|
||||
(node) => node.identity.strategy === "source-map-original",
|
||||
),
|
||||
).toHaveLength(3);
|
||||
for (const [name, mapPath, content, sourceIndex] of [
|
||||
["unembedded.ts", "absent.js.map", null, 0],
|
||||
["original.ts", "mixed.js.map", original, 1],
|
||||
["original.ts", "unnamed-empty.js.map", original, 1],
|
||||
] as const) {
|
||||
const mapDigest = digest(maps[mapPath]);
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "source-module",
|
||||
identity: expect.objectContaining({
|
||||
strategy: "source-map-original",
|
||||
source_map_sha256: mapDigest,
|
||||
original_source: name,
|
||||
source_sha256: content === null ? null : digest(content),
|
||||
}),
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: expect.objectContaining({
|
||||
source_name: name,
|
||||
map_path: mapPath,
|
||||
}),
|
||||
properties: expect.objectContaining({
|
||||
source_index: sourceIndex,
|
||||
declaration_index: sourceIndex,
|
||||
source_name_available: true,
|
||||
content_available: content !== null,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({ sha256: mapDigest }),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const [mapPath, content] of [
|
||||
["mixed.js.map", unnamed],
|
||||
["unnamed-empty.js.map", null],
|
||||
] as const)
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: null,
|
||||
properties: expect.objectContaining({
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source_name_available: false,
|
||||
content_available: content !== null,
|
||||
content_sha256: content === null ? null : digest(content),
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: digest(maps[mapPath]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
for (const [path, text] of Object.entries(maps))
|
||||
expect(await readFile(join(root, path), "utf8")).toBe(text);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"rejects non-string source-map names without inventing originals through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-invalid-map-source-");
|
||||
const mapText = JSON.stringify({
|
||||
version: 3,
|
||||
sources: [42, "discarded.ts"],
|
||||
sourcesContent: [null, "export const answer: number = 42;"],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
});
|
||||
await writeFixtureFiles(root, { "invalid.js.map": mapText });
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
expect(graph.coverage.status).toBe("partial");
|
||||
expect(
|
||||
graph.nodes.some(
|
||||
(node) => node.identity.strategy === "source-map-original",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
operation: "parse-local-source-map",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(mapText).digest("hex"),
|
||||
}),
|
||||
limitations: expect.arrayContaining([
|
||||
"Source map contains a non-string source name.",
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(await readFile(join(root, "invalid.js.map"), "utf8")).toBe(mapText);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,164 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, relative } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains unbound CommonJS semantic relationships through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-unbound-requires-");
|
||||
const lines = [
|
||||
'require("./dependency.cjs");',
|
||||
'void require("./dependency.cjs");',
|
||||
'consume(require("./dependency.cjs"));',
|
||||
'require("./dependency.cjs").member;',
|
||||
'const {} = require("./dependency.cjs");',
|
||||
'const bound = require("./dependency.cjs");',
|
||||
'const { left, right } = require("./dependency.cjs");',
|
||||
'module.exports = require("./dependency.cjs", require("./nested.cjs"));',
|
||||
'function local(require) { require("./shadow.cjs"); }',
|
||||
"require(dynamicSpecifier);",
|
||||
'let assigned; assigned = require("./dependency.cjs");',
|
||||
] as const;
|
||||
const source = lines.join("\n");
|
||||
const files = {
|
||||
"main.cjs": source,
|
||||
"imports.mjs": 'import "./dependency.cjs";',
|
||||
"dependency.cjs": 'throw new Error("fixture must not execute");',
|
||||
"nested.cjs": 'throw new Error("fixture must not execute");',
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(([path, text]) =>
|
||||
writeFile(join(root, path), text),
|
||||
),
|
||||
);
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode, response.stderr).toBe(0);
|
||||
document = response.json;
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("analyze_javascript_application", {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
document = response.structuredContent;
|
||||
}
|
||||
const evidence = parseEvidence(document);
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
const links = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "require" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === "main.cjs",
|
||||
);
|
||||
expect(links).toHaveLength(10);
|
||||
for (const [line, count] of [
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
[3, 1],
|
||||
[4, 1],
|
||||
[5, 1],
|
||||
[6, 1],
|
||||
[7, 2],
|
||||
[8, 1],
|
||||
[11, 1],
|
||||
] as const)
|
||||
expect(
|
||||
links.filter(
|
||||
({ evidence: edgeEvidence }) =>
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.start.line === line,
|
||||
),
|
||||
`semantic links on line ${line}`,
|
||||
).toHaveLength(count);
|
||||
const digest = createHash("sha256").update(source).digest("hex");
|
||||
for (const edge of links) {
|
||||
expect(edge.evidence.artifact).toMatchObject({
|
||||
available: true,
|
||||
sha256: digest,
|
||||
});
|
||||
expect(edge.properties.resolution_status).toBe("resolved");
|
||||
expect(edge.properties.resolved_path).toBe(
|
||||
edge.properties.specifier === "./nested.cjs"
|
||||
? "nested.cjs"
|
||||
: "dependency.cjs",
|
||||
);
|
||||
}
|
||||
const bare = links.find(
|
||||
({ evidence: edgeEvidence }) =>
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.start.line === 1,
|
||||
);
|
||||
expect(bare).toMatchObject({
|
||||
properties: {
|
||||
imported_name: null,
|
||||
local_name: null,
|
||||
exported_name: null,
|
||||
},
|
||||
evidence: {
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
source: "main.cjs",
|
||||
start: { line: 1, column: 0 },
|
||||
end: { line: 1, column: lines[0].length - 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.find(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "source-module" &&
|
||||
properties.path === "main.cjs",
|
||||
)?.properties.import_relationships,
|
||||
).toBe(10);
|
||||
expect(
|
||||
graph.edges.some(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "require" &&
|
||||
properties.specifier === "./dependency.cjs",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "commonjs-export" &&
|
||||
properties.specifier === "./dependency.cjs",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,84 @@
|
||||
import { resolve } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { browserScenarioCaptureSchema } from "../../../src/domain/browserScenarioCapture.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { processTest } from "../../support/process/processFixture.js";
|
||||
|
||||
// Actual CLI subprocess and OS signals with a controlled browser session.
|
||||
// This verifies adapter wiring and awaited cleanup, without launching Chromium.
|
||||
processTest
|
||||
.skipIf(process.platform === "win32")
|
||||
.for(["SIGINT", "SIGTERM"] as const)(
|
||||
"awaits browser scenario cleanup and retains observations after %s",
|
||||
async (signal, { processes }) => {
|
||||
const child = processes.spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"--import",
|
||||
resolve("tests/fixtures/browserScenarioCancellation.mjs"),
|
||||
resolve("scripts/rea.mjs"),
|
||||
"capture-browser-scenario",
|
||||
JSON.stringify({
|
||||
browser: { mode: "launch", executable_path: "/controlled/chromium" },
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
actions: [
|
||||
{
|
||||
step_id: "wait",
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 60_000,
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
capture: { after_each_step: ["url"], at_end: [], events: [] },
|
||||
}),
|
||||
"--json",
|
||||
],
|
||||
{ env: { PATH: process.env.PATH ?? "" } },
|
||||
);
|
||||
child.stdin.end();
|
||||
let stdout = "",
|
||||
stderr = "",
|
||||
requested = false;
|
||||
child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
if (!requested && stderr.includes("REA_CONTROLLED_BROWSER_READY"))
|
||||
requested = child.kill(signal);
|
||||
});
|
||||
const deadline = setTimeout(() => child.kill("SIGKILL"), 20_000);
|
||||
try {
|
||||
const exited = await new Promise<{
|
||||
code: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
}>((resolveExit, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, exitSignal) =>
|
||||
resolveExit({ code, signal: exitSignal }),
|
||||
);
|
||||
});
|
||||
expect(requested, stderr).toBe(true);
|
||||
expect(exited, stderr).toEqual({
|
||||
code: signal === "SIGINT" ? 130 : 143,
|
||||
signal: null,
|
||||
});
|
||||
expect(stderr).toContain("signal_present=1");
|
||||
expect(stderr).toContain("REA_CONTROLLED_CLOSE_CALLBACK");
|
||||
expect(stderr).toContain("REA_CONTROLLED_PROFILE_CALLBACK");
|
||||
const document: unknown = JSON.parse(stdout);
|
||||
const evidence = parseEvidence(document);
|
||||
expect(evidence).toEqual(document);
|
||||
const capture = browserScenarioCaptureSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(capture.browser.cleanup).toBe("terminated-owned-process");
|
||||
expect(capture.steps.map(({ status }) => status)).toEqual([
|
||||
"completed",
|
||||
"cancelled",
|
||||
]);
|
||||
expect(capture.completeness.status).toBe("incomplete");
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,154 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import {
|
||||
aotFixtureImage,
|
||||
engineFixtureImage,
|
||||
REFERENCE_HASH,
|
||||
} from "../../src/flutter/FlutterBuild.fixture.js";
|
||||
import {
|
||||
createFlutterApk,
|
||||
createDuplicateFlutterApk,
|
||||
} from "../fixtures/flutterApk.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"CLI and stdio MCP retain Flutter identity, selected ABI and duplicate-member refusals",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
Buffer.from("Login\0").copy(image, 0x2300);
|
||||
const engine = engineFixtureImage({
|
||||
notes: Buffer.from(
|
||||
"040000000800000003000000474e55000123456789abcdef",
|
||||
"hex",
|
||||
),
|
||||
prefix: Buffer.from(
|
||||
"040000000800000003000000474e55001111111111111111",
|
||||
"hex",
|
||||
),
|
||||
labels: ["Android (test) clang version 9.0.8"],
|
||||
});
|
||||
const path = await createFlutterApk("selected target.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/arm64-v8a/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
{ path: "lib/x86_64/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/x86_64/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
]);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, abi] of [
|
||||
["identify_flutter_build", undefined],
|
||||
["inspect_dart_aot", undefined],
|
||||
["inspect_dart_aot", "x86_64"],
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
name.replaceAll("_", "-"),
|
||||
path,
|
||||
"--json",
|
||||
...(abi === undefined ? [] : ["--abi", abi]),
|
||||
],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract(name).outputSchema.parse(result.json);
|
||||
const response = await call(name, {
|
||||
path,
|
||||
...(abi === undefined ? {} : { abi }),
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcp = parseEvidence(response.structuredContent);
|
||||
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
expect(mcp.subject).toEqual(evidence.subject);
|
||||
expect(mcp.subject).toMatchObject({
|
||||
local_path: path,
|
||||
format: "apk",
|
||||
digest: { sha256: evidence.normalized_result.target.sha256 },
|
||||
});
|
||||
expect(mcp.evidence_id).toBe(evidence.evidence_id);
|
||||
if (name === "inspect_dart_aot") {
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
abi: abi ?? "arm64-v8a",
|
||||
libapp: {
|
||||
coverage: "complete",
|
||||
snapshot_hash: REFERENCE_HASH,
|
||||
sha256: createHash("sha256").update(image).digest("hex"),
|
||||
},
|
||||
string_pool: {
|
||||
coverage: "complete",
|
||||
class_like_tokens: expect.arrayContaining(["Login"]),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const identified = toolContract(
|
||||
"identify_flutter_build",
|
||||
).outputSchema.parse(result.json).normalized_result;
|
||||
expect(identified.coverage).toBe("complete");
|
||||
for (const abi of identified.abis) {
|
||||
expect(abi.libflutter).toMatchObject({
|
||||
build_id: "0123456789abcdef",
|
||||
build_id_candidates: ["0123456789abcdef"],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const duplicate = await createDuplicateFlutterApk();
|
||||
for (const name of [
|
||||
"identify_flutter_build",
|
||||
"inspect_dart_aot",
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [name.replaceAll("_", "-"), duplicate, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const mcp = parseMcpToolError(await call(name, { path: duplicate }));
|
||||
expect(mcp.error).toEqual(result.json);
|
||||
expect(mcp.error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ message: expect.stringContaining(duplicate) }] },
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"CLI and MCP retain unsupported snapshot kinds as partial evidence",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
for (const offset of [0x1000, 0x2000])
|
||||
image.writeBigUInt64LE(4n, offset + 12);
|
||||
const path = await createFlutterApk("unsupported-kind.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
]);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-dart-aot", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_dart_aot").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_dart_aot", { path });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
coverage: "partial",
|
||||
libapp: { coverage: "partial", snapshot_hash: REFERENCE_HASH },
|
||||
string_pool: { coverage: "complete" },
|
||||
});
|
||||
expect(
|
||||
evidence.normalized_result.libapp.sections
|
||||
.filter((section) => section.name.endsWith("Data"))
|
||||
.map((section) => section.kind),
|
||||
).toEqual([4, 4]);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,223 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
createGoBinaryByteStringFixture,
|
||||
createGoBinaryDiagnosticFixtures,
|
||||
createGoBinaryFixture,
|
||||
createGoBinaryPathFailureFixture,
|
||||
GO_MODULE_TEXT,
|
||||
} from "../fixtures/go/image.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) {
|
||||
cliTest.skipIf(expectedErrno === "ELOOP" && process.platform === "win32")(
|
||||
`reports native ${expectedErrno} path failure as invalid selected-path input through the public Go CLI`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-path-failure-");
|
||||
const { path, errno } = await createGoBinaryPathFailureFixture(
|
||||
root,
|
||||
expectedErrno,
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_go_binary",
|
||||
issues: [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(errno),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.json).toMatchObject({
|
||||
details: { issues: [{ message: expect.stringContaining(path) }] },
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"preserves invalid embedded Go text bytes through the public CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-byte-strings-");
|
||||
const path = join(root, "byte-strings.elf");
|
||||
const fixture = createGoBinaryByteStringFixture();
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
expect(evidence.normalized_result.build_info).toEqual(
|
||||
fixture.expectedBuildInfo,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
for (const fixture of createGoBinaryDiagnosticFixtures()) {
|
||||
cliTest(
|
||||
`reports ${fixture.code} for ${fixture.name} through the public Go CLI`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-mz-");
|
||||
const path = join(root, `${fixture.name}.exe`);
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: fixture.code,
|
||||
details: {
|
||||
...fixture.details,
|
||||
...(fixture.code === "unsupported_target" ? { path } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"reports a readable unsupported carrier through the public Go CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-");
|
||||
const path = join(root, "text.bin");
|
||||
await writeFile(path, "This is not an executable container.");
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "unsupported_target",
|
||||
details: { operation: "inspect_go_binary", path },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
for (const format of ["elf", "pe", "macho"] as const) {
|
||||
for (const encoding of ["inline", "pointer"] as const) {
|
||||
cliTest(
|
||||
`inspects authored ${format} ${encoding} build metadata through the compiled CLI`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-");
|
||||
const fixture = createGoBinaryFixture({ format, encoding });
|
||||
const path = join(root, "application.bin");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", "application.bin", "--json"],
|
||||
cwd: root,
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
expect(evidence.raw_result).toBeNull();
|
||||
expect(evidence.subject?.local_path).toBe(path);
|
||||
expect(evidence.subject?.digest.sha256).toBe(
|
||||
createHash("sha256").update(fixture.bytes).digest("hex"),
|
||||
);
|
||||
const report = evidence.normalized_result;
|
||||
expect(report).toMatchObject({
|
||||
format,
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
artifact: { path, bytes: fixture.bytes.length },
|
||||
});
|
||||
expect(report.build_info).toMatchObject({
|
||||
header_offset: fixture.headerOffset,
|
||||
encoding,
|
||||
go_version: "go1.26.0",
|
||||
module_text: GO_MODULE_TEXT,
|
||||
module_bytes_base64: fixture.moduleBytes.toString("base64"),
|
||||
module: {
|
||||
path: "example.com/tool/cmd/tool",
|
||||
main: {
|
||||
path: "example.com/tool",
|
||||
version: "(devel)",
|
||||
sum: "",
|
||||
replacement: null,
|
||||
},
|
||||
dependencies: [
|
||||
{
|
||||
path: "example.com/dependency",
|
||||
version: "v1.2.3",
|
||||
sum: "h1:sample",
|
||||
replacement: { path: "../dependency", version: "", sum: "" },
|
||||
},
|
||||
],
|
||||
complete: true,
|
||||
unparsed_lines: [],
|
||||
},
|
||||
});
|
||||
expect(report.build_info?.module.settings).toContainEqual({
|
||||
key: "-ldflags",
|
||||
value: "-s -w",
|
||||
});
|
||||
if (report.build_info === null)
|
||||
throw new Error("Fixture build metadata must be present");
|
||||
const version = report.build_info.version_location;
|
||||
const module = report.build_info.module_location;
|
||||
expect(
|
||||
fixture.bytes
|
||||
.subarray(version.offset, version.offset + version.bytes)
|
||||
.toString("utf8"),
|
||||
).toBe(report.build_info.go_version);
|
||||
expect(
|
||||
fixture.bytes.subarray(module.offset, module.offset + module.bytes),
|
||||
).toEqual(Buffer.from(report.build_info.module_bytes_base64, "base64"));
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
cliTest("preserves MIPS identity in Go CLI Evidence", async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-mips-");
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.writeUInt16LE(8, 18); // ELF EM_MIPS.
|
||||
const path = join(root, "application.elf");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
expect(evidence.subject?.architecture).toBe("mips");
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
architecture: "mips",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
});
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"reports missing build information as unknown and preserves unsupported carriers distinctly",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-");
|
||||
const path = join(root, "metadata-free.elf");
|
||||
await writeFile(path, createGoBinaryFixture({ omitBuildInfo: true }).bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const report = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
).normalized_result;
|
||||
expect(report.build_info).toBeNull();
|
||||
expect(report.limitations.join(" ")).toContain(
|
||||
"does not establish that the binary is not Go",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -7,6 +7,122 @@ import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"managed CLI retains metadata and CIL after repeated local constructor owner lookups",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-row-lookup-");
|
||||
const path = join(root, "local-attributes.dll");
|
||||
await writeFile(
|
||||
path,
|
||||
buildManagedPeFixture({
|
||||
additionalEmptyTypes: 512,
|
||||
customAttributeRowCount: 512,
|
||||
customAttributeTypeRaw: (1 << 3) | 2,
|
||||
typeName: "LookupAttribute",
|
||||
extendsRaw: 0,
|
||||
methodName: ".ctor",
|
||||
methodFlags: 0x1886,
|
||||
methodSignature: Buffer.from([0x20, 0x01, 0x01, 0x0e]),
|
||||
ilBody: Buffer.from([0x06, 0x2a]),
|
||||
}),
|
||||
);
|
||||
const artifact = await cli.run({
|
||||
arguments: ["inspect-managed-artifact", path, "--json"],
|
||||
});
|
||||
expect(artifact.exitCode).toBe(0);
|
||||
expect(artifact.json).toMatchObject({
|
||||
normalized_result: {
|
||||
coverage: { state: "complete", issues: [] },
|
||||
attributes: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type_name: "Fixture.LookupAttribute",
|
||||
constructor_token: "0x06000001",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(artifact.json).toHaveProperty(
|
||||
"normalized_result.attributes.length",
|
||||
512,
|
||||
);
|
||||
const members = await cli.run({
|
||||
arguments: ["inspect-managed-members", path, "--json"],
|
||||
});
|
||||
expect(members.exitCode).toBe(0);
|
||||
expect(members.json).toMatchObject({
|
||||
normalized_result: {
|
||||
coverage: { state: "complete", issues: [] },
|
||||
types: expect.arrayContaining([
|
||||
expect.objectContaining({ full_name: "Fixture.Empty0" }),
|
||||
expect.objectContaining({ full_name: "Fixture.Empty511" }),
|
||||
expect.objectContaining({ full_name: "Fixture.LookupAttribute" }),
|
||||
]),
|
||||
methods: [
|
||||
expect.objectContaining({
|
||||
name: ".ctor",
|
||||
declaring_type: "Fixture.LookupAttribute",
|
||||
body: expect.objectContaining({
|
||||
status: "present",
|
||||
instruction_count: 1,
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(members.json).toHaveProperty("normalized_result.types.length", 513);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI separates .NET Standard API targets from runtime evidence",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-runtime-family-");
|
||||
for (const [name, targetFramework, readyToRun, runtimeFamily] of [
|
||||
["standard", ".NETStandard,Version=v2.0", false, "unknown"],
|
||||
["core", ".NETCoreApp,Version=v8.0", false, "modern-dotnet"],
|
||||
["standard-r2r", ".NETStandard,Version=v2.0", true, "modern-dotnet"],
|
||||
] as const) {
|
||||
const path = join(root, `${name}.dll`);
|
||||
await writeFile(
|
||||
path,
|
||||
buildManagedPeFixture({ targetFramework, readyToRun }),
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-managed-artifact", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
operation: "inspect_managed_artifact",
|
||||
subject: { local_path: path },
|
||||
normalized_result: {
|
||||
classification: {
|
||||
status: "managed",
|
||||
runtime_family: runtimeFamily,
|
||||
implementation: readyToRun ? "cil-and-ready-to-run" : "cil",
|
||||
evidence: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
code: readyToRun
|
||||
? "ready-to-run-signature-observed"
|
||||
: "target-framework-observed",
|
||||
detail: expect.stringContaining(
|
||||
readyToRun
|
||||
? "ReadyToRun signature"
|
||||
: name === "standard"
|
||||
? "does not identify a runtime family"
|
||||
: "names modern .NET",
|
||||
),
|
||||
file_offset: expect.any(Number),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
target_frameworks: [targetFramework],
|
||||
coverage: { state: "complete", issues: [] },
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI preserves evidence, filters, envelopes, and bounded token counts",
|
||||
async ({ cli }) => {
|
||||
@@ -60,3 +176,167 @@ cliTest(
|
||||
expect(jsonl.json).toBe("inspect_managed_members");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI rejects repeated or empty type selections as invalid input",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-cli-types-");
|
||||
const path = join(root, "fixture.dll");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
for (const [types, message] of [
|
||||
[["Fixture.Empty0", "Fixture.Empty0"], "must not repeat a name"],
|
||||
[[""], ">=1 characters"],
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-managed-members",
|
||||
path,
|
||||
...types.flatMap((type) => ["--type", type]),
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
expect.objectContaining({
|
||||
path: expect.stringMatching(/^type/u),
|
||||
message: expect.stringContaining(message),
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI bounds CIL claims by section virtual ranges",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-virtual-size-");
|
||||
for (const virtualSectionSize of [0, 0x800, 0x801, 0x802]) {
|
||||
// The two-byte tiny method starts at RVA 0x2800. Its header alone fits
|
||||
// at size 0x801, and its full CIL fits exactly at size 0x802.
|
||||
const bytes = buildManagedPeFixture({
|
||||
virtualSectionSize,
|
||||
ilBody: Buffer.from([0x06, 0x2a]),
|
||||
});
|
||||
const path = join(root, `virtual-${virtualSectionSize}.dll`);
|
||||
await writeFile(path, bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-managed-members", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result:
|
||||
virtualSectionSize === 0
|
||||
? {
|
||||
methods: [],
|
||||
metadata: { status: "malformed" },
|
||||
coverage: { state: "unavailable" },
|
||||
}
|
||||
: {
|
||||
methods: [
|
||||
{
|
||||
rva: 0x2800,
|
||||
body:
|
||||
virtualSectionSize === 0x802
|
||||
? {
|
||||
status: "present",
|
||||
normalized_il_sha256: expect.any(String),
|
||||
}
|
||||
: {
|
||||
status: "malformed",
|
||||
normalized_il_sha256: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
coverage: {
|
||||
state: virtualSectionSize === 0x802 ? "complete" : "partial",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI distinguishes raw padding from overlapping virtual sections",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-section-identity-");
|
||||
for (const virtualSectionSize of [0x800, 0x900]) {
|
||||
const bytes = buildManagedPeFixture({ virtualSectionSize });
|
||||
const coff = bytes.readUInt32LE(0x3c) + 4;
|
||||
const firstSection = coff + 20 + bytes.readUInt16LE(coff + 16);
|
||||
const secondSection = firstSection + 40;
|
||||
bytes.writeUInt16LE(2, coff + 2);
|
||||
bytes.write(".il", secondSection, "ascii");
|
||||
bytes.writeUInt32LE(0x100, secondSection + 8);
|
||||
bytes.writeUInt32LE(0x2800, secondSection + 12);
|
||||
bytes.writeUInt32LE(0x100, secondSection + 16);
|
||||
bytes.writeUInt32LE(0x0a00, secondSection + 20);
|
||||
const path = join(root, `sections-${virtualSectionSize}.dll`);
|
||||
await writeFile(path, bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-managed-members", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
methods: [
|
||||
{
|
||||
rva: 0x2800,
|
||||
body:
|
||||
virtualSectionSize === 0x800
|
||||
? {
|
||||
status: "present",
|
||||
file_offset: 0x0a00,
|
||||
normalized_il_sha256: expect.any(String),
|
||||
}
|
||||
: {
|
||||
status: "malformed",
|
||||
normalized_il_sha256: null,
|
||||
issue: expect.stringContaining("ambiguous overlapping"),
|
||||
},
|
||||
},
|
||||
],
|
||||
coverage: {
|
||||
state: virtualSectionSize === 0x800 ? "complete" : "partial",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI reports a section table past EOF as invalid input",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-cli-sections-");
|
||||
const path = join(root, "fixture.dll");
|
||||
const bytes = buildManagedPeFixture();
|
||||
const pe = bytes.readUInt32LE(0x3c);
|
||||
const sections = pe + 24 + bytes.readUInt16LE(pe + 20);
|
||||
bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20);
|
||||
await writeFile(path, bytes);
|
||||
for (const command of [
|
||||
"inspect-managed-artifact",
|
||||
"inspect-managed-members",
|
||||
"inspect-managed-native-boundaries",
|
||||
]) {
|
||||
const result = await cli.run({ arguments: [command, path, "--json"] });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: expect.stringContaining("pe.section-data"),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { buildManagedMemberPointerFixture } from "../../src/dotnet/ManagedPe.fixture.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"CLI and stdio MCP retain physical member identities through reordered pointers",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-member-pointers-");
|
||||
const path = join(root, "reordered.dll");
|
||||
const bytes = buildManagedMemberPointerFixture();
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
await writeFile(path, bytes);
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
transport.stderr?.on("data", () => undefined);
|
||||
const client = new Client({ name: "managed-pointer-parity", version: "1" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
for (const name of [
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
] as const) {
|
||||
const cliResult = await cli.run({
|
||||
arguments: [name.replaceAll("_", "-"), path, "--json"],
|
||||
});
|
||||
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
|
||||
const cliEvidence = parseEvidence(cliResult.json);
|
||||
const response = await client.callTool({ name, arguments: { path } });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcpEvidence = parseEvidence(response.structuredContent);
|
||||
expect(mcpEvidence.normalized_result).toEqual(
|
||||
cliEvidence.normalized_result,
|
||||
);
|
||||
expect(mcpEvidence.subject?.digest.sha256).toBe(sha256);
|
||||
expect(cliEvidence.subject?.digest.sha256).toBe(sha256);
|
||||
expect(mcpEvidence.normalized_result).toMatchObject({
|
||||
coverage: { state: "complete", issues: [] },
|
||||
});
|
||||
if (name === "inspect_managed_artifact") {
|
||||
expect(mcpEvidence.normalized_result).toMatchObject({
|
||||
attributes: [
|
||||
expect.objectContaining({
|
||||
constructor_token: "0x06000001",
|
||||
type_name: "Fixture.B",
|
||||
}),
|
||||
],
|
||||
});
|
||||
} else {
|
||||
expect(mcpEvidence.normalized_result).toMatchObject({
|
||||
fields: [
|
||||
expect.objectContaining({
|
||||
token: "0x04000001",
|
||||
declaring_type: "Fixture.B",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
token: "0x04000002",
|
||||
declaring_type: "Fixture.A",
|
||||
}),
|
||||
],
|
||||
methods: [
|
||||
expect.objectContaining({
|
||||
token: "0x06000001",
|
||||
declaring_type: "Fixture.B",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
token: "0x06000002",
|
||||
declaring_type: "Fixture.A",
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,84 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"CLI and stdio MCP inspect CLR ExtraData metadata without shifting table identities",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-extra-data-");
|
||||
const path = join(root, "extra-data.dll");
|
||||
const bytes = buildManagedPeFixture({ metadataExtraData: 0x1234_5678 });
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
await writeFile(path, bytes);
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
transport.stderr?.on("data", () => undefined);
|
||||
const client = new Client({
|
||||
name: "managed-extra-data-parity",
|
||||
version: "1",
|
||||
});
|
||||
try {
|
||||
await client.connect(transport);
|
||||
for (const name of [
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
] as const) {
|
||||
const cliResult = await cli.run({
|
||||
arguments: [name.replaceAll("_", "-"), path, "--json"],
|
||||
});
|
||||
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
|
||||
const cliEvidence = parseEvidence(cliResult.json);
|
||||
const response = await client.callTool({ name, arguments: { path } });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcpEvidence = parseEvidence(response.structuredContent);
|
||||
expect(mcpEvidence.normalized_result).toEqual(
|
||||
cliEvidence.normalized_result,
|
||||
);
|
||||
expect(mcpEvidence.subject?.digest.sha256).toBe(sha256);
|
||||
expect(cliEvidence.subject?.digest.sha256).toBe(sha256);
|
||||
expect(mcpEvidence.normalized_result).toMatchObject({
|
||||
module: {
|
||||
name: "Fixture.dll",
|
||||
mvid: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
},
|
||||
coverage: { state: "complete", issues: [] },
|
||||
});
|
||||
if (name === "inspect_managed_artifact") {
|
||||
expect(mcpEvidence.normalized_result).toMatchObject({
|
||||
assembly: { name: "Fixture.Managed" },
|
||||
});
|
||||
} else {
|
||||
expect(mcpEvidence.normalized_result).toMatchObject({
|
||||
types: [expect.objectContaining({ full_name: "Fixture.Program" })],
|
||||
methods: [
|
||||
expect.objectContaining({
|
||||
token: "0x06000001",
|
||||
name: "Main",
|
||||
declaring_type: "Fixture.Program",
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,560 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { partialProcessCaptureObservationSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { observeProcessStartIdentity } from "../../../src/process/ProcessOwnershipObservation.js";
|
||||
import {
|
||||
parseProcessCapture,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/process/processCaptureParsing.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { itWithCaptureCapability as captureTest } from "../../boundary/process/processCaptureCapability.js";
|
||||
import { expectSerializedUnverifiedHostCleanup } from "../../support/hostCleanup.js";
|
||||
|
||||
const finalizationFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFinalization.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
type CaptureScenario = Record<string, unknown>;
|
||||
type CaptureOutcome =
|
||||
| { readonly kind: "capture"; readonly capture: ProcessCapture }
|
||||
| { readonly kind: "partial"; readonly partial: unknown };
|
||||
|
||||
const captureScenario = (
|
||||
mode: "cooperative" | "ignoring" | "descendant",
|
||||
root: string,
|
||||
additions: CaptureScenario = {},
|
||||
finalExitCode?: number,
|
||||
): CaptureScenario => ({
|
||||
executable: process.execPath,
|
||||
arguments: [
|
||||
finalizationFixture,
|
||||
mode,
|
||||
root,
|
||||
...(finalExitCode === undefined ? [] : [String(finalExitCode)]),
|
||||
],
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [root],
|
||||
idle_timeout_ms: 10_000,
|
||||
...additions,
|
||||
});
|
||||
|
||||
const captureViaCli = async (
|
||||
root: string,
|
||||
scenario: CaptureScenario,
|
||||
): Promise<CaptureOutcome> => {
|
||||
const scenarioPath = join(root, "scenario.json");
|
||||
await writeFile(scenarioPath, JSON.stringify(scenario));
|
||||
const document = await runCliJson([
|
||||
"capture-process",
|
||||
scenarioPath,
|
||||
"--format",
|
||||
"json",
|
||||
]);
|
||||
if (
|
||||
typeof document === "object" &&
|
||||
document !== null &&
|
||||
"code" in document &&
|
||||
document.code === "cleanup_incomplete"
|
||||
)
|
||||
return {
|
||||
kind: "partial",
|
||||
partial: expectSerializedUnverifiedHostCleanup({ error: document }),
|
||||
};
|
||||
if (typeof document === "object" && document !== null && "code" in document)
|
||||
throw new Error(
|
||||
`CLI capture returned an unexpected error: ${JSON.stringify(document).slice(0, 1_000)}`,
|
||||
);
|
||||
return {
|
||||
kind: "capture",
|
||||
capture: parseProcessCapture(parseEvidence(document).normalized_result),
|
||||
};
|
||||
};
|
||||
|
||||
const captureViaMcp = async (
|
||||
scenario: CaptureScenario,
|
||||
): Promise<CaptureOutcome> => {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("capture_process_scenario", scenario);
|
||||
if (response.isError === true) {
|
||||
const parsed = parseMcpToolError(response);
|
||||
if (parsed.error.code === "cleanup_incomplete")
|
||||
return {
|
||||
kind: "partial",
|
||||
partial: expectSerializedUnverifiedHostCleanup(parsed),
|
||||
};
|
||||
throw new Error(
|
||||
`MCP capture returned an unexpected error: ${JSON.stringify(parsed).slice(0, 1_000)}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
kind: "capture",
|
||||
capture: parseProcessCapture(
|
||||
parseEvidence(
|
||||
toolContract("capture_process_scenario").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
),
|
||||
).normalized_result,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const waitFor = async (
|
||||
description: string,
|
||||
predicate: () => Promise<boolean>,
|
||||
deadlineMs = 7_500,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + deadlineMs;
|
||||
while (!(await predicate())) {
|
||||
if (Date.now() >= deadline)
|
||||
throw new Error(`timed out waiting for ${description}`);
|
||||
await delay(25);
|
||||
}
|
||||
};
|
||||
|
||||
const fixturePid = async (root: string): Promise<number> => {
|
||||
let pid = Number.NaN;
|
||||
await waitFor("the finalization fixture PID", async () => {
|
||||
try {
|
||||
pid = Number.parseInt(await readFile(join(root, "pid.txt"), "utf8"), 10);
|
||||
return Number.isSafeInteger(pid) && pid > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return pid;
|
||||
};
|
||||
|
||||
const waitForFinalization = async (root: string): Promise<number> => {
|
||||
// The fixture writes the PID before it can receive SIGTERM, so once the
|
||||
// marker exists the PID file is complete.
|
||||
await waitFor("the finalization fixture to receive SIGTERM", async () => {
|
||||
try {
|
||||
await access(join(root, "sigterm-received"));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return fixturePid(root);
|
||||
};
|
||||
|
||||
const waitForProcessExit = async (pid: number): Promise<void> =>
|
||||
waitFor(`finalization fixture ${String(pid)} to exit`, async () => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return false;
|
||||
} catch (error: unknown) {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const finalizationFromPartial = (partial: unknown) => {
|
||||
const parsed = partialProcessCaptureObservationSchema.parse(partial);
|
||||
if ("capture" in parsed) return parsed.capture.exit.finalization;
|
||||
return parsed.observations.exit.state === "available"
|
||||
? parsed.observations.exit.value.finalization
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const completedCaptureFromOutcome = (outcome: CaptureOutcome) => {
|
||||
if (outcome.kind === "capture") return outcome.capture;
|
||||
const partial = partialProcessCaptureObservationSchema.parse(outcome.partial);
|
||||
expect(partial.execution_failure).toBeNull();
|
||||
if (!("capture" in partial))
|
||||
throw new Error("host cleanup uncertainty omitted the completed capture");
|
||||
return partial.capture;
|
||||
};
|
||||
|
||||
const expectCooperativeFinalization = (
|
||||
outcome: CaptureOutcome,
|
||||
expectedExitCode = 0,
|
||||
): void => {
|
||||
const capture = completedCaptureFromOutcome(outcome);
|
||||
expect(capture.exit.reason, "the deadline remains the exit reason").toBe(
|
||||
"timeout",
|
||||
);
|
||||
expect(capture.exit.code, "a deadline exit has no normal code").toBeNull();
|
||||
expect(
|
||||
capture.exit.finalization,
|
||||
"the cooperative target receives only SIGTERM",
|
||||
).toMatchObject({
|
||||
requested_ms: 1_500,
|
||||
signals: [{ signal: "SIGTERM", delivery: "signaled" }],
|
||||
});
|
||||
expect(
|
||||
capture.exit.finalization?.signals,
|
||||
"cooperative finalization does not send SIGKILL",
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"the cooperative target exits within its interval",
|
||||
).toBeLessThan(1_500);
|
||||
expect(
|
||||
capture.exit.finalization?.exit_code,
|
||||
"the code the finalizer exited with is recorded",
|
||||
).toBe(expectedExitCode);
|
||||
expect(
|
||||
capture.frames.map(({ data }) => data).join(""),
|
||||
"finalization output is captured",
|
||||
).toContain("finalized");
|
||||
expect(
|
||||
capture.files_after.find(({ path }) => path.endsWith("final.json"))?.sha256,
|
||||
"the final filesystem snapshot hashes the final report",
|
||||
).toMatch(/^[0-9a-f]{64}$/u);
|
||||
expect(
|
||||
capture.manifest.scenario.finalization_ms,
|
||||
"the scenario commitment retains finalization_ms",
|
||||
).toBe(1_500);
|
||||
expect(
|
||||
capture.manifest.comparison_contract.finalization_ms,
|
||||
"the comparison contract retains finalization_ms",
|
||||
).toBe(1_500);
|
||||
};
|
||||
|
||||
const expectIgnoringFinalization = (outcome: CaptureOutcome): void => {
|
||||
const capture = completedCaptureFromOutcome(outcome);
|
||||
expect(capture.exit.reason, "the deadline remains the exit reason").toBe(
|
||||
"timeout",
|
||||
);
|
||||
expect(capture.exit.signal, "the ignoring child ends on SIGKILL").toBe(9);
|
||||
expect(
|
||||
capture.exit.finalization?.signals,
|
||||
"SIGTERM is followed by exactly one SIGKILL",
|
||||
).toMatchObject([
|
||||
{ signal: "SIGTERM", delivery: "signaled" },
|
||||
{ signal: "SIGKILL", delivery: "signaled" },
|
||||
]);
|
||||
expect(
|
||||
capture.exit.finalization?.signals,
|
||||
"the ignoring child has exactly two finalization attempts",
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
capture.exit.finalization?.signals[1]?.sent_at_ms,
|
||||
"SIGKILL waits for the requested interval",
|
||||
).toBeGreaterThanOrEqual(1_500);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"the elapsed finalization duration is observed",
|
||||
).toEqual(expect.any(Number));
|
||||
expect(
|
||||
capture.exit.finalization?.exit_code,
|
||||
"an exit ended by SIGKILL records no code",
|
||||
).toBeNull();
|
||||
expect(
|
||||
capture.files_after.find(({ path }) => path.endsWith("final.json")),
|
||||
"an ignoring child does not write a final report",
|
||||
).toBeUndefined();
|
||||
};
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"captures a cooperative finalizer through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-accept-");
|
||||
const scenario = captureScenario("cooperative", root, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
expectCooperativeFinalization(outcome);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"records the non-zero exit code of a finalizer through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-accept-");
|
||||
const scenario = captureScenario(
|
||||
"cooperative",
|
||||
root,
|
||||
{ timeout_ms: 1_500, finalization_ms: 1_500 },
|
||||
3,
|
||||
);
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
expectCooperativeFinalization(outcome, 3);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"forces SIGKILL after the finalization interval through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-accept-");
|
||||
const scenario = captureScenario("ignoring", root, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
expectIgnoringFinalization(outcome);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest(
|
||||
"retains finalization facts with omitted digests and cleans the owned descendant",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-finalization-descendant-");
|
||||
const childDirectory = join(root, "descendant");
|
||||
const outcome = await captureViaMcp(
|
||||
captureScenario("descendant", root, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
settle_ms: 100,
|
||||
limits: { file_bytes: 1 },
|
||||
}),
|
||||
);
|
||||
const capture = completedCaptureFromOutcome(outcome);
|
||||
expect(capture.exit).toMatchObject({
|
||||
reason: "timeout",
|
||||
code: null,
|
||||
finalization: {
|
||||
exit_code: 0,
|
||||
signals: [{ signal: "SIGTERM", delivery: "signaled" }],
|
||||
},
|
||||
});
|
||||
expect(capture.exit.finalization?.signals).toHaveLength(1);
|
||||
expect(capture.settlement).toMatchObject({
|
||||
state: "alive_at_deadline",
|
||||
cleanup_outcome: "cleaned",
|
||||
});
|
||||
expect(capture.frames.map(({ data }) => data).join("")).toContain(
|
||||
"finalized",
|
||||
);
|
||||
const final = capture.files_after.find(({ path }) =>
|
||||
path.endsWith(":final.json"),
|
||||
);
|
||||
expect(final).toMatchObject({ type: "file", sha256: null });
|
||||
expect(capture.truncation_details.filesystem_after).toMatchObject({
|
||||
enumeration_truncated: false,
|
||||
hash_budget_bytes: 1,
|
||||
hash_omissions: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: final?.path,
|
||||
reason: "file_bytes_budget",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(
|
||||
JSON.parse(await readFile(join(root, "final.json"), "utf8")),
|
||||
).toEqual({
|
||||
phase: "final",
|
||||
});
|
||||
await expect(
|
||||
access(join(childDirectory, "sigterm-received")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const childPid = await fixturePid(childDirectory);
|
||||
await expect(
|
||||
observeProcessStartIdentity(childPid),
|
||||
).resolves.toBeUndefined();
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"keeps the default identity through the compiled %s workflow without finalization_ms",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-default-");
|
||||
const scenario = captureScenario("ignoring", root, { timeout_ms: 500 });
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
if (outcome.kind === "partial") {
|
||||
expect(
|
||||
finalizationFromPartial(outcome.partial),
|
||||
"the cleanup-flake partial observation has no default finalization",
|
||||
).toBeUndefined();
|
||||
return;
|
||||
}
|
||||
expect(
|
||||
outcome.capture.exit,
|
||||
"default captures have no finalization evidence",
|
||||
).not.toHaveProperty("finalization");
|
||||
expect(
|
||||
outcome.capture.manifest.scenario,
|
||||
"the committed scenario keeps its legacy identity",
|
||||
).not.toHaveProperty("finalization_ms");
|
||||
expect(
|
||||
outcome.capture.manifest.comparison_contract,
|
||||
"the comparison contract keeps its legacy identity",
|
||||
).not.toHaveProperty("finalization_ms");
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"rejects an unrepresentable combined capture budget through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-budget-");
|
||||
const scenario = captureScenario("cooperative", root, {
|
||||
timeout_ms: Number.MAX_SAFE_INTEGER,
|
||||
finalization_ms: 1,
|
||||
settle_ms: 0,
|
||||
});
|
||||
if (adapter === "CLI") {
|
||||
const scenarioPath = join(root, "scenario.json");
|
||||
await writeFile(scenarioPath, JSON.stringify(scenario));
|
||||
const response = await runCliJson([
|
||||
"capture-process",
|
||||
scenarioPath,
|
||||
"--format",
|
||||
"json",
|
||||
]);
|
||||
expect(
|
||||
JSON.stringify(response),
|
||||
"CLI rejects the combined budget",
|
||||
).toContain("timeout_ms + finalization_ms + settle_ms");
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("capture_process_scenario", scenario);
|
||||
expect(response.isError, "MCP rejects the combined budget").toBe(true);
|
||||
expect(
|
||||
JSON.stringify(response),
|
||||
"MCP explains the combined budget",
|
||||
).toContain("timeout_ms + finalization_ms + settle_ms");
|
||||
}
|
||||
await expect(
|
||||
access(join(root, "periodic.json")),
|
||||
"invalid budgets are rejected before launching the fixture",
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
captureTest(
|
||||
"cancels the compiled CLI and MCP workflows during finalization without waiting for grace",
|
||||
async () => {
|
||||
const cliRoot = await createTestTempDirectory(
|
||||
"rea-finalization-cli-cancel-",
|
||||
);
|
||||
const cliScenarioPath = join(cliRoot, "scenario.json");
|
||||
await writeFile(
|
||||
cliScenarioPath,
|
||||
JSON.stringify(
|
||||
captureScenario("ignoring", cliRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const cli = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/rea.mjs",
|
||||
"capture-process",
|
||||
cliScenarioPath,
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{ stdio: ["ignore", "pipe", "pipe"] },
|
||||
);
|
||||
let stdout = "";
|
||||
cli.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
cli.stderr.resume();
|
||||
const cliClosed = new Promise<{ readonly code: number | null }>(
|
||||
(resolve, reject) => {
|
||||
cli.once("error", reject);
|
||||
cli.once("close", (code) => resolve({ code }));
|
||||
},
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
if (cli.exitCode === null && cli.signalCode === null) cli.kill("SIGKILL");
|
||||
await cliClosed;
|
||||
});
|
||||
const cliFixturePid = await waitForFinalization(cliRoot);
|
||||
const cliStarted = Date.now();
|
||||
cli.kill("SIGINT");
|
||||
const cliExit = await cliClosed;
|
||||
await waitForProcessExit(cliFixturePid);
|
||||
expect(cliExit.code, "SIGINT produces the CLI cancellation status").toBe(
|
||||
130,
|
||||
);
|
||||
expect(
|
||||
Date.now() - cliStarted,
|
||||
"CLI cancellation does not wait for the grace interval",
|
||||
).toBeLessThan(8_000);
|
||||
const cliDocument: unknown = JSON.parse(stdout);
|
||||
if (
|
||||
typeof cliDocument === "object" &&
|
||||
cliDocument !== null &&
|
||||
"code" in cliDocument &&
|
||||
cliDocument.code === "cleanup_incomplete"
|
||||
) {
|
||||
const partial = expectSerializedUnverifiedHostCleanup({
|
||||
error: cliDocument,
|
||||
});
|
||||
expect(
|
||||
finalizationFromPartial(partial),
|
||||
"CLI cleanup-flake partial observation records SIGKILL",
|
||||
).toMatchObject({
|
||||
signals: [{ signal: "SIGTERM" }, { signal: "SIGKILL" }],
|
||||
});
|
||||
} else {
|
||||
expect(cliDocument, "CLI returns a typed cancelled result").toMatchObject(
|
||||
{
|
||||
code: "cancelled",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const mcpRoot = await createTestTempDirectory(
|
||||
"rea-finalization-mcp-cancel-",
|
||||
);
|
||||
const { client } = await connectLocalToolsMcp();
|
||||
const controller = new AbortController();
|
||||
const call = client.callTool(
|
||||
{
|
||||
name: "capture_process_scenario",
|
||||
arguments: captureScenario("ignoring", mcpRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const mcpFixturePid = await waitForFinalization(mcpRoot);
|
||||
const mcpStarted = Date.now();
|
||||
controller.abort(new Error("cancel finalization acceptance fixture"));
|
||||
await expect(
|
||||
call,
|
||||
"MCP cancellation rejects the pending SDK request",
|
||||
).rejects.toThrow("cancel finalization acceptance fixture");
|
||||
await waitForProcessExit(mcpFixturePid);
|
||||
await expect(
|
||||
client.listTools(),
|
||||
"the server accepts a follow-up request after cancelling the capture",
|
||||
).resolves.toMatchObject({ tools: expect.any(Array) });
|
||||
expect(
|
||||
Date.now() - mcpStarted,
|
||||
"MCP cancellation does not wait for the grace interval",
|
||||
).toBeLessThan(8_000);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
@@ -0,0 +1,333 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, copyFile, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { expect, onTestFinished, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js";
|
||||
|
||||
const statusSchema = z.object({ result: z.object({ open: z.boolean() }) });
|
||||
const test = workspaceCliTest.skipIf(process.platform !== "darwin");
|
||||
|
||||
test(
|
||||
"retains a denial-shaped failure when caller arguments can alter the helper's AppleScript",
|
||||
{ timeout: 90_000 },
|
||||
async ({ workspace }) => {
|
||||
for (const source of ["target", "loader"] as const) {
|
||||
const target = workspace.path(
|
||||
source === "target" ? 'quoted"target' : "loader-target",
|
||||
);
|
||||
await copyFile("/usr/bin/true", target);
|
||||
const mode = await workspace.write(
|
||||
`${source}-mode`,
|
||||
"denied-after-handoff",
|
||||
);
|
||||
const receipt = workspace.path(`${source}-bootstrap`);
|
||||
const loaderArgs = [
|
||||
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
|
||||
mode,
|
||||
receipt,
|
||||
...(source === "loader" ? ['caller"loader'] : []),
|
||||
];
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("dist/main.js")],
|
||||
stderr: "pipe",
|
||||
env: {
|
||||
...workspace.environment,
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
});
|
||||
const mcp = new Client({ name: "hopper-literal-boundary", version: "1" });
|
||||
let runtime: string | undefined;
|
||||
onTestFinished(async () => {
|
||||
// SDK close can return immediately after SIGKILL. Wait for its actual
|
||||
// child-close event before recovering this process's retained lease.
|
||||
let serverExited: Promise<void> | undefined;
|
||||
if (transport.pid !== null) {
|
||||
const onclose = transport.onclose;
|
||||
serverExited = new Promise<void>((resolveExit) => {
|
||||
transport.onclose = () => {
|
||||
onclose?.();
|
||||
resolveExit();
|
||||
};
|
||||
});
|
||||
}
|
||||
await mcp.close();
|
||||
await transport.close();
|
||||
await serverExited;
|
||||
// The fixture created only this marker, never a native GUI document.
|
||||
if (runtime !== undefined)
|
||||
await rm(runtime, { recursive: true, force: true });
|
||||
const acquired = await acquireHopperTargetLease({
|
||||
targetPath: target,
|
||||
targetKind: "executable",
|
||||
loaderArgs,
|
||||
runId: "literal-boundary-test-cleanup",
|
||||
});
|
||||
if (!acquired.acquired) throw new Error("Fixture lease remained live");
|
||||
await acquired.lease.release();
|
||||
});
|
||||
await mcp.connect(transport);
|
||||
const call = (name: string, arguments_: Record<string, string> = {}) =>
|
||||
mcp.callTool({ name, arguments: arguments_ });
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
const first = parseMcpToolError(await call("current_document"));
|
||||
runtime = dirname(await readFile(receipt, "utf8"));
|
||||
expect(first.error).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
launcher: {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Not authorized to send Apple events",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await access(`${receipt}.document-created`);
|
||||
await access(runtime);
|
||||
expect(parseMcpToolError(await call("list_procedures"))).toEqual(first);
|
||||
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("recovers a denied Hopper launch through the same stdio MCP session and CLI", async ({
|
||||
workspace,
|
||||
cli,
|
||||
}) => {
|
||||
const target = workspace.path("target");
|
||||
await copyFile("/usr/bin/true", target);
|
||||
const mode = await workspace.write("mode", "denied");
|
||||
const receipt = workspace.path("bootstrap-path");
|
||||
const environment = {
|
||||
...workspace.environment,
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
|
||||
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
|
||||
mode,
|
||||
receipt,
|
||||
]),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
};
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("dist/main.js")],
|
||||
env: environment,
|
||||
stderr: "pipe",
|
||||
});
|
||||
const mcp = new Client({ name: "hopper-startup-recovery", version: "1" });
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await mcp.close();
|
||||
await transport.close();
|
||||
});
|
||||
await mcp.connect(transport);
|
||||
const call = (name: string, arguments_: Record<string, string> = {}) =>
|
||||
mcp.callTool({ name, arguments: arguments_ }).catch((cause: unknown) => {
|
||||
throw new Error(`${name}: ${stderr}`, { cause });
|
||||
});
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(true);
|
||||
for (const operation of ["current_document", "list_procedures"]) {
|
||||
const { error } = parseMcpToolError(await call(operation));
|
||||
expect(error).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
stage: "launch",
|
||||
launcher: {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Not authorized to send Apple events",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(error.message).toContain("Automation");
|
||||
const bootstrap = await readFile(receipt, "utf8");
|
||||
await expect(access(dirname(bootstrap))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
expect((await call("close_binary")).isError).not.toBe(true);
|
||||
const deniedCli = await cli.run({
|
||||
arguments: ["analyze", target, "--provider", "hopper", "--json"],
|
||||
environment,
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
expect(deniedCli.exitCode).toBe(1);
|
||||
expect(deniedCli.json).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: { launcher: { exit_code: 2 } },
|
||||
});
|
||||
|
||||
await writeFile(mode, "bridge");
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(true);
|
||||
expect((await call("current_document")).isError).not.toBe(true);
|
||||
expect((await call("close_binary")).isError).not.toBe(true);
|
||||
expect(
|
||||
statusSchema.parse((await call("binary_session")).structuredContent).result
|
||||
.open,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test(
|
||||
"preserves a timed-out handoff and closes only a late bridge with matching run identity",
|
||||
{ timeout: 60_000 },
|
||||
async ({ workspace }) => {
|
||||
const target = workspace.path("target");
|
||||
await copyFile("/usr/bin/true", target);
|
||||
const mode = await workspace.write("mode", "handoff");
|
||||
const receipt = workspace.path("bootstrap-path");
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("dist/main.js")],
|
||||
stderr: "pipe",
|
||||
env: {
|
||||
...workspace.environment,
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
|
||||
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
|
||||
mode,
|
||||
receipt,
|
||||
]),
|
||||
REA_HOPPER_STARTUP_TIMEOUT_MS: "2000",
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
});
|
||||
const mcp = new Client({ name: "hopper-late-readiness", version: "1" });
|
||||
const children: ChildProcess[] = [];
|
||||
let runtime: string | undefined;
|
||||
const stop = async (child: ChildProcess) => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolveExit) =>
|
||||
child.once("exit", () => resolveExit()),
|
||||
);
|
||||
child.kill("SIGKILL");
|
||||
await exited;
|
||||
};
|
||||
onTestFinished(async () => {
|
||||
await Promise.all(children.map(stop));
|
||||
await mcp.close();
|
||||
await transport.close();
|
||||
if (runtime !== undefined)
|
||||
await rm(runtime, { recursive: true, force: true });
|
||||
});
|
||||
await mcp.connect(transport);
|
||||
const call = (name: string, arguments_: Record<string, string> = {}) =>
|
||||
mcp.callTool({ name, arguments: arguments_ });
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
const initial = parseMcpToolError(await call("current_document"));
|
||||
expect(initial.error).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_timeout",
|
||||
details: { timeout_ms: 2000, launcher: { exit_code: 0 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parseMcpToolError(await call("list_procedures"))).toEqual(initial);
|
||||
const status = z.object({
|
||||
result: z.object({
|
||||
provider_operation_health: z.object({
|
||||
state: z.literal("not_started"),
|
||||
stage: z.literal("launch"),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
status.parse((await call("binary_session")).structuredContent);
|
||||
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
const bootstrap = await readFile(await readFile(receipt, "utf8"), "utf8");
|
||||
const setting = (name: string): string => {
|
||||
const line = bootstrap
|
||||
.split("\n")
|
||||
.find((value) => value.startsWith(`${name} = `));
|
||||
if (line === undefined)
|
||||
throw new Error(`Missing bootstrap setting ${name}`);
|
||||
return z.string().parse(JSON.parse(line.slice(name.length + 3)));
|
||||
};
|
||||
const socket = setting("REA_SOCKET");
|
||||
const token = setting("REA_TOKEN");
|
||||
const runId = setting("REA_RUN_ID");
|
||||
runtime = dirname(socket);
|
||||
const lateBridge = async (identity: string, credential = token) => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
resolve("tests/fixtures/fakeHopper.mjs"),
|
||||
socket,
|
||||
credential,
|
||||
identity,
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
children.push(child);
|
||||
await vi.waitFor(() => access(socket));
|
||||
return child;
|
||||
};
|
||||
for (const [identity, credential] of [
|
||||
["different-run", token],
|
||||
[runId, "different-token"],
|
||||
] as const) {
|
||||
const wrong = await lateBridge(identity, credential);
|
||||
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
expect(wrong.exitCode).toBeNull();
|
||||
await access(runtime);
|
||||
await stop(wrong);
|
||||
await rm(socket, { force: true });
|
||||
}
|
||||
const closing = call("close_binary");
|
||||
await delay(150);
|
||||
const owned = await lateBridge(runId);
|
||||
expect((await closing).isError).not.toBe(true);
|
||||
await vi.waitFor(() => expect(owned.exitCode).toBe(0));
|
||||
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await writeFile(mode, "bridge");
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
expect((await call("current_document")).isError).not.toBe(true);
|
||||
expect((await call("close_binary")).isError).not.toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,299 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { expect } from "vitest";
|
||||
import { parse } from "yaml";
|
||||
import { z } from "zod";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"DSH CLI previews, approves, repairs, launches MCP, repeats and uninstalls while preserving caller YAML",
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-dsh-lifecycle-");
|
||||
const profile = join(home, "selected harness");
|
||||
const config = join(profile, "cordis.patch.yml");
|
||||
const skill = join(
|
||||
home,
|
||||
".agents/skills/reverse-engineer-anything/SKILL.md",
|
||||
);
|
||||
await mkdir(profile);
|
||||
const original = `# caller home patch
|
||||
- insert:
|
||||
- id: rea-mcp
|
||||
name: '@deepseek-ai/dsh-mcp-client'
|
||||
config: {serverName: rea, transport: stdio, command: stale, args: [mcp]}
|
||||
- holder: &op
|
||||
insert:
|
||||
- id: unrelated
|
||||
name: caller-plugin
|
||||
disabled: true
|
||||
config: {cwd: !!js process.cwd()}
|
||||
- id: rea-mcp
|
||||
name: '@deepseek-ai/dsh-mcp-client'
|
||||
config:
|
||||
serverName: rea
|
||||
transport: stdio
|
||||
command: stale
|
||||
args: [mcp]
|
||||
cwd: !!js process.cwd()
|
||||
env:
|
||||
REA_LOG_LEVEL: !!js process.env.REA_LOG_LEVEL
|
||||
- *op
|
||||
`;
|
||||
await writeFile(config, original);
|
||||
const environment = { HOME: home, USERPROFILE: home, DSH_HOME: profile };
|
||||
const run = (args: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: [...args, "--json"],
|
||||
cwd: home,
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
const plan = await run(["setup", "--client", "dsh", "--dry-run"]);
|
||||
expect(plan.exitCode).toBe(0);
|
||||
expect(plan.json).toMatchObject({
|
||||
status: "planned",
|
||||
appliedActions: [],
|
||||
plannedActions: expect.arrayContaining([
|
||||
expect.objectContaining({ id: "configure_client:dsh", target: config }),
|
||||
expect.objectContaining({ id: "install_skill" }),
|
||||
]),
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(original);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const unapproved = await run(["setup", "--client", "dsh"]);
|
||||
expect(unapproved.json).toMatchObject({
|
||||
status: "needs_confirmation",
|
||||
appliedActions: [],
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(original);
|
||||
const configured = await run(["setup", "--client", "dsh", "--yes"]);
|
||||
expect(configured.exitCode).toBe(0);
|
||||
expect(configured.json).toMatchObject({
|
||||
status: "ready",
|
||||
clients: { dsh: { status: "configured" } },
|
||||
});
|
||||
const text = await readFile(config, "utf8");
|
||||
expect(text).toContain("# caller home patch");
|
||||
const patches = parse(text, {
|
||||
customTags: [
|
||||
{
|
||||
tag: "tag:yaml.org,2002:js",
|
||||
resolve: (source: string) => ({ __jsExpr: source }),
|
||||
},
|
||||
],
|
||||
}) as { insert?: { id: string; config: unknown }[] }[];
|
||||
const rows = patches.flatMap((patch) => patch.insert ?? []);
|
||||
expect(rows.filter(({ id }) => id === "unrelated")).toEqual([
|
||||
{
|
||||
id: "unrelated",
|
||||
name: "caller-plugin",
|
||||
disabled: true,
|
||||
config: { cwd: { __jsExpr: "process.cwd()" } },
|
||||
},
|
||||
]);
|
||||
expect(rows.filter(({ id }) => id === "rea-mcp")).toHaveLength(1);
|
||||
const registration = z
|
||||
.object({
|
||||
command: z.string(),
|
||||
args: z.array(z.string()),
|
||||
cwd: z.unknown(),
|
||||
env: z.unknown(),
|
||||
})
|
||||
.parse(rows.find(({ id }) => id === "rea-mcp")?.config);
|
||||
expect(registration.cwd).toEqual({ __jsExpr: "process.cwd()" });
|
||||
expect(registration.env).toMatchObject({
|
||||
REA_LOG_LEVEL: { __jsExpr: "process.env.REA_LOG_LEVEL" },
|
||||
});
|
||||
const doctor = await run(["doctor", "--client", "dsh", "--skill"]);
|
||||
expect(doctor.exitCode).toBe(0);
|
||||
expect(doctor.json).toMatchObject({
|
||||
healthy: true,
|
||||
identity: {
|
||||
registrations: expect.arrayContaining([
|
||||
expect.objectContaining({ client: "dsh", state: "aligned" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
await verifyGeneratedLauncher(registration, home, environment);
|
||||
const repeated = await run(["setup", "--client", "dsh", "--yes"]);
|
||||
expect(repeated.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: [],
|
||||
plannedActions: [],
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(text);
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
|
||||
const removed = await run(["uninstall"]);
|
||||
expect(removed.exitCode).toBe(0);
|
||||
expect(removed.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "dsh", status: "removed" }),
|
||||
]),
|
||||
});
|
||||
const remaining = parse(await readFile(config, "utf8"), {
|
||||
logLevel: "silent",
|
||||
}) as { insert?: { id: string }[] }[];
|
||||
expect(
|
||||
remaining.flatMap((patch) => patch.insert ?? []).map(({ id }) => id),
|
||||
).toEqual(["unrelated"]);
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
|
||||
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
async function verifyGeneratedLauncher(
|
||||
registration: { command: string; args: string[] },
|
||||
home: string,
|
||||
environment: Record<string, string>,
|
||||
): Promise<void> {
|
||||
// Exercise the generated launcher. Native Cordis expression evaluation belongs
|
||||
// to verify:deepseek-client, not this SDK transport journey.
|
||||
const transport = new StdioClientTransport({
|
||||
command: registration.command,
|
||||
args: registration.args,
|
||||
cwd: home,
|
||||
env: { PATH: process.env.PATH ?? "", ...environment },
|
||||
stderr: "pipe",
|
||||
});
|
||||
const client = new Client({ name: "dsh-setup-lifecycle", version: "1" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
expect((await client.listTools()).tools.map(({ name }) => name)).toContain(
|
||||
"binary_session",
|
||||
);
|
||||
const session = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(session.isError).not.toBe(true);
|
||||
expect(session.structuredContent).toMatchObject({
|
||||
result: { open: false },
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
|
||||
cliTest.for(["null", "caller-value", "[caller-value]"])(
|
||||
"DSH CLI refuses to edit config %s and plain uninstall removes its owned row",
|
||||
async (configValue, { cli }) => {
|
||||
const home = await createTestTempDirectory("rea-dsh-malformed-config-");
|
||||
const profile = join(home, ".dsh");
|
||||
const config = join(profile, "cordis.patch.yml");
|
||||
await mkdir(profile);
|
||||
const initial = `# caller patch
|
||||
- insert:
|
||||
- id: other
|
||||
name: caller-plugin
|
||||
- id: rea-mcp
|
||||
name: '@deepseek-ai/dsh-mcp-client'
|
||||
config: ${configValue}
|
||||
`;
|
||||
await writeFile(config, initial);
|
||||
const run = (args: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: [...args, "--json"],
|
||||
cwd: home,
|
||||
environment: { HOME: home, USERPROFILE: home, DSH_HOME: profile },
|
||||
});
|
||||
const configured = await run(["setup", "--client", "dsh", "--yes"]);
|
||||
expect(configured.exitCode).not.toBe(0);
|
||||
expect(configured.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
appliedActions: [],
|
||||
remediation: expect.stringContaining("config: Use a literal mapping"),
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(initial);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const removed = await run(["uninstall"]);
|
||||
expect(removed.exitCode).toBe(0);
|
||||
expect(removed.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "dsh", status: "removed" }),
|
||||
]),
|
||||
});
|
||||
const remaining = await readFile(config, "utf8");
|
||||
expect(remaining).toContain("# caller patch");
|
||||
expect(parse(remaining)).toEqual([
|
||||
{ insert: [{ id: "other", name: "caller-plugin" }] },
|
||||
]);
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(initial);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for([
|
||||
{
|
||||
label: "group-owned rows",
|
||||
patch: `- id: tools
|
||||
insert:
|
||||
- id: other
|
||||
name: caller-plugin
|
||||
- id: rea-mcp
|
||||
name: '@deepseek-ai/dsh-mcp-client'
|
||||
config: {serverName: rea, transport: stdio, command: stale, args: [mcp]}
|
||||
`,
|
||||
remediation: "group with unknown activity",
|
||||
removal: "removed",
|
||||
},
|
||||
{
|
||||
label: "expression-backed inserts",
|
||||
patch: "- insert: !!js process.env.DSH_ROWS\n",
|
||||
remediation: "unknown structure",
|
||||
removal: "retained",
|
||||
},
|
||||
])(
|
||||
"DSH CLI rejects setup and preserves ownership for $label",
|
||||
async ({ patch, remediation, removal }, { cli }) => {
|
||||
const home = await createTestTempDirectory("rea-dsh-ownership-");
|
||||
const profile = join(home, ".dsh");
|
||||
const config = join(profile, "cordis.patch.yml");
|
||||
await mkdir(profile);
|
||||
await writeFile(config, patch);
|
||||
const run = (args: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: [...args, "--json"],
|
||||
cwd: home,
|
||||
environment: { HOME: home, USERPROFILE: home, DSH_HOME: profile },
|
||||
});
|
||||
const setup = await run(["setup", "--client", "dsh", "--yes"]);
|
||||
expect(setup.exitCode).not.toBe(0);
|
||||
expect(setup.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
appliedActions: [],
|
||||
remediation: expect.stringContaining(remediation),
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(patch);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const uninstall = await run(["uninstall"]);
|
||||
expect(uninstall.exitCode).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "dsh", status: removal }),
|
||||
]),
|
||||
});
|
||||
if (removal === "removed") {
|
||||
expect(parse(await readFile(config, "utf8"))).toEqual([
|
||||
{ id: "tools", insert: [{ id: "other", name: "caller-plugin" }] },
|
||||
]);
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(patch);
|
||||
} else {
|
||||
expect(await readFile(config, "utf8")).toBe(patch);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,112 @@
|
||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
// Match native profile rules, including reserved names on POSIX.
|
||||
for (const [variable, profile] of [
|
||||
["OMP_PROFILE", "Bad Name"],
|
||||
["OMP_PROFILE", "../escape"],
|
||||
["OMP_PROFILE", "trailing."],
|
||||
["OMP_PROFILE", "con.txt"],
|
||||
["OMP_PROFILE", "com0"],
|
||||
["OMP_PROFILE", "lpt0"],
|
||||
["OMP_PROFILE", "a".repeat(65)],
|
||||
["PI_PROFILE", "Bad Name"],
|
||||
] as const)
|
||||
cliTest(
|
||||
`OMP rejects invalid ${variable} ${profile} without writing a fallback`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-omp-invalid-profile-");
|
||||
const agent = join(home, "selected agent");
|
||||
const config = join(agent, "mcp.json");
|
||||
const original = '{"mcpServers":{"other":{"command":"other-server"}}}\n';
|
||||
await mkdir(agent);
|
||||
await writeFile(config, original);
|
||||
const run = (args: readonly string[], profile: string) =>
|
||||
cli.run({
|
||||
arguments: args,
|
||||
cwd: home,
|
||||
environment: {
|
||||
USERPROFILE: home,
|
||||
PI_CODING_AGENT_DIR: agent,
|
||||
[variable]: profile,
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
for (const option of ["--dry-run", "--yes"]) {
|
||||
const rejected = await run(
|
||||
["setup", "--client", "omp", option, "--json"],
|
||||
profile,
|
||||
);
|
||||
expect(rejected.exitCode).not.toBe(0);
|
||||
expect(rejected.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
plannedActions: [],
|
||||
appliedActions: [],
|
||||
remediation: expect.stringContaining(
|
||||
`Invalid OMP profile ${JSON.stringify(profile)}`,
|
||||
),
|
||||
});
|
||||
}
|
||||
expect(await readFile(config, "utf8")).toBe(original);
|
||||
for (const path of [
|
||||
config + ".rea.backup",
|
||||
join(home, ".omp", "agent"),
|
||||
join(home, ".agents", "skills"),
|
||||
])
|
||||
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
if (profile !== "con.txt") return;
|
||||
const doctor = await run(
|
||||
["doctor", "--client", "omp", "--json"],
|
||||
"con.txt",
|
||||
);
|
||||
expect(doctor.exitCode).not.toBe(0);
|
||||
expect(doctor.json).toMatchObject({
|
||||
identity: {
|
||||
registrations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
client: "omp",
|
||||
state: "invalid",
|
||||
remediation: expect.stringContaining(
|
||||
"Windows reserved device name",
|
||||
),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
const unrelated = await run(
|
||||
["setup", "--client", "qwen_code", "--yes", "--json"],
|
||||
"Bad Name",
|
||||
);
|
||||
expect(unrelated.exitCode).toBe(0);
|
||||
expect(unrelated.json).toMatchObject({ status: "ready" });
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"OMP explicit default selection overrides an invalid legacy profile",
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-omp-default-profile-");
|
||||
const agent = join(home, "agent");
|
||||
const result = await cli.run({
|
||||
arguments: ["setup", "--client", "omp", "--yes", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
USERPROFILE: home,
|
||||
PI_CODING_AGENT_DIR: agent,
|
||||
OMP_PROFILE: " ",
|
||||
PI_PROFILE: "Bad Name",
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toMatchObject({ status: "ready" });
|
||||
expect(
|
||||
JSON.parse(await readFile(join(agent, "mcp.json"), "utf8")),
|
||||
).toHaveProperty("mcpServers.rea");
|
||||
},
|
||||
);
|
||||
@@ -1,11 +1,203 @@
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { COMPACT_INPUT_SCHEMA_BUDGET_BYTES } from "../../../src/config/mcpInputSchemaProfile.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const profile of ["", "bogus"])
|
||||
cliTest(
|
||||
`setup and doctor refuse an invalid retained schema profile ${JSON.stringify(profile)}`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-pi-invalid-profile-cli-");
|
||||
const agent = join(home, ".pi", "agent");
|
||||
const config = join(agent, "mcp.json");
|
||||
const original = JSON.stringify({
|
||||
mcpServers: {
|
||||
rea: {
|
||||
type: "stdio",
|
||||
command: "rea",
|
||||
args: ["mcp"],
|
||||
env: { REA_MCP_INPUT_SCHEMA_PROFILE: profile },
|
||||
},
|
||||
},
|
||||
});
|
||||
await mkdir(agent, { recursive: true });
|
||||
await writeFile(config, original);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
HOPPER_LAUNCHER_PATH: join(home, "unconfigured-hopper"),
|
||||
};
|
||||
const setup = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
"pi",
|
||||
"--skill=false",
|
||||
"--yes",
|
||||
"--json",
|
||||
],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(setup.exitCode).toBe(1);
|
||||
expect(setup.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
plannedActions: [],
|
||||
appliedActions: [],
|
||||
remediation: expect.stringContaining("REA_MCP_INPUT_SCHEMA_PROFILE"),
|
||||
});
|
||||
const doctor = await cli.run({
|
||||
arguments: ["doctor", "--client", "pi", "--json"],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(doctor.exitCode).toBe(1);
|
||||
expect(doctor.json).toMatchObject({
|
||||
healthy: false,
|
||||
identity: {
|
||||
registrations: expect.arrayContaining([
|
||||
expect.objectContaining({ client: "pi", state: "invalid" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(original);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"setup preserves a configured compact catalog through CLI migration and MCP startup",
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-pi-environment-cli-");
|
||||
const agent = join(home, ".pi", "agent");
|
||||
const config = join(agent, "mcp.json");
|
||||
const custom = {
|
||||
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
|
||||
REA_LOG_LEVEL: "silent",
|
||||
};
|
||||
const original = JSON.stringify({
|
||||
mcpServers: {
|
||||
rea: {
|
||||
type: "stdio",
|
||||
command: "npx",
|
||||
args: ["-y", "rea-agents@1.0.0", "mcp"],
|
||||
env: custom,
|
||||
},
|
||||
},
|
||||
});
|
||||
await mkdir(agent, { recursive: true });
|
||||
await writeFile(config, original);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
HOPPER_LAUNCHER_PATH: join(home, "unconfigured-hopper"),
|
||||
};
|
||||
const arguments_ = [
|
||||
"setup",
|
||||
"--client",
|
||||
"pi",
|
||||
"--skill=false",
|
||||
"--yes",
|
||||
"--json",
|
||||
];
|
||||
const planned = await cli.run({
|
||||
arguments: [...arguments_, "--dry-run"],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(planned.exitCode).toBe(0);
|
||||
expect(planned.json).toMatchObject({
|
||||
plannedActions: [
|
||||
expect.objectContaining({
|
||||
id: "configure_client:pi",
|
||||
detail: expect.stringContaining(
|
||||
"Existing server environment overrides are retained",
|
||||
),
|
||||
}),
|
||||
],
|
||||
appliedActions: [],
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(original);
|
||||
const applied = await cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
expect(applied.exitCode).toBe(0);
|
||||
expect(applied.json).toMatchObject({
|
||||
status: "ready",
|
||||
clients: { pi: { status: "configured" } },
|
||||
});
|
||||
const configured = await readFile(config, "utf8");
|
||||
const registration = z
|
||||
.object({
|
||||
mcpServers: z.object({
|
||||
rea: z.object({
|
||||
command: z.string(),
|
||||
args: z.array(z.string()),
|
||||
env: z.record(z.string(), z.string()).optional(),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(JSON.parse(configured)).mcpServers.rea;
|
||||
const transport = new StdioClientTransport({
|
||||
command: registration.command,
|
||||
args: registration.args,
|
||||
cwd: home,
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
||||
...environment,
|
||||
...registration.env,
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
const client = new Client({ name: "setup-environment", version: "1" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const { tools } = await client.listTools();
|
||||
expect(tools.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
tools
|
||||
.filter(
|
||||
({ inputSchema }) =>
|
||||
Buffer.byteLength(JSON.stringify(inputSchema), "utf8") >
|
||||
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
|
||||
)
|
||||
.map(({ name }) => name),
|
||||
).toEqual([]);
|
||||
expect(await client.ping()).toEqual({});
|
||||
} finally {
|
||||
await client.close();
|
||||
await transport.close();
|
||||
}
|
||||
expect(registration.env).toMatchObject(custom);
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
|
||||
const repeated = await cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
expect(repeated.exitCode).toBe(0);
|
||||
expect(repeated.json).toMatchObject({
|
||||
plannedActions: [],
|
||||
appliedActions: [],
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(configured);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"Pi public CLI plans, requires approval, applies, diagnoses, repeats, and uninstalls only owned content",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { access, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { join, relative, resolve } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"skill-only setup verifies its selected client copy on install, rerun and repair",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-selected-skill-");
|
||||
const selected = join(
|
||||
directory,
|
||||
".claude/skills/reverse-engineer-anything",
|
||||
);
|
||||
const shared = join(directory, ".agents/skills/reverse-engineer-anything");
|
||||
const run = (args: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: [...args, "--json"],
|
||||
cwd: directory,
|
||||
environment: { USERPROFILE: directory },
|
||||
});
|
||||
const preview = await run([
|
||||
"setup",
|
||||
"--skill-client",
|
||||
"claude_code",
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(preview.exitCode, preview.stdout).toBe(0);
|
||||
expect(preview.json).toMatchObject({
|
||||
status: "planned",
|
||||
doctor: {
|
||||
scope: {
|
||||
clients: [],
|
||||
skill: true,
|
||||
skill_clients: ["claude_code"],
|
||||
},
|
||||
},
|
||||
});
|
||||
const registered = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
"claude_code",
|
||||
"--skill=false",
|
||||
"--yes",
|
||||
]);
|
||||
expect(registered.exitCode, registered.stderr).toBe(0);
|
||||
const configuration = join(directory, ".claude.json");
|
||||
const before = await readFile(configuration, "utf8");
|
||||
const args = ["setup", "--skill-client", "claude_code", "--yes"];
|
||||
const installed = await run(args);
|
||||
expect(installed.exitCode, installed.stdout).toBe(0);
|
||||
expect(installed.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: ["installed_skill"],
|
||||
doctor: {
|
||||
healthy: true,
|
||||
scope: { clients: [], skill: true, skill_clients: ["claude_code"] },
|
||||
identity: { skill: { state: "aligned" } },
|
||||
},
|
||||
});
|
||||
const bundle = resolve("skills/reverse-engineer-anything");
|
||||
const assertAligned = async () => {
|
||||
for (const entry of await readdir(bundle, {
|
||||
recursive: true,
|
||||
withFileTypes: true,
|
||||
})) {
|
||||
if (!entry.isFile()) continue;
|
||||
const path = relative(bundle, join(entry.parentPath, entry.name));
|
||||
expect(await readFile(join(selected, path))).toEqual(
|
||||
await readFile(join(bundle, path)),
|
||||
);
|
||||
}
|
||||
};
|
||||
await assertAligned();
|
||||
const repeated = await run(args);
|
||||
expect(repeated.exitCode, repeated.stdout).toBe(0);
|
||||
expect(repeated.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: [],
|
||||
});
|
||||
|
||||
await writeFile(
|
||||
join(selected, "references/native-and-artifacts.md"),
|
||||
"damaged selected copy\n",
|
||||
);
|
||||
const damaged = await run(["doctor", "--client", "claude_code", "--skill"]);
|
||||
expect(damaged.json).toMatchObject({
|
||||
healthy: false,
|
||||
identity: { skill: { state: "stale" } },
|
||||
});
|
||||
const repaired = await run(args);
|
||||
expect(repaired.exitCode, repaired.stdout).toBe(0);
|
||||
expect(repaired.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: ["installed_skill"],
|
||||
});
|
||||
await assertAligned();
|
||||
await expect(access(shared)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await readFile(configuration, "utf8")).toBe(before);
|
||||
|
||||
const sharedControl = await run([
|
||||
"setup",
|
||||
"--skill-client",
|
||||
"shared",
|
||||
"--yes",
|
||||
]);
|
||||
expect(sharedControl.exitCode, sharedControl.stdout).toBe(0);
|
||||
expect(sharedControl.json).toMatchObject({ status: "ready" });
|
||||
await access(join(shared, "SKILL.md"));
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"setup keeps registration and skill readiness selections independent",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-independent-skill-");
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
"codex",
|
||||
"--skill-client",
|
||||
"claude_code",
|
||||
"--yes",
|
||||
"--json",
|
||||
],
|
||||
cwd: directory,
|
||||
environment: { USERPROFILE: directory },
|
||||
});
|
||||
expect(result.exitCode, result.stdout).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
status: "ready",
|
||||
doctor: {
|
||||
healthy: true,
|
||||
scope: {
|
||||
clients: ["codex"],
|
||||
skill_clients: ["claude_code"],
|
||||
skill: true,
|
||||
},
|
||||
identity: { skill: { state: "aligned" } },
|
||||
},
|
||||
});
|
||||
await access(join(directory, ".codex/config.toml"));
|
||||
await access(
|
||||
join(directory, ".claude/skills/reverse-engineer-anything/SKILL.md"),
|
||||
);
|
||||
await expect(access(join(directory, ".claude.json"))).rejects.toMatchObject(
|
||||
{ code: "ENOENT" },
|
||||
);
|
||||
await expect(
|
||||
access(join(directory, ".agents/skills/reverse-engineer-anything")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "../../../src/browser/history/CaptureRelease.js";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../../src/domain/webNetworkCapture.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
@@ -42,80 +43,99 @@ const entry = JSON.stringify({
|
||||
const capture = (count: number) =>
|
||||
`{"log":{"version":"1.2","creator":{"name":"synthetic","version":"1"},"entries":[${Array<string>(count).fill(entry).join(",")}]}}`;
|
||||
|
||||
it("reports real HAR heap exhaustion through CLI and MCP and preserves server usability", async () => {
|
||||
const root = await createTestTempDirectory("rea-har-capacity-");
|
||||
const path = join(root, "caller-marked.har");
|
||||
const dense = capture(34_098);
|
||||
expect(Buffer.byteLength(dense)).toBeLessThan(
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
);
|
||||
await writeFile(path, dense);
|
||||
const { call, client } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_web_network_capture", {
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["caller-marked"],
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response)).toMatchObject({
|
||||
error: {
|
||||
code: "resource_constraint",
|
||||
retryable: false,
|
||||
message: expect.stringContaining("fixed V8 heap"),
|
||||
remediation: {
|
||||
action: expect.stringContaining(
|
||||
"smaller capture exported by its producer",
|
||||
// Node.js enforces the decoder's V8 heap flags. Bun ignores them; on Windows
|
||||
// the decoder's Job Object commit limit is the enforced bound instead, and
|
||||
// Bun elsewhere has no bound this capture can reach.
|
||||
const jobLimit = HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES;
|
||||
it.skipIf(process.versions.bun !== undefined && jobLimit === null)(
|
||||
"reports real HAR memory exhaustion through CLI and MCP and preserves server usability",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-har-capacity-");
|
||||
const path = join(root, "caller-marked.har");
|
||||
const dense = capture(34_098);
|
||||
expect(Buffer.byteLength(dense)).toBeLessThan(
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
);
|
||||
await writeFile(path, dense);
|
||||
const { call, client } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_web_network_capture", {
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
sensitive_values: ["caller-marked"],
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response)).toMatchObject({
|
||||
error: {
|
||||
code: "resource_constraint",
|
||||
retryable: false,
|
||||
message: expect.stringContaining(
|
||||
jobLimit === null
|
||||
? "fixed V8 heap"
|
||||
: "Windows Job Object memory limit",
|
||||
),
|
||||
},
|
||||
details: {
|
||||
resource: "memory",
|
||||
reported_limits: {
|
||||
old_generation_heap_mib: 192,
|
||||
observed_exit_code: process.platform === "win32" ? 134 : null,
|
||||
observed_signal: process.platform === "win32" ? null : "SIGABRT",
|
||||
remediation: {
|
||||
action: expect.stringContaining(
|
||||
"smaller capture exported by its producer",
|
||||
),
|
||||
},
|
||||
captured_output: {
|
||||
stderr: expect.stringContaining("heap out of memory"),
|
||||
truncated: false,
|
||||
details: {
|
||||
resource: "memory",
|
||||
reported_limits:
|
||||
jobLimit === null
|
||||
? {
|
||||
old_generation_heap_mib: 192,
|
||||
observed_exit_code: process.platform === "win32" ? 134 : null,
|
||||
observed_signal:
|
||||
process.platform === "win32" ? null : "SIGABRT",
|
||||
}
|
||||
: { process_memory_limit_bytes: jobLimit, observed_signal: null },
|
||||
captured_output:
|
||||
jobLimit === null
|
||||
? {
|
||||
stderr: expect.stringContaining("heap out of memory"),
|
||||
truncated: false,
|
||||
}
|
||||
: { truncated: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(response)).not.toContain("caller-marked");
|
||||
expect(JSON.stringify(response)).not.toContain("rea doctor");
|
||||
const failed: unknown = await execute(process.execPath, [
|
||||
cli,
|
||||
"inspect-web-network-capture",
|
||||
path,
|
||||
"har",
|
||||
"--json",
|
||||
]).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failed).toMatchObject({ code: 1 });
|
||||
const stdout =
|
||||
typeof failed === "object" && failed !== null && "stdout" in failed
|
||||
? String(failed.stdout)
|
||||
: "";
|
||||
expect(JSON.parse(stdout)).toMatchObject({ code: "resource_constraint" });
|
||||
const small = join(root, "small.har");
|
||||
await writeFile(small, capture(2));
|
||||
await client.ping();
|
||||
const control = await call("inspect_web_network_capture", {
|
||||
capture_path: small,
|
||||
format: "har",
|
||||
});
|
||||
expect(control.isError, JSON.stringify(control)).not.toBe(true);
|
||||
expect(control.structuredContent).toMatchObject({
|
||||
normalized_result: { total_records: 2 },
|
||||
});
|
||||
await truncate(path, WEB_NETWORK_CAPTURE_LIMITS.inputBytes + 1);
|
||||
const oversized = await call("inspect_web_network_capture", {
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
});
|
||||
expect(parseMcpToolError(oversized)).toMatchObject({
|
||||
error: { code: "invalid_request" },
|
||||
});
|
||||
}, 60_000);
|
||||
});
|
||||
expect(JSON.stringify(response)).not.toContain("caller-marked");
|
||||
expect(JSON.stringify(response)).not.toContain("rea doctor");
|
||||
const failed: unknown = await execute(process.execPath, [
|
||||
cli,
|
||||
"inspect-web-network-capture",
|
||||
path,
|
||||
"har",
|
||||
"--json",
|
||||
]).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failed).toMatchObject({ code: 1 });
|
||||
const stdout =
|
||||
typeof failed === "object" && failed !== null && "stdout" in failed
|
||||
? String(failed.stdout)
|
||||
: "";
|
||||
expect(JSON.parse(stdout)).toMatchObject({ code: "resource_constraint" });
|
||||
const small = join(root, "small.har");
|
||||
await writeFile(small, capture(2));
|
||||
await client.ping();
|
||||
const control = await call("inspect_web_network_capture", {
|
||||
capture_path: small,
|
||||
format: "har",
|
||||
});
|
||||
expect(control.isError, JSON.stringify(control)).not.toBe(true);
|
||||
expect(control.structuredContent).toMatchObject({
|
||||
normalized_result: { total_records: 2 },
|
||||
});
|
||||
await truncate(path, WEB_NETWORK_CAPTURE_LIMITS.inputBytes + 1);
|
||||
const oversized = await call("inspect_web_network_capture", {
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
});
|
||||
expect(parseMcpToolError(oversized)).toMatchObject({
|
||||
error: { code: "invalid_request" },
|
||||
});
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
@@ -91,6 +91,52 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
|
||||
),
|
||||
["capture_electron_scenario", { ...electron, args: ["a\0b"] }],
|
||||
["demangle_swift", { symbols: ["abc\0def"] }],
|
||||
["inspect_web_network_capture", { capture_path: nul, format: "har" }],
|
||||
[
|
||||
"export_web_scripts",
|
||||
{ capture_path: nul, output_directory: "/tmp/exported-scripts" },
|
||||
],
|
||||
["inspect_pe_resources", { path: nul }],
|
||||
["inspect_binary_layout", { path: nul }],
|
||||
["inspect_recorded_crash", { path: nul }],
|
||||
["inspect_wasm_artifact", { path: nul }],
|
||||
["inspect_wasm_artifact", { path: "/tmp/sample.wasm", glue_paths: [nul] }],
|
||||
[
|
||||
"inspect_wasm_artifact",
|
||||
{ path: "/tmp/sample.wasm", candidate_paths: [nul] },
|
||||
],
|
||||
["inspect_evm_interface", { path: nul, encoding: "raw" }],
|
||||
[
|
||||
"export_web_scripts",
|
||||
{ capture_path: "/tmp/capture.json", output_directory: nul },
|
||||
],
|
||||
[
|
||||
"trace_web_source_location",
|
||||
{
|
||||
manifest_path: nul,
|
||||
script_index: 0,
|
||||
source_map: { path: "/tmp/source.map", url: "http://127.0.0.1/a" },
|
||||
generated_position: { line: 1, column: 0 },
|
||||
},
|
||||
],
|
||||
[
|
||||
"trace_web_source_location",
|
||||
{
|
||||
manifest_path: "/tmp/manifest.json",
|
||||
script_index: 0,
|
||||
source_map: { path: nul, url: "http://127.0.0.1/a" },
|
||||
generated_position: { line: 1, column: 0 },
|
||||
},
|
||||
],
|
||||
["trace_web_module_imports", { manifest_path: nul, script_index: 0 }],
|
||||
[
|
||||
"trace_web_module_imports",
|
||||
{
|
||||
manifest_path: "/tmp/manifest.json",
|
||||
script_index: 0,
|
||||
import_map: { path: nul, base_url: "http://127.0.0.1/a" },
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
it("rejects OS-invalid local inputs through the real advertised MCP contracts", async () => {
|
||||
@@ -161,26 +207,27 @@ captureTest(
|
||||
}),
|
||||
),
|
||||
];
|
||||
// Each CLI case is an independent process; running them concurrently keeps
|
||||
// the suite well inside its deadline on slower CI runners.
|
||||
await Promise.all(
|
||||
invalid.map(async (options, index) => {
|
||||
const request = { ...scenario, ...options };
|
||||
expect(
|
||||
(await call("capture_process_scenario", request)).isError,
|
||||
JSON.stringify(options),
|
||||
).toBe(true);
|
||||
const path = join(root, `scenario-${String(index)}.json`);
|
||||
await writeFile(path, JSON.stringify(request));
|
||||
await expect(
|
||||
execute(process.execPath, [cli, "capture-process", path, "--json"]),
|
||||
JSON.stringify(options),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining("invalid_request"),
|
||||
});
|
||||
}),
|
||||
);
|
||||
// Each CLI case initializes its own runtime. Bound subprocess fanout too,
|
||||
// so one test cannot oversubscribe the host beyond the Vitest workers.
|
||||
for (let start = 0; start < invalid.length; start += 2)
|
||||
await Promise.all(
|
||||
invalid.slice(start, start + 2).map(async (options, offset) => {
|
||||
const request = { ...scenario, ...options };
|
||||
expect(
|
||||
(await call("capture_process_scenario", request)).isError,
|
||||
JSON.stringify(options),
|
||||
).toBe(true);
|
||||
const path = join(root, `scenario-${String(start + offset)}.json`);
|
||||
await writeFile(path, JSON.stringify(request));
|
||||
await expect(
|
||||
execute(process.execPath, [cli, "capture-process", path, "--json"]),
|
||||
JSON.stringify(options),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining("invalid_request"),
|
||||
});
|
||||
}),
|
||||
);
|
||||
await expect(access(marker)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const missing = join(root, "missing-executable");
|
||||
const failed = await call("capture_process_scenario", {
|
||||
|
||||
@@ -35,7 +35,9 @@ cliTest(
|
||||
environment,
|
||||
timeoutMs: 15000,
|
||||
});
|
||||
expect(cliResponse.exitCode).toBe(0);
|
||||
expect(cliResponse.exitCode, cliResponse.stdout + cliResponse.stderr).toBe(
|
||||
0,
|
||||
);
|
||||
expect(cliResponse.json).toMatchObject({
|
||||
normalized_result: {
|
||||
engine: null,
|
||||
|
||||
@@ -40,7 +40,7 @@ cliTest(
|
||||
},
|
||||
timeoutMs: 45000,
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
|
||||
expect(response.json).toMatchObject({
|
||||
normalized_result: {
|
||||
source: { script_index: 0 },
|
||||
@@ -48,7 +48,9 @@ cliTest(
|
||||
generated_offset: 0,
|
||||
execution: "unknown",
|
||||
matches: [{ content: { text: "original" } }],
|
||||
runtime: { id: "node-v8" },
|
||||
runtime: {
|
||||
id: process.versions.bun === undefined ? "node-v8" : "bun",
|
||||
},
|
||||
},
|
||||
});
|
||||
const transport = new StdioClientTransport({
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { stat, truncate, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotAndroidTarget } from "../../../src/android/AndroidTargetSnapshot.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels an in-flight APK snapshot and removes its partial output",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-android-snapshot-cancel-");
|
||||
const source = join(root, "large.apk");
|
||||
const snapshot = join(root, "target.apk");
|
||||
await writeFile(source, "");
|
||||
// A sparse extent keeps fixture setup cheap while ensuring the copy cannot
|
||||
// finish before the test observes its first output bytes and aborts it.
|
||||
await truncate(source, 64 * 1024 * 1024 * 1024);
|
||||
|
||||
const controller = new AbortController();
|
||||
const pending = snapshotAndroidTarget(
|
||||
source,
|
||||
"0".repeat(64),
|
||||
root,
|
||||
"inspect_android_package",
|
||||
controller.signal,
|
||||
);
|
||||
try {
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
stat(snapshot).then(
|
||||
({ size }) => size > 0,
|
||||
() => false,
|
||||
),
|
||||
{ timeout: 10_000, interval: 10 },
|
||||
)
|
||||
.toBe(true);
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
|
||||
await expect(stat(snapshot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
controller.abort();
|
||||
await pending.catch(() => undefined);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -5,7 +5,8 @@ import { expect, it as test } from "vitest";
|
||||
|
||||
import {
|
||||
inspectJadxAvailability,
|
||||
resolveJadxConfiguration,
|
||||
resolveJadxConfigurationInputs,
|
||||
validateJadxConfiguration,
|
||||
} from "../../../src/android/JadxConfiguration.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -14,6 +15,18 @@ import { writeJadxJarInventory } from "../../fixtures/android/jadxJar.js";
|
||||
|
||||
const it = test.skipIf(process.platform === "win32");
|
||||
|
||||
const resolveConfiguration = async (
|
||||
environment: Parameters<typeof resolveJadxConfigurationInputs>[0],
|
||||
operation: Parameters<typeof resolveJadxConfigurationInputs>[1],
|
||||
) => {
|
||||
const configuration = await resolveJadxConfigurationInputs(
|
||||
environment,
|
||||
operation,
|
||||
);
|
||||
await validateJadxConfiguration(configuration, environment, operation);
|
||||
return configuration;
|
||||
};
|
||||
|
||||
it("rejects malformed or unrelated engine archives with JAR-specific recovery", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-invalid-jar-");
|
||||
const javaHome = await createFakeJdk(root);
|
||||
@@ -29,7 +42,7 @@ it("rejects malformed or unrelated engine archives with JAR-specific recovery",
|
||||
diagnostics: { jar_path: await realpath(jar), phase: "jar-inspection" },
|
||||
});
|
||||
await expect(
|
||||
resolveJadxConfiguration(environment, "inspect_android_package"),
|
||||
resolveConfiguration(environment, "inspect_android_package"),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("REA_JADX_MCP_JAR"),
|
||||
@@ -45,7 +58,7 @@ it("rejects an explicit JAVA_HOME without an executable java binary", async () =
|
||||
await writeJadxJarInventory(jar);
|
||||
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
@@ -62,7 +75,7 @@ it("accepts a full JDK and canonicalizes the selected JAR", async () => {
|
||||
await writeJadxJarInventory(jar);
|
||||
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
@@ -73,12 +86,46 @@ it("accepts a full JDK and canonicalizes the selected JAR", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("admits engine classes past repeated ZIP resource filenames", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-duplicate-resource-");
|
||||
const jar = join(root, "engine.jar");
|
||||
const javaHome = await createFakeJdk(root);
|
||||
await writeOrderedZip(jar, [
|
||||
"META-INF/LICENSE.txt",
|
||||
"META-INF/LICENCE.txt",
|
||||
"com/atxx/jhmcp/JadxSession.class",
|
||||
"com/atxx/jhmcp/SessionHolder.class",
|
||||
"jadx/api/JadxDecompiler.class",
|
||||
"com/google/gson/Gson.class",
|
||||
"io/modelcontextprotocol/kotlin/sdk/server/Server.class",
|
||||
]);
|
||||
const bytes = await readFile(jar);
|
||||
const original = Buffer.from("META-INF/LICENCE.txt");
|
||||
let renamed = 0;
|
||||
for (
|
||||
let offset = bytes.indexOf(original);
|
||||
offset >= 0;
|
||||
offset = bytes.indexOf(original, offset + original.length)
|
||||
) {
|
||||
bytes.write("META-INF/LICENSE.txt", offset);
|
||||
renamed++;
|
||||
}
|
||||
expect(renamed).toBe(2);
|
||||
await writeFile(jar, bytes);
|
||||
await expect(
|
||||
resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
).resolves.toMatchObject({ jar: await realpath(jar) });
|
||||
});
|
||||
|
||||
it("configures heap and visible processors independently without forcing either", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-config-");
|
||||
const jar = join(root, "engine.jar");
|
||||
const javaHome = await createFakeJdk(root);
|
||||
await writeJadxJarInventory(jar);
|
||||
const configuration = await resolveJadxConfiguration(
|
||||
const configuration = await resolveConfiguration(
|
||||
{
|
||||
REA_JADX_MCP_JAR: jar,
|
||||
JAVA_HOME: javaHome,
|
||||
@@ -92,7 +139,7 @@ it("configures heap and visible processors independently without forcing either"
|
||||
"-XX:ActiveProcessorCount=4",
|
||||
]);
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
resolveConfiguration(
|
||||
{
|
||||
REA_JADX_MCP_JAR: jar,
|
||||
JAVA_HOME: javaHome,
|
||||
@@ -107,7 +154,7 @@ it("configures heap and visible processors independently without forcing either"
|
||||
for (const name of ["REA_JADX_HEAP_MIB", "REA_JADX_ACTIVE_PROCESSOR_COUNT"])
|
||||
for (const value of ["", "0", "-1", "1.5", "8g", " 4", "9007199254740992"])
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
resolveConfiguration(
|
||||
{
|
||||
REA_JADX_MCP_JAR: jar,
|
||||
JAVA_HOME: javaHome,
|
||||
@@ -127,7 +174,7 @@ it("distinguishes a runnable JRE from a missing Java executable", async () => {
|
||||
await writeJadxJarInventory(jar);
|
||||
const jreHome = await createFakeJdk(root, false);
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: jreHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
@@ -175,7 +222,7 @@ it("preserves exact Java probe output and marks max-buffer capture as truncated"
|
||||
);
|
||||
await chmod(java, 0o700);
|
||||
|
||||
const failure = await resolveJadxConfiguration(
|
||||
const failure = await resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
"inspect_android_package",
|
||||
).then(
|
||||
@@ -241,7 +288,7 @@ it("distinguishes an unreported Java version from an unsupported old version", a
|
||||
);
|
||||
await chmod(join(oldHome, "bin", "java"), 0o700);
|
||||
await expect(
|
||||
resolveJadxConfiguration(
|
||||
resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: oldHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { PwntoolsLayoutProvider } from "../../../src/native/pwntools/PwntoolsLayoutProvider.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
// Exercise the decoder's launch/cleanup contract independently of the host's
|
||||
// process table. The interpreter has exec'd over its caller-selected wrapper.
|
||||
it
|
||||
.runIf(process.platform === "linux" && process.arch === "x64")
|
||||
.each(["owned", "wrong-token", "wrong-parent"] as const)(
|
||||
"cancels an exec wrapper only with current ownership: %s",
|
||||
async (identity) => {
|
||||
const { root } = await createTestWorkspace("rea-pwntools-wrapper-");
|
||||
onTestFinished(() => removeTestWorkspace(root));
|
||||
const path = join(root, "input");
|
||||
await writeFile(path, "source-owned-seam-bytes");
|
||||
const controller = new AbortController();
|
||||
class DecoderProcess extends EventEmitter {
|
||||
readonly pid = 41234;
|
||||
readonly stdout = new PassThrough();
|
||||
readonly stderr = new PassThrough();
|
||||
exitCode: number | null = null;
|
||||
signalCode: NodeJS.Signals | null = null;
|
||||
kill(): boolean {
|
||||
throw new Error("Cleanup must validate ownership before signaling");
|
||||
}
|
||||
}
|
||||
const child = new DecoderProcess();
|
||||
let live = true;
|
||||
const signalGroup = vi.fn(() => {
|
||||
live = false;
|
||||
child.signalCode = "SIGTERM";
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", null, "SIGTERM");
|
||||
child.emit("close", null, "SIGTERM");
|
||||
});
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (spawn) => {
|
||||
const ownership = {
|
||||
runId: spawn.runId,
|
||||
leaderPid: child.pid,
|
||||
processGroupId: child.pid,
|
||||
expectedParentPid: process.pid,
|
||||
...(spawn.expectedCommand === null
|
||||
? {}
|
||||
: { expectedCommand: spawn.expectedCommand ?? spawn.command }),
|
||||
};
|
||||
setImmediate(() => controller.abort());
|
||||
return {
|
||||
process: child,
|
||||
ownership,
|
||||
cleanup: () =>
|
||||
cleanupOwnedProcessGroup(ownership, {
|
||||
listProcesses: async () =>
|
||||
live
|
||||
? [
|
||||
{
|
||||
pid: child.pid,
|
||||
parentPid:
|
||||
identity === "wrong-parent"
|
||||
? process.pid + 1
|
||||
: process.pid,
|
||||
processGroupId: child.pid,
|
||||
state: "S",
|
||||
command:
|
||||
"/selected/python -I bridge/pwntools/layout.py",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
environment: async () => ({
|
||||
REA_PROCESS_RUN_ID:
|
||||
identity === "wrong-token" ? "another-run" : spawn.runId,
|
||||
}),
|
||||
signalGroup,
|
||||
}),
|
||||
};
|
||||
},
|
||||
);
|
||||
const result = await provider.inspect(
|
||||
{ path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error:
|
||||
identity === "owned"
|
||||
? { _tag: "AnalysisCancelledError" }
|
||||
: { _tag: "ProviderAdapterError", cleanupIncomplete: true },
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledTimes(identity === "owned" ? 1 : 0);
|
||||
},
|
||||
);
|
||||
@@ -294,6 +294,15 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.value.completeness.excluded).toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "webmcp_tools",
|
||||
reason: "out_of_target_scope",
|
||||
}),
|
||||
);
|
||||
expect(result.value.completeness.unavailable_sections).not.toContain(
|
||||
"webmcp_tools",
|
||||
);
|
||||
const serialized = JSON.stringify(result.value);
|
||||
expect(serialized).toContain("tool-secret");
|
||||
expect(serialized).toContain("tool-source-secret");
|
||||
@@ -354,7 +363,9 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
|
||||
"WebMCP.invokeTool",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpBrowserProvider: WebMCP replay inventory", () => {
|
||||
it("returns every WebMCP registration in the replay", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
@@ -410,7 +421,98 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpBrowserProvider WebMCP inventory completeness", () => {
|
||||
describe("CdpBrowserProvider WebMCP malformed replay completeness", () => {
|
||||
it.each(["toolsAdded", "toolsRemoved"] as const)(
|
||||
"keeps malformed %s replay entries from proving WebMCP equality",
|
||||
async (malformedEvent) => {
|
||||
let malformed = false;
|
||||
const registration = {
|
||||
name: "read_item",
|
||||
frameId: "frame-main",
|
||||
inputSchema: { type: "object" },
|
||||
};
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents: (command) => {
|
||||
if (command.method !== "WebMCP.enable") return undefined;
|
||||
const events: {
|
||||
readonly method: string;
|
||||
readonly params: unknown;
|
||||
readonly sessionId?: string;
|
||||
}[] = [
|
||||
{
|
||||
method: "WebMCP.toolsAdded",
|
||||
...(command.sessionId === undefined
|
||||
? {}
|
||||
: { sessionId: command.sessionId }),
|
||||
params: {
|
||||
tools:
|
||||
malformed && malformedEvent === "toolsAdded"
|
||||
? [registration, null]
|
||||
: [registration],
|
||||
},
|
||||
},
|
||||
];
|
||||
if (malformed && malformedEvent === "toolsRemoved")
|
||||
events.push({
|
||||
method: "WebMCP.toolsRemoved",
|
||||
...(command.sessionId === undefined
|
||||
? {}
|
||||
: { sessionId: command.sessionId }),
|
||||
params: { tools: [{ name: registration.name }, null] },
|
||||
});
|
||||
return events;
|
||||
},
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const input = {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
};
|
||||
const inspection = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse(input),
|
||||
);
|
||||
if (!inspection.ok) throw inspection.error;
|
||||
const discover = async () => {
|
||||
const result = await provider.discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse(input),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
const before = await discover();
|
||||
expect(before.tools.items).toHaveLength(1);
|
||||
expect(before.completeness.unavailable_sections).not.toContain(
|
||||
"webmcp_tools",
|
||||
);
|
||||
|
||||
malformed = true;
|
||||
const after = await discover();
|
||||
expect(after.tools.items).toHaveLength(1);
|
||||
expect(after.completeness.unavailable_sections).toContain("webmcp_tools");
|
||||
expect(after.completeness.excluded).toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "webmcp_tools",
|
||||
reason: "invalid_protocol_value",
|
||||
}),
|
||||
);
|
||||
const comparison = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: inspection.value, webmcp: before },
|
||||
after: { inspection: inspection.value, webmcp: after },
|
||||
}),
|
||||
);
|
||||
expect(comparison.dimensions.webmcp).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("CdpBrowserProvider WebMCP schema comparison", () => {
|
||||
it("compares full untrusted declarations independently of object-key order", async () => {
|
||||
const declaration: JsonValue = {
|
||||
type: "object",
|
||||
|
||||
@@ -14,6 +14,36 @@ import {
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describe("CdpBrowserProvider: cancellation and session events", () => {
|
||||
it("honors cancellation during the final progress callback before publishing inspection", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report(update) {
|
||||
if (update.completed === 3) controller.abort();
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "inspect_web_page",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("projects direct-session cancellation onto the requested operation", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
|
||||
@@ -29,6 +29,7 @@ it("preserves unavailable response observations and captures completed peers", a
|
||||
headers: { "Content-Type": "application/json" },
|
||||
postData: '{"selected":true}',
|
||||
},
|
||||
initiator: { type: "script" },
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -130,6 +131,381 @@ it("preserves unavailable response observations and captures completed peers", a
|
||||
).toEqual(["missing-body", "available"]);
|
||||
});
|
||||
|
||||
it("marks JSON response bodies unavailable when their events arrive during body capture", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
const session =
|
||||
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
|
||||
if (command.method === "Network.enable") {
|
||||
const url = `${origin}/initial.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "initial",
|
||||
request: { url, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "initial",
|
||||
response: { url, status: 200, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "initial", encodedDataLength: 16 },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (command.method !== "Network.getResponseBody") return undefined;
|
||||
const url = `${origin}/late.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "late",
|
||||
request: { url, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "late",
|
||||
response: { url, status: 200, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "late", encodedDataLength: 14 },
|
||||
},
|
||||
];
|
||||
},
|
||||
commandResult(command) {
|
||||
return command.method === "Network.getResponseBody"
|
||||
? { body: '{"initial":true}', base64Encoded: false }
|
||||
: 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: 20,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "initial",
|
||||
body_shapes: {
|
||||
status: "included",
|
||||
request: null,
|
||||
response: expect.any(Object),
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
request_id: "late",
|
||||
body_shapes: { status: "unavailable", request: null, response: null },
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not attach a redirect response body to the reused request ID", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
const session =
|
||||
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
|
||||
if (command.method === "Network.enable") {
|
||||
const url = `${origin}/before-redirect.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
request: { url, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
response: { url, status: 302, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "reused", encodedDataLength: 12 },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (command.method !== "Network.getResponseBody") return undefined;
|
||||
const previousUrl = `${origin}/before-redirect.json`;
|
||||
const nextUrl = `${origin}/after-redirect.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
request: { url: nextUrl, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
redirectResponse: {
|
||||
url: previousUrl,
|
||||
status: 302,
|
||||
mimeType: "application/json",
|
||||
encodedDataLength: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
response: {
|
||||
url: nextUrl,
|
||||
status: 200,
|
||||
mimeType: "application/json",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "reused", encodedDataLength: 14 },
|
||||
},
|
||||
];
|
||||
},
|
||||
commandResult(command) {
|
||||
return command.method === "Network.getResponseBody"
|
||||
? { body: '{"belongs":"redirect"}', base64Encoded: false }
|
||||
: 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: 20,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "reused",
|
||||
url: `${browser.allowedOrigin}/after-redirect.json`,
|
||||
redirects: [expect.objectContaining({ status: 302 })],
|
||||
body_shapes: { status: "unavailable", request: null, response: null },
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
});
|
||||
|
||||
it("marks malformed JSON body shapes unavailable while preserving partial request shapes", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
if (command.method !== "Network.enable") return undefined;
|
||||
const session =
|
||||
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
|
||||
return ["unavailable", "partial"].flatMap((requestId) => {
|
||||
const url = `${origin}/${requestId}`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId,
|
||||
request: {
|
||||
url,
|
||||
method: requestId === "partial" ? "POST" : "GET",
|
||||
...(requestId === "partial"
|
||||
? {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
postData: '{"request":true}',
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId,
|
||||
response: { url, status: 200, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId, encodedDataLength: 0 },
|
||||
},
|
||||
];
|
||||
});
|
||||
},
|
||||
commandResult(command) {
|
||||
return command.method === "Network.getResponseBody"
|
||||
? { body: "{", base64Encoded: false }
|
||||
: 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: 20,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "unavailable",
|
||||
body_shapes: { status: "unavailable", request: null, response: null },
|
||||
}),
|
||||
expect.objectContaining({
|
||||
request_id: "partial",
|
||||
body_shapes: {
|
||||
status: "partial",
|
||||
request: expect.any(Object),
|
||||
response: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
expect(result.value.completeness.excluded).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "json_body_shapes",
|
||||
reason: "invalid_protocol_value",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects malformed response-body envelopes and preserves request shapes", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
if (command.method !== "Network.enable") return undefined;
|
||||
const session =
|
||||
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
|
||||
return ["missing-encoding-flag", "invalid-encoding-flag"].flatMap(
|
||||
(requestId) => {
|
||||
const url = `${origin}/${requestId}`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId,
|
||||
request: {
|
||||
url,
|
||||
method:
|
||||
requestId === "invalid-encoding-flag" ? "POST" : "GET",
|
||||
...(requestId === "invalid-encoding-flag"
|
||||
? {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
postData: '{"request":true}',
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId,
|
||||
response: { url, status: 200, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId, encodedDataLength: 0 },
|
||||
},
|
||||
];
|
||||
},
|
||||
);
|
||||
},
|
||||
commandResult(command) {
|
||||
if (command.method !== "Network.getResponseBody") return undefined;
|
||||
return command.params.requestId === "missing-encoding-flag"
|
||||
? { body: '{"response":true}' }
|
||||
: { body: '{"response":true}', base64Encoded: "false" };
|
||||
},
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 20,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "missing-encoding-flag",
|
||||
body_shapes: { status: "unavailable", request: null, response: null },
|
||||
}),
|
||||
expect.objectContaining({
|
||||
request_id: "invalid-encoding-flag",
|
||||
body_shapes: {
|
||||
status: "partial",
|
||||
request: expect.any(Object),
|
||||
response: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "json_body_shapes",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 2,
|
||||
});
|
||||
expect(result.value.completeness.excluded).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "json_body_shapes",
|
||||
reason: "provider_unavailable",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
options: {
|
||||
@@ -169,7 +545,339 @@ it.each([
|
||||
},
|
||||
);
|
||||
|
||||
describe("CdpBrowserProvider: network 1", () => {
|
||||
describe("malformed CDP network request metadata", () => {
|
||||
it("omits requests with missing required metadata and reports the malformed events", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
if (command.method !== "Network.enable") return undefined;
|
||||
const session =
|
||||
command.sessionId === undefined
|
||||
? {}
|
||||
: { sessionId: command.sessionId };
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "valid",
|
||||
request: { url: `${origin}/valid`, method: "GET" },
|
||||
initiator: { type: "future-protocol-type" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "missing-method",
|
||||
request: { url: `${origin}/missing-method` },
|
||||
initiator: { type: "script" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "empty-method",
|
||||
request: { url: `${origin}/empty-method`, method: "" },
|
||||
initiator: { type: "script" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "missing-initiator-type",
|
||||
request: {
|
||||
url: `${origin}/missing-initiator-type`,
|
||||
method: "POST",
|
||||
},
|
||||
initiator: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "missing-request",
|
||||
request: null,
|
||||
initiator: { type: "script" },
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
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).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "valid",
|
||||
method: "GET",
|
||||
initiator: expect.objectContaining({ type: "future-protocol-type" }),
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("malformed reused CDP request IDs", () => {
|
||||
it("keeps the last valid request and redirects after a malformed replacement", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
if (command.method !== "Network.enable") return undefined;
|
||||
const session =
|
||||
command.sessionId === undefined
|
||||
? {}
|
||||
: { sessionId: command.sessionId };
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "redirecting",
|
||||
request: { url: `${origin}/first`, method: "POST" },
|
||||
initiator: { type: "parser" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "redirecting",
|
||||
request: { url: `${origin}/second`, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
redirectResponse: {
|
||||
url: `${origin}/first`,
|
||||
status: 301,
|
||||
mimeType: "text/plain",
|
||||
encodedDataLength: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "redirecting",
|
||||
response: {
|
||||
url: `${origin}/second`,
|
||||
status: 202,
|
||||
mimeType: "application/json",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "redirecting",
|
||||
request: { url: `${origin}/third` },
|
||||
initiator: { type: "other" },
|
||||
redirectResponse: {
|
||||
url: `${origin}/second`,
|
||||
status: 302,
|
||||
mimeType: "text/plain",
|
||||
encodedDataLength: 18,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "redirecting",
|
||||
response: {
|
||||
url: `${origin}/third`,
|
||||
status: 418,
|
||||
mimeType: "application/json",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "redirecting", encodedDataLength: 777 },
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
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;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "redirecting",
|
||||
url: `${browser.allowedOrigin}/second`,
|
||||
method: "GET",
|
||||
status: 202,
|
||||
mime_type: "application/json",
|
||||
encoded_data_length: null,
|
||||
redirects: [
|
||||
expect.objectContaining({
|
||||
url: `${browser.allowedOrigin}/first`,
|
||||
response_url: `${browser.allowedOrigin}/first`,
|
||||
method: "POST",
|
||||
status: 301,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "json_body_shapes",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
expect(
|
||||
browser.commands.filter(
|
||||
({ method }) => method === "Network.getResponseBody",
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CDP network length metadata", () => {
|
||||
it("retains valid zero lengths and excludes malformed loading lengths", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
if (command.method !== "Network.enable") return undefined;
|
||||
const session =
|
||||
command.sessionId === undefined
|
||||
? {}
|
||||
: { sessionId: command.sessionId };
|
||||
const request = (requestId: string, path: string) => ({
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId,
|
||||
request: { url: `${origin}${path}`, method: "GET" },
|
||||
initiator: { type: "parser" },
|
||||
},
|
||||
});
|
||||
return [
|
||||
request("zero", "/zero"),
|
||||
request("missing", "/missing"),
|
||||
request("negative", "/negative"),
|
||||
request("prior", "/prior"),
|
||||
request("redirect-zero", "/redirect-zero-first"),
|
||||
request("redirect-invalid", "/redirect-invalid-first"),
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "zero", encodedDataLength: 0 },
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "missing" },
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "negative", encodedDataLength: -1 },
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "prior", encodedDataLength: 27 },
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "prior", encodedDataLength: -1 },
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "redirect-zero",
|
||||
request: { url: `${origin}/redirect-zero-final`, method: "GET" },
|
||||
initiator: { type: "parser" },
|
||||
redirectResponse: {
|
||||
url: `${origin}/redirect-zero-first`,
|
||||
status: 301,
|
||||
encodedDataLength: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "redirect-invalid",
|
||||
request: {
|
||||
url: `${origin}/redirect-invalid-final`,
|
||||
method: "GET",
|
||||
},
|
||||
initiator: { type: "parser" },
|
||||
redirectResponse: {
|
||||
url: `${origin}/redirect-invalid-first`,
|
||||
status: 301,
|
||||
encodedDataLength: -1,
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
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;
|
||||
const requests = new Map(
|
||||
result.value.network.requests.map((item) => [item.request_id, item]),
|
||||
);
|
||||
expect(requests.get("zero")?.encoded_data_length).toBe(0);
|
||||
expect(requests.get("missing")?.encoded_data_length).toBeNull();
|
||||
expect(requests.get("negative")?.encoded_data_length).toBeNull();
|
||||
expect(requests.get("prior")?.encoded_data_length).toBe(27);
|
||||
expect(
|
||||
requests.get("redirect-zero")?.redirects?.[0]?.encoded_data_length,
|
||||
).toBe(0);
|
||||
expect(
|
||||
requests.get("redirect-invalid")?.redirects?.[0]?.encoded_data_length,
|
||||
).toBeNull();
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "network_requests",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("same-origin redirect chains", () => {
|
||||
it("retains same-origin redirect hops on the one final request", async () => {
|
||||
const browser = await startFakeCdpBrowser({ redirectWithinOrigin: true });
|
||||
trackBrowser(browser);
|
||||
@@ -222,7 +930,9 @@ describe("CdpBrowserProvider: network 1", () => {
|
||||
count: expect.any(Number),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("redirect origin policy", () => {
|
||||
it("drops network evidence when a request redirects outside the approved origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
redirectToDisallowedOrigin: true,
|
||||
|
||||
@@ -69,20 +69,24 @@ describe("CdpBrowserProvider: passive evidence redaction", () => {
|
||||
line: 3,
|
||||
column: 5,
|
||||
});
|
||||
expect(result.value.network.websocket_events).toEqual([
|
||||
expect(result.value.network.websocket_connections).toEqual([
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
direction: "sent",
|
||||
opcode: 1,
|
||||
payload_bytes: Buffer.byteLength("websocket-secret"),
|
||||
payload_shape: null,
|
||||
},
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
direction: "received",
|
||||
opcode: 2,
|
||||
payload_bytes: 3,
|
||||
payload_shape: null,
|
||||
url: `ws://${new URL(browser.allowedOrigin).host}/live?token=websocket-url-secret`,
|
||||
events: [
|
||||
{
|
||||
direction: "sent",
|
||||
opcode: 1,
|
||||
payload_bytes: Buffer.byteLength("websocket-secret"),
|
||||
payload_shape: null,
|
||||
},
|
||||
{
|
||||
direction: "received",
|
||||
opcode: 2,
|
||||
payload_bytes: 3,
|
||||
payload_shape: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(result.value.console.events[0]?.argument_types).toEqual(["string"]);
|
||||
@@ -220,6 +224,7 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sensitiveShapes: true,
|
||||
binaryWebSocketEvent: true,
|
||||
eventsBeforeReply: ["Network.enable"],
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
@@ -288,27 +293,31 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(result.value.network.websocket_events).toEqual([
|
||||
expect(result.value.network.websocket_connections).toEqual([
|
||||
expect.objectContaining({
|
||||
opcode: 1,
|
||||
payload_shape: expect.objectContaining({
|
||||
format: "json",
|
||||
json_shape: expect.objectContaining({
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: [{ kind: "property", name: "token" }],
|
||||
types: ["string"],
|
||||
events: [
|
||||
expect.objectContaining({
|
||||
opcode: 1,
|
||||
payload_shape: expect.objectContaining({
|
||||
format: "json",
|
||||
json_shape: expect.objectContaining({
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: [{ kind: "property", name: "token" }],
|
||||
types: ["string"],
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
opcode: 2,
|
||||
payload_shape: {
|
||||
format: "binary",
|
||||
json_shape: null,
|
||||
},
|
||||
expect.objectContaining({
|
||||
opcode: 2,
|
||||
payload_shape: {
|
||||
format: "binary",
|
||||
json_shape: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
const serialized = JSON.stringify(result.value);
|
||||
@@ -326,6 +335,29 @@ describe("CdpBrowserProvider: explicitly requested text and payload shapes", ()
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpBrowserProvider: WebSocket connection projection", () => {
|
||||
it("retains allowed connections created without observed frames", async () => {
|
||||
const browser = await startFakeCdpBrowser({ webSocketWithoutFrames: 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.websocket_connections).toEqual([
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
url: `ws://${new URL(browser.allowedOrigin).host}/live?token=websocket-url-secret`,
|
||||
events: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpBrowserProvider: malformed approved payloads", () => {
|
||||
it("fails closed on malformed approved response and binary payload encodings", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
@@ -359,9 +391,11 @@ describe("CdpBrowserProvider: malformed approved payloads", () => {
|
||||
// The security-relevant claim: malformed base64 never yields a shape.
|
||||
response: null,
|
||||
});
|
||||
expect(result.value.network.websocket_events[1]).toMatchObject({
|
||||
expect(
|
||||
result.value.network.websocket_connections[0]?.events[1],
|
||||
).toMatchObject({
|
||||
opcode: 2,
|
||||
payload_bytes: 0,
|
||||
payload_bytes: null,
|
||||
payload_shape: { format: "binary", json_shape: null },
|
||||
});
|
||||
expect(result.value.completeness.unavailable_sections).toEqual(
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("CDP target inventory", () => {
|
||||
type: "page",
|
||||
title: `Page ${String(index)}`,
|
||||
url: `https://allowed.example/page/${String(index)}`,
|
||||
attached: false,
|
||||
...(index === 0 ? {} : { attached: index === 1 ? false : true }),
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${String(port)}/devtools/page/${id}`,
|
||||
};
|
||||
});
|
||||
@@ -60,6 +60,14 @@ describe("CDP target inventory", () => {
|
||||
expect(result.value.targets).toHaveLength(targets.length);
|
||||
expect(result.value.targets[0]?.target_id).toBe("target-0000");
|
||||
expect(result.value.targets.at(-1)?.target_id).toBe("target-1100");
|
||||
expect(
|
||||
result.value.targets.slice(0, 3).map(({ attached }) => attached),
|
||||
).toEqual([null, false, true]);
|
||||
expect(
|
||||
result.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
if (server.listening)
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
|
||||
@@ -47,6 +47,7 @@ it.each(["Page.disable", "Target.detachFromTarget"])(
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
await vi.waitFor(() => expect(browser.activeConnectionCount()).toBe(0));
|
||||
},
|
||||
);
|
||||
|
||||
@@ -76,6 +77,11 @@ it("releases cleanup when cancellation arrives after capture completes", async (
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Target.detachFromTarget",
|
||||
);
|
||||
await vi.waitFor(() => expect(browser.activeConnectionCount()).toBe(0));
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
expect((await fetch(`${browser.endpoint}/json/version`)).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("closes an Electron inspection session when cleanup is cancelled", async () => {
|
||||
@@ -122,11 +128,11 @@ it("closes an Electron inspection session when cleanup is cancelled", async () =
|
||||
operation: "inspect_electron_page",
|
||||
},
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Page.disable",
|
||||
);
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Page.disable");
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
await vi.waitFor(() => expect(browser.activeConnectionCount()).toBe(0));
|
||||
expect((await fetch(`${browser.endpoint}/json/version`)).ok).toBe(true);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createServer } from "node:http";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CdpConnection } from "../../../src/browser/CdpConnection.js";
|
||||
import { WEB_RUNTIME_LIMITS } from "../../../src/domain/webRuntime.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
@@ -31,16 +35,14 @@ const INVALID_REPLIES = [
|
||||
],
|
||||
] as const;
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
describe("CDP connection", () => {
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await Promise.all(
|
||||
browsers.splice(0).map(async (browser) => browser.close()),
|
||||
);
|
||||
});
|
||||
|
||||
it("correlates concurrent command responses over a real WebSocket", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
@@ -142,27 +144,177 @@ describe("CDP connection", () => {
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves the selected payload limit reason for pending and subsequent commands", async () => {
|
||||
describe("CDP connection payload budgets", () => {
|
||||
it("accepts an exact UTF-8 payload and rejects one byte more at the selected limit", async () => {
|
||||
const maxPayloadBytes = 512;
|
||||
const exactResult = cdpResultAtSize(maxPayloadBytes);
|
||||
const oversizedResult = cdpResultAtSize(maxPayloadBytes + 1);
|
||||
const results = [exactResult, oversizedResult];
|
||||
let resultIndex = 0;
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: () => ({ oversized: "x".repeat(2_048) }),
|
||||
commandResult: () => results[resultIndex++],
|
||||
});
|
||||
browsers.push(browser);
|
||||
const connection = await CdpConnection.connect(
|
||||
browser.browserWebSocketUrl,
|
||||
"observe_web_execution",
|
||||
undefined,
|
||||
{ maxPayloadBytes: 512 },
|
||||
);
|
||||
let connection: CdpConnection | undefined;
|
||||
try {
|
||||
for (const method of ["Runtime.enable", "Debugger.enable"]) {
|
||||
await expect(connection.send(method)).rejects.toMatchObject({
|
||||
reason: "payload_limit",
|
||||
userMessage: expect.stringContaining("512 byte protocol budget"),
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
connection = await CdpConnection.connect(
|
||||
browser.browserWebSocketUrl,
|
||||
"observe_web_execution",
|
||||
undefined,
|
||||
{ maxPayloadBytes },
|
||||
);
|
||||
await expect(connection.send("Runtime.enable")).resolves.toEqual(
|
||||
exactResult,
|
||||
);
|
||||
await connection.close();
|
||||
|
||||
connection = await CdpConnection.connect(
|
||||
browser.browserWebSocketUrl,
|
||||
"observe_web_execution",
|
||||
undefined,
|
||||
{ maxPayloadBytes },
|
||||
);
|
||||
const disconnected = vi.fn();
|
||||
connection.onDisconnect(disconnected);
|
||||
const openedConnection = connection;
|
||||
const disconnectNotification = new Promise((resolve) =>
|
||||
openedConnection.onDisconnect(resolve),
|
||||
);
|
||||
await expect(connection.send("Runtime.enable")).rejects.toMatchObject({
|
||||
reason: "payload_limit",
|
||||
userMessage: expect.stringContaining("512 byte protocol budget"),
|
||||
});
|
||||
expect(await disconnectNotification).toMatchObject({
|
||||
reason: "payload_limit",
|
||||
});
|
||||
expect(disconnected).toHaveBeenCalledTimes(1);
|
||||
const lateListener = vi.fn();
|
||||
connection.onDisconnect(lateListener);
|
||||
expect(lateListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ reason: "payload_limit" }),
|
||||
);
|
||||
await expect(connection.send("Debugger.enable")).rejects.toMatchObject({
|
||||
reason: "payload_limit",
|
||||
});
|
||||
expect(browser.commands).toHaveLength(2);
|
||||
} finally {
|
||||
await connection?.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the shared protocol budget by default and rejects an oversized frame header", async () => {
|
||||
const server = await startOversizedFrameServer(
|
||||
WEB_RUNTIME_LIMITS.protocolBytes + 1,
|
||||
);
|
||||
let connection: CdpConnection | undefined;
|
||||
try {
|
||||
connection = await CdpConnection.connect(server.url, "inspect_web_page");
|
||||
const disconnectNotification = new Promise((resolve) =>
|
||||
connection?.onDisconnect(resolve),
|
||||
);
|
||||
await expect(connection.send("Runtime.enable")).rejects.toMatchObject({
|
||||
reason: "payload_limit",
|
||||
userMessage: expect.stringContaining(
|
||||
`${WEB_RUNTIME_LIMITS.protocolBytes} byte protocol budget`,
|
||||
),
|
||||
});
|
||||
expect(await disconnectNotification).toMatchObject({
|
||||
reason: "payload_limit",
|
||||
});
|
||||
await expect(connection.send("Debugger.enable")).rejects.toMatchObject({
|
||||
reason: "payload_limit",
|
||||
});
|
||||
} finally {
|
||||
await connection?.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, 0x8000_0000])(
|
||||
"rejects invalid explicit CDP payload budget %s",
|
||||
async (maxPayloadBytes) => {
|
||||
await expect(
|
||||
CdpConnection.connect(
|
||||
"ws://127.0.0.1:1/unused",
|
||||
"inspect_web_page",
|
||||
undefined,
|
||||
{ maxPayloadBytes },
|
||||
),
|
||||
).rejects.toThrow(RangeError);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const cdpResultAtSize = (bytes: number): Readonly<Record<string, unknown>> => {
|
||||
const emptyReply = JSON.stringify({ id: 1, result: { value: "" } });
|
||||
const valueBytes = bytes - Buffer.byteLength(emptyReply);
|
||||
if (valueBytes < 0)
|
||||
throw new RangeError("Requested fixture reply is too small");
|
||||
const value =
|
||||
"é".repeat(Math.floor(valueBytes / 2)) + (valueBytes % 2 === 0 ? "" : "x");
|
||||
const result = { value };
|
||||
const reply = JSON.stringify({ id: 1, result });
|
||||
if (Buffer.byteLength(reply) !== bytes)
|
||||
throw new Error("Fixture reply did not match its requested byte length");
|
||||
return result;
|
||||
};
|
||||
|
||||
const startOversizedFrameServer = async (payloadBytes: number) => {
|
||||
const server = createServer();
|
||||
const sockets = new Set<{ destroy(): void }>();
|
||||
server.on("upgrade", (request, socket) => {
|
||||
const key = request.headers["sec-websocket-key"];
|
||||
if (typeof key !== "string") {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
const accept = createHash("sha1")
|
||||
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
|
||||
.digest("base64");
|
||||
socket.write(
|
||||
[
|
||||
"HTTP/1.1 101 Switching Protocols",
|
||||
"Upgrade: websocket",
|
||||
"Connection: Upgrade",
|
||||
`Sec-WebSocket-Accept: ${accept}`,
|
||||
"",
|
||||
"",
|
||||
].join("\r\n"),
|
||||
);
|
||||
sockets.add(socket);
|
||||
socket.once("close", () => sockets.delete(socket));
|
||||
let sentOversizedHeader = false;
|
||||
socket.on("data", () => {
|
||||
if (sentOversizedHeader) {
|
||||
socket.end(Buffer.from([0x88, 0]));
|
||||
return;
|
||||
}
|
||||
sentOversizedHeader = true;
|
||||
const header = Buffer.alloc(10);
|
||||
header[0] = 0x81;
|
||||
header[1] = 127;
|
||||
header.writeBigUInt64BE(BigInt(payloadBytes), 2);
|
||||
socket.write(header);
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new TypeError("Expected a TCP listener address");
|
||||
return {
|
||||
url: `ws://127.0.0.1:${String(address.port)}`,
|
||||
async close(): Promise<void> {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((error) =>
|
||||
error === undefined ? resolve() : reject(error),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -82,6 +83,7 @@ describe("CdpElectronProvider target selection", () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(index).href,
|
||||
duplicateElectronInventory: true,
|
||||
omitElectronTargetAttachmentState: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const provider = new CdpElectronProvider();
|
||||
@@ -95,8 +97,14 @@ describe("CdpElectronProvider target selection", () => {
|
||||
expect.objectContaining({
|
||||
target_id: "electron-page",
|
||||
file_path: index,
|
||||
attached: null,
|
||||
}),
|
||||
]);
|
||||
expect(
|
||||
listed.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(listed.value.excluded).toEqual({
|
||||
unsupported_url: 3,
|
||||
non_page: 2,
|
||||
@@ -111,6 +119,12 @@ describe("CdpElectronProvider target selection", () => {
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.file_path).toBe(index);
|
||||
expect(inspected.value.target.attached).toBeNull();
|
||||
expect(
|
||||
inspected.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(inspected.value.frames).toEqual([
|
||||
expect.objectContaining({ file_path: index }),
|
||||
]);
|
||||
@@ -199,6 +213,51 @@ describe("CdpElectronProvider target selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider packaged pages", () => {
|
||||
it("lists and inspects packaged pages served from inside app.asar", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-asar-provider-");
|
||||
temporary.push(root);
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
await writeFile(
|
||||
join(source, "index.html"),
|
||||
"<script src='app.js'></script>",
|
||||
);
|
||||
await writeFile(join(source, "app.js"), "export const app = true;");
|
||||
const archive = join(root, "app.asar");
|
||||
await createPackage(source, archive);
|
||||
const packaged = await realpath(archive);
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: `${pathToFileURL(join(archive, "index.html")).href}?isBookDoubleClicked=0#/library`,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const provider = new CdpElectronProvider();
|
||||
const listed = await provider.listTargets(
|
||||
listElectronTargetsInputSchema.parse({ cdp_endpoint: browser.endpoint }),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "electron-page",
|
||||
file_path: join(packaged, "index.html"),
|
||||
}),
|
||||
]);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
target_id: "electron-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.file_path).toBe(join(packaged, "index.html"));
|
||||
expect(inspected.value.scripts.items).toEqual([
|
||||
expect.objectContaining({ file_path: join(packaged, "app.js") }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider capture", () => {
|
||||
it.each([{}, { scriptSource: null }, { scriptSource: 123 }])(
|
||||
"rejects malformed Electron source replies instead of inventing source: %j",
|
||||
|
||||
@@ -39,6 +39,68 @@ const equivalentBodies = [
|
||||
},
|
||||
];
|
||||
|
||||
it("captures all repeated array rows and empty arrays without retaining payload values", async () => {
|
||||
const count = 6_000;
|
||||
const body = JSON.stringify(
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
value: index % 2 === 0 ? index : "payload-value-excluded",
|
||||
nested: index % 2 === 0 ? [] : [true, null],
|
||||
empty: [],
|
||||
"*": { "": "payload-value-excluded" },
|
||||
})),
|
||||
);
|
||||
const before = captureBody("base64 response", body);
|
||||
const shape = before.network.requests[0]?.body_shapes.response;
|
||||
const element = { kind: "array-element" };
|
||||
const property = (name: string) => ({ kind: "property", name });
|
||||
expect(shape).toMatchObject({
|
||||
root_type: "array",
|
||||
node_count: count * 7 + 1,
|
||||
max_depth_observed: 3,
|
||||
properties: [
|
||||
{ path: [element], types: ["object"], observations: count },
|
||||
{
|
||||
path: [element, property("*")],
|
||||
types: ["object"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("*"), property("")],
|
||||
types: ["string"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("empty")],
|
||||
types: ["array"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("nested")],
|
||||
types: ["array"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("nested"), element],
|
||||
types: ["boolean", "null"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("value")],
|
||||
types: ["number", "string"],
|
||||
observations: count,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(shape)).not.toContain("payload-value-excluded");
|
||||
const after = captureBody("base64 response", body);
|
||||
expect(
|
||||
(await compareCaptures(before, after)).dimensions.network,
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
});
|
||||
|
||||
describe.each<BodySource>(["request", "response", "base64 response"])(
|
||||
"CDP %s JSON shape comparison",
|
||||
(source) => {
|
||||
@@ -254,6 +316,7 @@ const captureBody = (source: BodySource, body: string): WebPageInspection => {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
postData: source === "request" ? body : "{}",
|
||||
},
|
||||
initiator: { type: "script" },
|
||||
},
|
||||
});
|
||||
const responseBody = source === "request" ? "{}" : body;
|
||||
@@ -276,8 +339,10 @@ const captureBody = (source: BodySource, body: string): WebPageInspection => {
|
||||
encodedDataLength: Buffer.byteLength(responseBody),
|
||||
},
|
||||
});
|
||||
expect(events.responseBodyRequestIds()).toEqual(["request-1"]);
|
||||
events.ingestResponseBody("request-1", {
|
||||
const candidate = events.responseBodyRequests()[0];
|
||||
expect(candidate?.requestId).toBe("request-1");
|
||||
expect(candidate).toBeDefined();
|
||||
events.ingestResponseBody(candidate!, {
|
||||
body:
|
||||
source === "base64 response"
|
||||
? Buffer.from(responseBody).toString("base64")
|
||||
@@ -323,7 +388,7 @@ const captureBody = (source: BodySource, body: string): WebPageInspection => {
|
||||
resources: [],
|
||||
network: {
|
||||
requests: [...events.network.values()],
|
||||
websocket_events: events.websockets,
|
||||
websocket_connections: [...events.webSocketConnectionsById.values()],
|
||||
coverage_started_at: CAPTURE_TIME,
|
||||
prior_activity_available: false,
|
||||
},
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createJavaScriptRuntimeObservationEvidence } from "../../../src/applica
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import { publishWebScripts } from "../../../src/browser/assets/PublishWebScripts.js";
|
||||
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import { selectScriptCapture } from "../../../src/browser/assets/ScriptCaptureAdapters.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { inspectElectronPageInputSchema } from "../../../src/domain/javascript/electronObservation.js";
|
||||
@@ -69,6 +70,8 @@ describe.each(["browser", "electron"] as const)(
|
||||
"$name through capture and consumers",
|
||||
async ({ reported, expected }) => {
|
||||
const root = await fixtureRoot();
|
||||
const artifactResources = new ArtifactResourceScope();
|
||||
resources.push(() => artifactResources.close());
|
||||
const browser = await startFakeCdpBrowser({
|
||||
...(kind === "electron"
|
||||
? { electronFileUrl: pathToFileURL(join(root, "index.html")).href }
|
||||
@@ -129,6 +132,7 @@ describe.each(["browser", "electron"] as const)(
|
||||
},
|
||||
selectScriptCapture(result.value),
|
||||
createHash("sha256").update(captureBytes).digest("hex"),
|
||||
{ resources: artifactResources },
|
||||
);
|
||||
expect(exported.scripts[0]?.source).toMatchObject({
|
||||
is_module: expected.is_module,
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { waitForBrowserDevtoolsPort } from "../../../src/browser/BrowserProcessStartup.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
processTest as it,
|
||||
waitForExit,
|
||||
} from "../../support/process/processFixture.js";
|
||||
|
||||
const chromeExecutable = [
|
||||
process.env.REA_BROWSER_EXECUTABLE,
|
||||
"/usr/bin/google-chrome-stable",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
].find(
|
||||
(candidate): candidate is string =>
|
||||
typeof candidate === "string" &&
|
||||
candidate.length > 0 &&
|
||||
existsSync(candidate),
|
||||
);
|
||||
|
||||
// Match the real-browser verifier: a cold Chrome launch on a loaded coverage
|
||||
// runner can exceed 20 seconds before publishing DevToolsActivePort.
|
||||
const CHROME_STARTUP_TIMEOUT_MS = 60_000;
|
||||
const CHROME_TEST_TIMEOUT_MS = CHROME_STARTUP_TIMEOUT_MS + 30_000;
|
||||
|
||||
// Issue 1586's page, plus the HTML, image, use, and foreign-origin cases the
|
||||
// real snapshot must distinguish. The XHTML page is the prefixed-svg gap
|
||||
// reported on PR 1602. The tests are skipped when no Chrome-family executable
|
||||
// is installed.
|
||||
const pageHtml = `<!doctype html><title>x</title>
|
||||
<svg width="10" height="10">
|
||||
<a id="s2" xlink:href="/xl-s2h"><text>s2</text></a>
|
||||
<a id="both" xlink:href="/xlink-loses" href="/href-wins"><text>both</text></a>
|
||||
<image id="img" xlink:href="/xl-image" />
|
||||
<use id="use" xlink:href="/xl-use" />
|
||||
<a id="out" xlink:href="https://cdn.example.test/out"><text>out</text></a>
|
||||
</svg>
|
||||
<a id="html" xlink:href="/xl-html">html</a>
|
||||
`;
|
||||
|
||||
it.skipIf(chromeExecutable === undefined)(
|
||||
"reports the issue page SVG xlink:href links through headless Chrome",
|
||||
async ({ processes }) => {
|
||||
const executable = chromeExecutable;
|
||||
if (executable === undefined) return;
|
||||
const profile = await createTestTempDirectory("rea-svg-xlink-");
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
||||
response.end(pageHtml);
|
||||
});
|
||||
await new Promise<void>((resolve) => {
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("SVG fixture server did not bind a TCP port");
|
||||
const origin = `http://127.0.0.1:${String(address.port)}`;
|
||||
const pageUrl = `${origin}/x.html`;
|
||||
let stderr = "";
|
||||
const child = processes.spawn(executable, [
|
||||
"--headless=new",
|
||||
...(process.env.REA_BROWSER_NO_SANDBOX === "true"
|
||||
? ["--no-sandbox"]
|
||||
: []),
|
||||
"--remote-debugging-address=127.0.0.1",
|
||||
"--remote-debugging-port=0",
|
||||
`--user-data-dir=${profile}`,
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--disable-background-networking",
|
||||
"--disable-component-update",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-sync",
|
||||
"--metrics-recording-only",
|
||||
pageUrl,
|
||||
]);
|
||||
child.stdout.on("data", () => undefined);
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
if (stderr.length < 8_192) stderr += chunk.toString("utf8");
|
||||
});
|
||||
try {
|
||||
const port = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable,
|
||||
activePortPath: join(profile, "DevToolsActivePort"),
|
||||
stderr: () => stderr,
|
||||
timeoutMs: CHROME_STARTUP_TIMEOUT_MS,
|
||||
});
|
||||
const endpoint = `http://127.0.0.1:${String(port)}`;
|
||||
const provider = new CdpBrowserProvider();
|
||||
const targetId = await pageTarget(provider, endpoint, origin, pageUrl);
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
target_id: targetId,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const urls = result.value.metadata.dom_urls;
|
||||
const html = result.value.dom.nodes.find(
|
||||
(node) =>
|
||||
node.node_name === "A" && node.attribute_names.includes("xlink:href"),
|
||||
);
|
||||
expect(html).toBeDefined();
|
||||
expect(urls.some((url) => url.node_index === html?.index)).toBe(false);
|
||||
expect(urls).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
attribute: "href",
|
||||
url: `${origin}/xl-s2h`,
|
||||
destination_scope: "approved",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
attribute: "href",
|
||||
url: `${origin}/href-wins`,
|
||||
destination_scope: "approved",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
attribute: "href",
|
||||
url: `${origin}/xl-image`,
|
||||
destination_scope: "approved",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
attribute: "href",
|
||||
url: `${origin}/xl-use`,
|
||||
destination_scope: "approved",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
attribute: "href",
|
||||
url: null,
|
||||
destination_scope: "outside_policy",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
urls.some(
|
||||
(url) =>
|
||||
url.url?.endsWith("/xl-html") === true ||
|
||||
url.url?.endsWith("/xlink-loses") === true,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(urls.every((url) => url.attribute === "href")).toBe(true);
|
||||
expect(urls).toHaveLength(5);
|
||||
} finally {
|
||||
child.kill("SIGTERM");
|
||||
if (!(await waitForExit(child, 2_000))) child.kill("SIGKILL");
|
||||
await waitForExit(child, 2_000);
|
||||
await new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
}
|
||||
},
|
||||
CHROME_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
const xhtmlPage = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<head><title>x</title></head>
|
||||
<body>
|
||||
<svg:svg width="10" height="10">
|
||||
<svg:a id="pa1" xlink:href="/xl-pa1"><svg:text>p</svg:text></svg:a>
|
||||
<svg:image id="img" xlink:href="/xl-image"/>
|
||||
<svg:foreignObject width="10" height="10">
|
||||
<a id="fo-a" xlink:href="/xl-html-fo">no</a>
|
||||
<h:a xmlns:h="http://www.w3.org/1999/xhtml" id="fo-h" xlink:href="/xl-h">no</h:a>
|
||||
<svg:a id="fo-svg" xlink:href="/xl-fo-svg"><svg:text>y</svg:text></svg:a>
|
||||
</svg:foreignObject>
|
||||
</svg:svg>
|
||||
<svg:a id="orphan" xlink:href="/xl-orphan"><svg:text>o</svg:text></svg:a>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink" width="10" height="10">
|
||||
<a id="custom" x:href="/xl-custom"><text>c</text></a>
|
||||
<a id="both" href="/href-wins" x:href="/xlink-loses"><text>b</text></a>
|
||||
<a id="empty" href="" x:href="/xlink-empty"><text>e</text></a>
|
||||
</svg>
|
||||
<svg:a id="out" xlink:href="https://cdn.example.test/out"><svg:text>out</svg:text></svg:a>
|
||||
<bogus:svg xmlns:bogus="http://example.com/not-svg" id="bogus" xlink:href="/xl-bogus"/>
|
||||
<a id="xhtml-a" xlink:href="/xl-xhtml-a">no</a>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
for (const { format, page, contentType, nodeNames, link, destinations } of [
|
||||
{
|
||||
format: "XHTML",
|
||||
page: xhtmlPage,
|
||||
contentType: "application/xhtml+xml",
|
||||
nodeNames: ["html", "svg:a", "bogus:svg"],
|
||||
link: { name: "svg:a", attribute: "xlink:href" },
|
||||
destinations: [
|
||||
"/xl-pa1",
|
||||
"/xl-image",
|
||||
"/xl-fo-svg",
|
||||
"/xl-orphan",
|
||||
"/xl-custom",
|
||||
"/href-wins",
|
||||
"",
|
||||
null,
|
||||
],
|
||||
},
|
||||
{
|
||||
format: "SVG",
|
||||
page: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:p="http://www.w3.org/1999/xlink"><a p:href="/linked"><text>link</text></a></svg>`,
|
||||
contentType: "image/svg+xml",
|
||||
nodeNames: ["svg", "a"],
|
||||
link: { name: "a", attribute: "p:href" },
|
||||
destinations: ["/linked"],
|
||||
},
|
||||
]) {
|
||||
it.skipIf(chromeExecutable === undefined)(
|
||||
`reports namespaced SVG links from a standalone ${format} document through headless Chrome`,
|
||||
async ({ processes }) => {
|
||||
const executable = chromeExecutable;
|
||||
if (executable === undefined) return;
|
||||
const profile = await createTestTempDirectory("rea-svg-xhtml-");
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200, {
|
||||
"content-type": `${contentType}; charset=utf-8`,
|
||||
});
|
||||
response.end(page);
|
||||
});
|
||||
await new Promise<void>((resolve) => {
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("XHTML fixture server did not bind a TCP port");
|
||||
const origin = `http://127.0.0.1:${String(address.port)}`;
|
||||
const pageUrl = `${origin}/page.xhtml`;
|
||||
let stderr = "";
|
||||
const child = processes.spawn(executable, [
|
||||
"--headless=new",
|
||||
...(process.env.REA_BROWSER_NO_SANDBOX === "true"
|
||||
? ["--no-sandbox"]
|
||||
: []),
|
||||
"--remote-debugging-address=127.0.0.1",
|
||||
"--remote-debugging-port=0",
|
||||
`--user-data-dir=${profile}`,
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--disable-background-networking",
|
||||
"--disable-component-update",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-sync",
|
||||
"--metrics-recording-only",
|
||||
pageUrl,
|
||||
]);
|
||||
child.stdout.on("data", () => undefined);
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
if (stderr.length < 8_192) stderr += chunk.toString("utf8");
|
||||
});
|
||||
try {
|
||||
const port = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable,
|
||||
activePortPath: join(profile, "DevToolsActivePort"),
|
||||
stderr: () => stderr,
|
||||
timeoutMs: CHROME_STARTUP_TIMEOUT_MS,
|
||||
});
|
||||
const endpoint = `http://127.0.0.1:${String(port)}`;
|
||||
const provider = new CdpBrowserProvider();
|
||||
const targetId = await pageTarget(provider, endpoint, origin, pageUrl);
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
target_id: targetId,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const urls = result.value.metadata.dom_urls;
|
||||
for (const name of nodeNames) {
|
||||
expect(
|
||||
result.value.dom.nodes.some((node) => node.node_name === name),
|
||||
).toBe(true);
|
||||
}
|
||||
expect(
|
||||
result.value.dom.nodes.some(
|
||||
(node) =>
|
||||
node.node_name === link.name &&
|
||||
node.attribute_names.includes(link.attribute),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(urls).toEqual(
|
||||
destinations.map((destination) =>
|
||||
expect.objectContaining({
|
||||
attribute: "href",
|
||||
url:
|
||||
destination === null
|
||||
? null
|
||||
: destination === ""
|
||||
? pageUrl
|
||||
: `${origin}${destination}`,
|
||||
destination_scope:
|
||||
destination === null ? "outside_policy" : "approved",
|
||||
}),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
child.kill("SIGTERM");
|
||||
if (!(await waitForExit(child, 2_000))) child.kill("SIGKILL");
|
||||
await waitForExit(child, 2_000);
|
||||
await new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
}
|
||||
},
|
||||
CHROME_TEST_TIMEOUT_MS,
|
||||
);
|
||||
}
|
||||
|
||||
const pageTarget = async (
|
||||
provider: CdpBrowserProvider,
|
||||
endpoint: string,
|
||||
origin: string,
|
||||
pageUrl: string,
|
||||
): Promise<string> => {
|
||||
const deadline = Date.now() + 10_000;
|
||||
while (Date.now() < deadline) {
|
||||
const listed = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
const match = listed.value.targets.find((target) =>
|
||||
target.url.startsWith(pageUrl),
|
||||
);
|
||||
if (match !== undefined) return match.target_id;
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error("Headless Chrome did not expose the SVG fixture page");
|
||||
};
|
||||
@@ -188,6 +188,107 @@ describe("runtime window and producer granularity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("joins a reordered multi-script coverage sample by identity and preserves unavailable bounds", async () => {
|
||||
const texts = new Map(
|
||||
Array.from({ length: 256 }, (_, index) => [
|
||||
`script-${index}`,
|
||||
`// 🔥\r\n${" ".repeat(index)}function f(){return ${index};}`,
|
||||
]),
|
||||
);
|
||||
const { browser, provider, execution } = await fixture({
|
||||
commandEvents: (command, origin) =>
|
||||
command.method === "Debugger.enable"
|
||||
? [...texts.keys(), "foreign-script"].map((scriptId) => ({
|
||||
...(command.sessionId === undefined
|
||||
? {}
|
||||
: { sessionId: command.sessionId }),
|
||||
method: "Debugger.scriptParsed",
|
||||
params: {
|
||||
scriptId,
|
||||
url: `${origin}/shared.js`,
|
||||
executionContextId: scriptId === "foreign-script" ? 99 : 1,
|
||||
startLine: 0,
|
||||
startColumn: 0,
|
||||
endLine: 1,
|
||||
endColumn: 0,
|
||||
},
|
||||
}))
|
||||
: undefined,
|
||||
commandError: (command) =>
|
||||
command.method === "Debugger.getScriptSource" &&
|
||||
command.params.scriptId === "script-128"
|
||||
? { code: -32000, message: "Selected source is unavailable" }
|
||||
: undefined,
|
||||
commandResult: (command, origin) => {
|
||||
if (command.method === "Debugger.getScriptSource")
|
||||
return { scriptSource: texts.get(String(command.params.scriptId)) };
|
||||
if (command.method !== "Profiler.takePreciseCoverage") return undefined;
|
||||
return {
|
||||
timestamp: 13,
|
||||
result: [...texts]
|
||||
.reverse()
|
||||
.map(([scriptId, text]) => ({
|
||||
scriptId,
|
||||
url: `${origin}/shared.js`,
|
||||
functions: [
|
||||
{
|
||||
functionName: "f",
|
||||
isBlockCoverage: true,
|
||||
ranges: [
|
||||
{ startOffset: 0, endOffset: text.length, count: 1 },
|
||||
{ startOffset: 8, endOffset: 9, count: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}))
|
||||
.concat([
|
||||
{
|
||||
scriptId: "foreign-script",
|
||||
url: `${origin}/shared.js`,
|
||||
functions: [],
|
||||
},
|
||||
]),
|
||||
};
|
||||
},
|
||||
});
|
||||
const result = await provider.observeExecution(execution);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.coverage.excluded_scripts).toBe(1);
|
||||
expect(
|
||||
result.value.coverage.scripts.map(({ script_id }) => script_id),
|
||||
).toEqual([...texts.keys()].reverse());
|
||||
for (const script of result.value.coverage.scripts) {
|
||||
expect(script.functions[0]?.ranges).toEqual([
|
||||
{
|
||||
start_offset: 0,
|
||||
end_offset: texts.get(script.script_id)?.length,
|
||||
count: 1,
|
||||
source_bounds:
|
||||
script.script_id === "script-128" ? "unknown" : "verified",
|
||||
},
|
||||
{
|
||||
start_offset: 8,
|
||||
end_offset: 9,
|
||||
count: 0,
|
||||
source_bounds:
|
||||
script.script_id === "script-128" ? "unknown" : "verified",
|
||||
},
|
||||
]);
|
||||
}
|
||||
expect(
|
||||
result.value.sources.find(({ script_id }) => script_id === "script-128")
|
||||
?.source,
|
||||
).toMatchObject({ state: "unavailable" });
|
||||
expect(
|
||||
browser.commands.some(
|
||||
({ method }) => method === "Profiler.stopPreciseCoverage",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
browser.commands.some(({ method }) => method === "Target.detachFromTarget"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
describe("runtime source and listener identity", () => {
|
||||
it("retains same-URL script identities, UTF-16 bounds, nested zero counts and actual cleanup", async () => {
|
||||
const { browser, provider, execution } = await fixture();
|
||||
|
||||
@@ -5,6 +5,59 @@ import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution
|
||||
import { inspectWebEventListenersInputSchema } from "../../../src/domain/webEventListeners.js";
|
||||
import { startRuntimeBrowser } from "../../fixtures/webRuntime.js";
|
||||
|
||||
it("invalidates retained sources when their execution context is reused during another source read", async () => {
|
||||
let emit: ((event: CdpEvent) => void) | undefined;
|
||||
const browser = await startRuntimeBrowser({
|
||||
commandResult: (command, origin) => {
|
||||
if (
|
||||
command.method === "Debugger.getScriptSource" &&
|
||||
command.params.scriptId === "script-b"
|
||||
)
|
||||
emit?.({
|
||||
sessionId: "session-1",
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: {
|
||||
context: {
|
||||
id: 1,
|
||||
uniqueId: "replacement-context",
|
||||
origin,
|
||||
name: "",
|
||||
auxData: {
|
||||
frameId: "runtime-main",
|
||||
isDefault: true,
|
||||
type: "default",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
emit = browser.emitEvent;
|
||||
onTestFinished(() => browser.close());
|
||||
const result = await new CdpWebRuntimeProvider().observeExecution(
|
||||
observeWebExecutionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 5,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.coverage.scripts).toEqual([]);
|
||||
expect(result.value.coverage.excluded_scripts).toBe(3);
|
||||
expect(result.value.script_inventory.main_document_scripts).toBe(0);
|
||||
for (const scriptId of ["script-a", "script-b"])
|
||||
expect(
|
||||
result.value.sources.find(({ script_id }) => script_id === scriptId),
|
||||
).toMatchObject({ frame_id: null, source: { state: "excluded" } });
|
||||
expect(browser.commands.map(({ method }) => method)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"Profiler.stopPreciseCoverage",
|
||||
"Target.detachFromTarget",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each(
|
||||
["listeners", "execution"].flatMap((operation) =>
|
||||
["source_read", "other_source_read", "final_assertion"].map((phase) => ({
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
it.each(["omitted", "null"] as const)(
|
||||
"excludes TargetInfo workers with %s required attached state",
|
||||
async (attachmentState) => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: (command, origin) => {
|
||||
if (command.method !== "Target.getTargets") return undefined;
|
||||
return {
|
||||
targetInfos: [
|
||||
{
|
||||
targetId: "worker-1",
|
||||
type: "service_worker",
|
||||
url: `${origin}/worker.js`,
|
||||
openerId: "allowed-page",
|
||||
...(attachmentState === "null" ? { attached: null } : {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
try {
|
||||
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.workers).toEqual([]);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "workers",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -2,8 +2,10 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
rm,
|
||||
symlink,
|
||||
truncate,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
@@ -11,6 +13,7 @@ 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 { MitmproxyCaptureAdapter } from "../../../src/browser/history/MitmproxyCaptureAdapter.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "../../../src/browser/history/CaptureRelease.js";
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
@@ -20,6 +23,41 @@ import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
|
||||
const linux = it.skipIf(process.platform !== "linux");
|
||||
|
||||
linux("refuses a directory configured as the mitmdump executable", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-mitmdump-command-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const command = join(root, "mitmdump");
|
||||
await mkdir(command);
|
||||
|
||||
await expect(
|
||||
new MitmproxyCaptureAdapter({ REA_MITMDUMP_COMMAND: command }).command(
|
||||
join(root, "request.json"),
|
||||
join(root, "runtime"),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining(command),
|
||||
});
|
||||
});
|
||||
|
||||
linux("allows a symlink to a regular mitmdump executable", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-mitmdump-command-symlink-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const command = join(root, "mitmdump");
|
||||
const target = join(root, "mitmdump-bin");
|
||||
await writeFile(target, "#!/bin/sh\n", { mode: 0o700 });
|
||||
await symlink(target, command);
|
||||
|
||||
await expect(
|
||||
new MitmproxyCaptureAdapter({ REA_MITMDUMP_COMMAND: command }).command(
|
||||
join(root, "request.json"),
|
||||
join(root, "runtime"),
|
||||
),
|
||||
).resolves.toMatchObject({ command });
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"binds decoder replies to the complete selected provider identity (matching name: %s)",
|
||||
async (matching) => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import type { WebPageInspection } from "../../../src/domain/browserObservationSchemas.js";
|
||||
import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";
|
||||
import {
|
||||
compareWebCapturesInputSchema,
|
||||
@@ -126,6 +127,410 @@ describe("web capture diff", () => {
|
||||
expect(result.dimensions.dom_structure.status).toBe("unknown");
|
||||
expect(result.dimensions.dom_structure.reason).toContain("incomplete");
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture WebSocket comparison", () => {
|
||||
it("compares complete ordered WebSocket streams by source URL, not request IDs", async () => {
|
||||
const browser = await startFakeCdpBrowser({ binaryWebSocketEvent: true });
|
||||
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,
|
||||
include_websocket_shapes: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const before = structuredClone(captured.value);
|
||||
markSectionsComplete(before, [
|
||||
"network_requests",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
"websocket_shapes",
|
||||
]);
|
||||
expect(before.network.websocket_connections).toHaveLength(1);
|
||||
expect(before.network.websocket_connections[0]?.url).toBe(
|
||||
`ws://${new URL(browser.allowedOrigin).host}/live?token=websocket-url-secret`,
|
||||
);
|
||||
expect(before.network.websocket_connections[0]?.events).toHaveLength(2);
|
||||
|
||||
const idOnlyChange = structuredClone(before);
|
||||
const idOnlyConnection = idOnlyChange.network.websocket_connections[0];
|
||||
if (idOnlyConnection === undefined)
|
||||
throw new Error("Missing captured WebSocket connection");
|
||||
idOnlyConnection.request_id = "capture-local-id-2";
|
||||
expect(compareNetwork(before, idOnlyChange)).toMatchObject({
|
||||
status: "unchanged",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const changeFrame = (
|
||||
update: (
|
||||
event: WebPageInspection["network"]["websocket_connections"][number]["events"][number],
|
||||
) => void,
|
||||
): WebPageInspection => {
|
||||
const changed = structuredClone(before);
|
||||
const event = changed.network.websocket_connections[0]?.events[0];
|
||||
if (event === undefined)
|
||||
throw new Error("Missing captured WebSocket frame");
|
||||
update(event);
|
||||
return changed;
|
||||
};
|
||||
const eventChanges: readonly ((
|
||||
event: WebPageInspection["network"]["websocket_connections"][number]["events"][number],
|
||||
) => void)[] = [
|
||||
(event) => {
|
||||
event.direction = "received";
|
||||
},
|
||||
(event) => {
|
||||
event.opcode = 2;
|
||||
},
|
||||
(event) => {
|
||||
event.payload_shape = { format: "binary", json_shape: null };
|
||||
},
|
||||
];
|
||||
for (const update of eventChanges)
|
||||
expect(compareNetwork(before, changeFrame(update)).status).toBe(
|
||||
"changed",
|
||||
);
|
||||
|
||||
const changed = structuredClone(before);
|
||||
const connection = changed.network.websocket_connections[0];
|
||||
const event = connection?.events[0];
|
||||
if (connection === undefined || event === undefined)
|
||||
throw new Error("Missing captured WebSocket frame");
|
||||
if (event.payload_bytes === null)
|
||||
throw new Error("Expected captured WebSocket byte count");
|
||||
connection.request_id = "capture-local-id-3";
|
||||
event.direction = "received";
|
||||
event.opcode = 2;
|
||||
event.payload_bytes += 1;
|
||||
event.payload_shape = { format: "binary", json_shape: null };
|
||||
expect(compareNetwork(before, changed)).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
|
||||
const reordered = structuredClone(before);
|
||||
reordered.network.websocket_connections[0]?.events.reverse();
|
||||
expect(compareNetwork(before, reordered)).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
|
||||
const addedEmptyConnection = structuredClone(before);
|
||||
addedEmptyConnection.network.websocket_connections.push({
|
||||
request_id: "new-empty-connection",
|
||||
url: before.network.websocket_connections[0]!.url,
|
||||
events: [],
|
||||
});
|
||||
expect(compareNetwork(before, addedEmptyConnection)).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture WebSocket shape comparison", () => {
|
||||
it("aligns WebSocket shape streams only through common known coverage", async () => {
|
||||
const browser = await startFakeCdpBrowser({ binaryWebSocketEvent: true });
|
||||
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,
|
||||
include_websocket_shapes: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const before = structuredClone(captured.value);
|
||||
markSectionsComplete(before, [
|
||||
"network_requests",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
"websocket_shapes",
|
||||
]);
|
||||
|
||||
const sameUrlStreams = structuredClone(before);
|
||||
sameUrlStreams.network.websocket_connections.push({
|
||||
...structuredClone(sameUrlStreams.network.websocket_connections[0]!),
|
||||
request_id: "second-local-id",
|
||||
});
|
||||
const reorderedConnections = structuredClone(sameUrlStreams);
|
||||
reorderedConnections.network.websocket_connections.reverse();
|
||||
for (const [
|
||||
index,
|
||||
item,
|
||||
] of reorderedConnections.network.websocket_connections.entries())
|
||||
item.request_id = `new-local-id-${String(index)}`;
|
||||
expect(compareNetwork(sameUrlStreams, reorderedConnections)).toMatchObject({
|
||||
status: "unchanged",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const correlatedBefore = structuredClone(before);
|
||||
const correlatedConnection =
|
||||
correlatedBefore.network.websocket_connections[0]!;
|
||||
const shape = (root_type: "string" | "number") => ({
|
||||
format: "json" as const,
|
||||
json_shape: {
|
||||
root_type,
|
||||
node_count: 1,
|
||||
max_depth_observed: 0,
|
||||
properties: [],
|
||||
},
|
||||
});
|
||||
const firstShape = shape("string");
|
||||
const secondShape = shape("number");
|
||||
for (const connection of [
|
||||
correlatedConnection,
|
||||
{
|
||||
...structuredClone(correlatedConnection),
|
||||
request_id: "second-correlated-connection",
|
||||
},
|
||||
]) {
|
||||
connection.events[0]!.payload_shape = structuredClone(firstShape);
|
||||
connection.events[1]!.payload_shape = structuredClone(secondShape);
|
||||
}
|
||||
correlatedBefore.network.websocket_connections = [
|
||||
correlatedConnection,
|
||||
{
|
||||
...structuredClone(correlatedConnection),
|
||||
request_id: "second-correlated-connection",
|
||||
},
|
||||
];
|
||||
const crossed = structuredClone(correlatedBefore);
|
||||
crossed.network.websocket_connections[0]!.events[1]!.payload_shape =
|
||||
structuredClone(firstShape);
|
||||
crossed.network.websocket_connections[1]!.events[0]!.payload_shape =
|
||||
structuredClone(secondShape);
|
||||
crossed.network.websocket_connections[1]!.events[1]!.payload_shape =
|
||||
structuredClone(firstShape);
|
||||
expect(compareNetwork(correlatedBefore, crossed).status).toBe("changed");
|
||||
|
||||
const partialShapes = structuredClone(correlatedBefore);
|
||||
partialShapes.network.websocket_connections[0]!.events[1]!.payload_shape =
|
||||
null;
|
||||
const ambiguousShapeChange = structuredClone(partialShapes);
|
||||
ambiguousShapeChange.network.websocket_connections[1]!.events[1]!.payload_shape =
|
||||
structuredClone(firstShape);
|
||||
expect(compareNetwork(partialShapes, ambiguousShapeChange)).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
changes: [],
|
||||
});
|
||||
const changedKnownShape = structuredClone(partialShapes);
|
||||
changedKnownShape.network.websocket_connections[0]!.events[0]!.payload_shape =
|
||||
structuredClone(secondShape);
|
||||
expect(compareNetwork(partialShapes, changedKnownShape).status).toBe(
|
||||
"changed",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture WebSocket shape coverage", () => {
|
||||
it("keeps unchanged unknown when selected WebSocket shapes are unavailable", 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,
|
||||
include_websocket_shapes: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const unavailable = structuredClone(captured.value);
|
||||
markSectionsComplete(unavailable, [
|
||||
"network_requests",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
]);
|
||||
unavailable.completeness.unavailable_sections.push("websocket_shapes");
|
||||
for (const connection of unavailable.network.websocket_connections)
|
||||
for (const event of connection.events) event.payload_shape = null;
|
||||
expect(
|
||||
compareNetwork(unavailable, structuredClone(unavailable)),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
changes: [],
|
||||
});
|
||||
|
||||
const observed = structuredClone(unavailable);
|
||||
for (const connection of observed.network.websocket_connections)
|
||||
for (const event of connection.events)
|
||||
event.payload_shape = { format: "binary", json_shape: null };
|
||||
for (const [left, right] of [
|
||||
[unavailable, observed],
|
||||
[observed, unavailable],
|
||||
] as const)
|
||||
expect(compareNetwork(left, right)).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
changes: [],
|
||||
});
|
||||
|
||||
const metadataChanged = structuredClone(observed);
|
||||
metadataChanged.network.websocket_connections[0]!.events[0]!.opcode = 2;
|
||||
expect(compareNetwork(unavailable, metadataChanged).status).toBe("changed");
|
||||
|
||||
const truncated = structuredClone(observed);
|
||||
truncated.network.websocket_connections[0]!.events[0]!.payload_shape = null;
|
||||
truncated.completeness.truncated_sections.push("websocket_shapes");
|
||||
for (const [left, right] of [
|
||||
[truncated, observed],
|
||||
[observed, truncated],
|
||||
] as const)
|
||||
expect(compareNetwork(left, right)).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
changes: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture WebSocket payload byte coverage", () => {
|
||||
it("keeps unknown byte counts out of differences while comparing known metadata", async () => {
|
||||
const browser = await startFakeCdpBrowser({ binaryWebSocketEvent: true });
|
||||
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 known = structuredClone(captured.value);
|
||||
markSectionsComplete(known, [
|
||||
"network_requests",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
]);
|
||||
const unknownBytes = structuredClone(known);
|
||||
unknownBytes.network.websocket_connections[0]!.events[1]!.payload_bytes =
|
||||
null;
|
||||
for (const [left, right] of [
|
||||
[unknownBytes, known],
|
||||
[known, unknownBytes],
|
||||
] as const)
|
||||
expect(compareNetwork(left, right)).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
changes: [],
|
||||
});
|
||||
|
||||
const knownMetadataChanged = structuredClone(unknownBytes);
|
||||
knownMetadataChanged.network.websocket_connections[0]!.events[1]!.direction =
|
||||
"sent";
|
||||
expect(compareNetwork(unknownBytes, knownMetadataChanged).status).toBe(
|
||||
"changed",
|
||||
);
|
||||
|
||||
const knownBytesChanged = structuredClone(known);
|
||||
const knownBytesEvent =
|
||||
knownBytesChanged.network.websocket_connections[0]!.events[1]!;
|
||||
if (knownBytesEvent.payload_bytes === null)
|
||||
throw new Error("Expected captured WebSocket byte count");
|
||||
knownBytesEvent.payload_bytes += 1;
|
||||
expect(compareNetwork(known, knownBytesChanged).status).toBe("changed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture diff", () => {
|
||||
it("treats unavailable HTTP response facts as unknown while retaining observed changes", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const before = structuredClone(captured.value);
|
||||
const request = before.network.requests[0];
|
||||
if (request === undefined) throw new Error("Missing network request");
|
||||
request.status = null;
|
||||
request.mime_type = null;
|
||||
request.encoded_data_length = null;
|
||||
markSectionsComplete(before, [
|
||||
"network_requests",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
"json_body_shapes",
|
||||
]);
|
||||
for (const item of before.network.requests)
|
||||
item.body_shapes.status = "not_approved";
|
||||
|
||||
const after = structuredClone(before);
|
||||
const responseObserved = after.network.requests[0];
|
||||
if (responseObserved === undefined)
|
||||
throw new Error("Missing network request");
|
||||
responseObserved.status = 200;
|
||||
responseObserved.mime_type = "application/json";
|
||||
responseObserved.encoded_data_length = 100;
|
||||
expect(compareNetwork(before, after)).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
changes: [],
|
||||
});
|
||||
expect(compareNetwork(after, before)).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
expect(compareNetwork(before, before).status).toBe("unknown");
|
||||
|
||||
for (const field of [
|
||||
"status",
|
||||
"mime_type",
|
||||
"encoded_data_length",
|
||||
] as const) {
|
||||
const partial = structuredClone(after);
|
||||
partial.network.requests[0]![field] = null;
|
||||
expect(compareNetwork(partial, after).status).toBe("unknown");
|
||||
expect(compareNetwork(after, partial).status).toBe("unknown");
|
||||
}
|
||||
|
||||
const inventoryBefore = structuredClone(before);
|
||||
inventoryBefore.network.requests = [];
|
||||
expect(compareNetwork(inventoryBefore, before)).toMatchObject({
|
||||
status: "changed",
|
||||
total_changes: 1,
|
||||
changes: [expect.objectContaining({ change: "added" })],
|
||||
});
|
||||
|
||||
const statusChanged = structuredClone(after);
|
||||
statusChanged.network.requests[0]!.status = 500;
|
||||
expect(compareNetwork(after, statusChanged)).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
after.network.requests[0]!.encoded_data_length = null;
|
||||
expect(compareNetwork(after, statusChanged).status).toBe("changed");
|
||||
|
||||
const repeated = structuredClone(statusChanged);
|
||||
const duplicate = structuredClone(repeated.network.requests[0]!);
|
||||
duplicate.status = 200;
|
||||
duplicate.mime_type = "text/plain";
|
||||
repeated.network.requests.push(duplicate);
|
||||
const reassociated = structuredClone(repeated);
|
||||
reassociated.network.requests[0]!.mime_type = "text/plain";
|
||||
reassociated.network.requests.at(-1)!.mime_type = "application/json";
|
||||
expect(compareNetwork(repeated, reassociated).status).toBe("changed");
|
||||
repeated.network.requests[0]!.status = null;
|
||||
expect(compareNetwork(repeated, reassociated).status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("ignores transient request IDs and capture-approval state", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
@@ -194,7 +599,11 @@ describe("web capture redirect comparison", () => {
|
||||
redirect_event_timestamp: 2,
|
||||
},
|
||||
];
|
||||
markSectionsComplete(before, ["network_requests"]);
|
||||
markSectionsComplete(before, [
|
||||
"network_requests",
|
||||
"websocket_connections",
|
||||
"websocket_frames",
|
||||
]);
|
||||
|
||||
const after = structuredClone(before);
|
||||
const afterRequest = after.network.requests[0];
|
||||
@@ -496,3 +905,11 @@ const markSectionsComplete = (
|
||||
(section) => !completed.has(section),
|
||||
);
|
||||
};
|
||||
|
||||
const compareNetwork = (before: WebPageInspection, after: WebPageInspection) =>
|
||||
compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: before },
|
||||
after: { inspection: after },
|
||||
}),
|
||||
).dimensions.network;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createServer } from "node:http";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -28,27 +29,117 @@ const expectInvalidIncludedSourceMaps = (result: WebSourceMaps): void => {
|
||||
expectInvalidSourceMaps({ ...result, status: "unavailable" });
|
||||
};
|
||||
|
||||
it("parses ECMA-426 HTTP source-map prefixes while retaining exact response evidence", async () => {
|
||||
const map = JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["src/main.ts"],
|
||||
sourcesContent: ["import './dependency.ts';"],
|
||||
mappings: "AAAA",
|
||||
});
|
||||
const prefix = ")]}'transport prefix";
|
||||
const texts = [
|
||||
map,
|
||||
`\uFEFF${prefix}\n${map}`,
|
||||
`${prefix}\n${map}`,
|
||||
`${prefix}\r\n${map}`,
|
||||
`${prefix}\r${map}`,
|
||||
`${prefix}${map}`,
|
||||
`${prefix}\n{`,
|
||||
];
|
||||
const server = createServer((incoming, response) => {
|
||||
const index = Number(incoming.url?.slice(1));
|
||||
response.setHeader("content-type", "application/source-map+json");
|
||||
response.end(texts[index]);
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new TypeError("Expected a TCP listener address");
|
||||
const localOrigin = `http://127.0.0.1:${String(address.port)}`;
|
||||
const result = await fetchWebSourceMaps(
|
||||
texts.map((_, index) => ({
|
||||
...request,
|
||||
fetchUrl: `${localOrigin}/${index}`,
|
||||
declaredUrl: `${localOrigin}/${index}`,
|
||||
})),
|
||||
input({ allowed_origins: [localOrigin] }),
|
||||
);
|
||||
expect(result.items.map(({ status }) => status)).toEqual([
|
||||
"included",
|
||||
"included",
|
||||
"included",
|
||||
"included",
|
||||
"included",
|
||||
"invalid",
|
||||
"invalid",
|
||||
]);
|
||||
for (const [index, text] of texts.slice(0, 5).entries())
|
||||
expect(result.items[index]).toMatchObject({
|
||||
artifact: {
|
||||
text,
|
||||
bytes: Buffer.byteLength(text),
|
||||
sha256: createHash("sha256").update(text).digest("hex"),
|
||||
},
|
||||
original_sources: [{ source: `${localOrigin}/src/main.ts` }],
|
||||
mappings: [
|
||||
{
|
||||
generated_line: 1,
|
||||
generated_column: 0,
|
||||
source: `${localOrigin}/src/main.ts`,
|
||||
original_line: 1,
|
||||
original_column: 0,
|
||||
},
|
||||
],
|
||||
original_module_edges: [
|
||||
{
|
||||
from_source: `${localOrigin}/src/main.ts`,
|
||||
specifier: "./dependency.ts",
|
||||
resolved_source: `${localOrigin}/src/dependency.ts`,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.items.slice(5)).toMatchObject([
|
||||
{ artifact: null, mappings: [], original_sources: [] },
|
||||
{ artifact: null, mappings: [], original_sources: [] },
|
||||
]);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
if (server.listening)
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) =>
|
||||
error === undefined ? resolve() : reject(error),
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("source-map redirect URL resolution", () => {
|
||||
it.each(["/maps/current", "/assets/v2/app.js.map"])(
|
||||
const deliveredPath =
|
||||
"/assets/v2/app.js.map?revision=2&token=public-selection";
|
||||
it.each(["/maps/current", deliveredPath])(
|
||||
"resolves relative sources against the delivered map at %s",
|
||||
async (initialPath) => {
|
||||
const calls: string[] = [];
|
||||
const text = JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["../src/main.ts"],
|
||||
sourcesContent: ["import './dependency.ts';"],
|
||||
mappings: "AAAA",
|
||||
});
|
||||
const server = createServer((incoming, response) => {
|
||||
calls.push(incoming.url ?? "");
|
||||
if (incoming.url === "/maps/current") {
|
||||
response.writeHead(302, { location: "/assets/v2/app.js.map" }).end();
|
||||
response.writeHead(302, { location: deliveredPath }).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["../src/main.ts"],
|
||||
sourcesContent: ["import './dependency.ts';"],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
);
|
||||
response.end(text);
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -66,7 +157,7 @@ describe("source-map redirect URL resolution", () => {
|
||||
);
|
||||
expect(calls).toEqual(
|
||||
initialPath === "/maps/current"
|
||||
? [initialPath, "/assets/v2/app.js.map"]
|
||||
? [initialPath, deliveredPath]
|
||||
: [initialPath],
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
@@ -74,6 +165,12 @@ describe("source-map redirect URL resolution", () => {
|
||||
items: [
|
||||
{
|
||||
declared_url: declaredUrl,
|
||||
effective_url: `${localOrigin}${deliveredPath}`,
|
||||
artifact: {
|
||||
text,
|
||||
bytes: Buffer.byteLength(text),
|
||||
sha256: createHash("sha256").update(text).digest("hex"),
|
||||
},
|
||||
original_sources: [
|
||||
{ source: `${localOrigin}/assets/src/main.ts` },
|
||||
],
|
||||
@@ -98,6 +195,74 @@ describe("source-map redirect URL resolution", () => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
[404, "unavailable", "fetch_failed"],
|
||||
[200, "not-json", "invalid"],
|
||||
])(
|
||||
"retains the delivered URL when its HTTP %s response cannot supply a map",
|
||||
async (responseStatus, body, itemStatus) => {
|
||||
const effectiveUrl = `${origin}${deliveredPath}`;
|
||||
const calls: string[] = [];
|
||||
const result = await fetchWebSourceMaps([request], input(), undefined, {
|
||||
fetch: (url) => {
|
||||
calls.push(String(url));
|
||||
return Promise.resolve(
|
||||
calls.length === 1
|
||||
? new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: effectiveUrl },
|
||||
})
|
||||
: new Response(body, { status: responseStatus }),
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(calls).toEqual([request.fetchUrl, effectiveUrl]);
|
||||
expect(result.items[0]).toMatchObject({
|
||||
status: itemStatus,
|
||||
declared_url: request.declaredUrl,
|
||||
effective_url: effectiveUrl,
|
||||
artifact: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the last observed response URL when the next redirect fetch rejects", async () => {
|
||||
const nextUrl = `${origin}${deliveredPath}`;
|
||||
const calls: string[] = [];
|
||||
const result = await fetchWebSourceMaps([request], input(), undefined, {
|
||||
fetch: (url) => {
|
||||
calls.push(String(url));
|
||||
return calls.length === 1
|
||||
? Promise.resolve(
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: nextUrl },
|
||||
}),
|
||||
)
|
||||
: Promise.reject(new TypeError("fixture connection failed"));
|
||||
},
|
||||
});
|
||||
expect(calls).toEqual([request.fetchUrl, nextUrl]);
|
||||
expect(result.items[0]).toMatchObject({
|
||||
status: "fetch_failed",
|
||||
declared_url: request.declaredUrl,
|
||||
effective_url: request.fetchUrl,
|
||||
artifact: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an absent effective URL when the first fetch rejects", async () => {
|
||||
const result = await fetchWebSourceMaps([request], input(), undefined, {
|
||||
fetch: () => Promise.reject(new TypeError("fixture connection failed")),
|
||||
});
|
||||
expect(result.items[0]).toMatchObject({
|
||||
status: "fetch_failed",
|
||||
declared_url: request.declaredUrl,
|
||||
effective_url: null,
|
||||
artifact: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web source-map fetching and validation: fetching maps and following redirects", () => {
|
||||
@@ -185,7 +350,7 @@ describe("web source-map fetching and validation: fetching maps and following re
|
||||
expect(calls).toEqual([request.fetchUrl]);
|
||||
expect(result).toMatchObject({
|
||||
status: "unavailable",
|
||||
items: [{ status: "policy_filtered" }],
|
||||
items: [{ status: "policy_filtered", effective_url: request.fetchUrl }],
|
||||
});
|
||||
expectInvalidSourceMaps({
|
||||
...result,
|
||||
@@ -219,7 +384,7 @@ describe("web source-map fetching and validation: fetching maps and following re
|
||||
expect(calls).toEqual([]);
|
||||
expect(result).toMatchObject({
|
||||
status: "unavailable",
|
||||
items: [{ status: "policy_filtered" }],
|
||||
items: [{ status: "policy_filtered", effective_url: null }],
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -586,7 +751,7 @@ describe("web source-map sourcesContent validation", () => {
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
sources: ["source.ts"],
|
||||
sourcesContent: [null],
|
||||
sourcesContent: null,
|
||||
names: [],
|
||||
mappings: "",
|
||||
}),
|
||||
@@ -598,10 +763,61 @@ describe("web source-map sourcesContent validation", () => {
|
||||
expect(result.items[0]).toMatchObject({
|
||||
status: "included",
|
||||
original_sources: [
|
||||
{ source: `${origin}/assets/source.ts`, artifact: null },
|
||||
{
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source: `${origin}/assets/source.ts`,
|
||||
artifact: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unnamed source slots and mapping indices", async () => {
|
||||
const result = await fetchWebSourceMaps([request], input(), undefined, {
|
||||
fetch: () =>
|
||||
Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
sources: [null, "source.ts"],
|
||||
sourcesContent: ["unknown source text", "named source text"],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
expect(result.items[0]).toMatchObject({
|
||||
status: "partial",
|
||||
original_sources: [
|
||||
{
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source: null,
|
||||
artifact: { text: "unknown source text" },
|
||||
},
|
||||
{
|
||||
source_index: 1,
|
||||
declaration_index: 1,
|
||||
source: `${origin}/assets/source.ts`,
|
||||
artifact: { text: "named source text" },
|
||||
},
|
||||
],
|
||||
mappings: [
|
||||
{
|
||||
source_index: 1,
|
||||
declaration_index: 1,
|
||||
source: `${origin}/assets/source.ts`,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.items[0]?.limitation).toContain(
|
||||
"unnamed source at declaration 0",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("source-map original dependency syntax", () => {
|
||||
@@ -892,7 +1108,63 @@ describe("web source-map collection", () => {
|
||||
});
|
||||
|
||||
describe("source-map output admission", () => {
|
||||
it("admits a complete maximum-size map set when its real output fits", async () => {
|
||||
it.each([
|
||||
{ selectionMiB: 8, responseStatus: "invalid" },
|
||||
{ selectionMiB: 16, responseStatus: "invalid" },
|
||||
{ selectionMiB: 16, responseStatus: "included" },
|
||||
])(
|
||||
"accounts for JSON escaping in a $selectionMiB MiB effective URL for $responseStatus responses",
|
||||
async ({ selectionMiB, responseStatus }) => {
|
||||
const effectiveUrl = `${origin}/delivered.map?selection=${"\\".repeat(selectionMiB * 1_024 * 1_024)}`;
|
||||
const secondRequest = { ...request, scriptKey: `scr_${"2".repeat(64)}` };
|
||||
let calls = 0;
|
||||
const result = await fetchWebSourceMaps(
|
||||
[request, secondRequest],
|
||||
input(),
|
||||
undefined,
|
||||
{
|
||||
fetch: () => {
|
||||
calls += 1;
|
||||
return Promise.resolve(
|
||||
calls === 1
|
||||
? validMapResponse()
|
||||
: calls === 2
|
||||
? new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: effectiveUrl },
|
||||
})
|
||||
: responseStatus === "included"
|
||||
? validMapResponse()
|
||||
: new Response("not-json", { status: 200 }),
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(calls).toBe(3);
|
||||
expect(result).toMatchObject({
|
||||
status: "partial",
|
||||
requested: 2,
|
||||
processed: selectionMiB === 8 ? 2 : 1,
|
||||
});
|
||||
if (selectionMiB === 8) {
|
||||
expect(result.items[1]).toMatchObject({
|
||||
status: "invalid",
|
||||
declared_url: secondRequest.declaredUrl,
|
||||
});
|
||||
expect(result.items[1]?.effective_url === effectiveUrl).toBe(true);
|
||||
} else {
|
||||
expect(result.items).toHaveLength(1);
|
||||
expect(result.limitation).toContain("1 requested map");
|
||||
}
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
|
||||
32 * 1_024 * 1_024,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("source-map set output admission", () => {
|
||||
it("admits a maximum-size map set according to its serialized output size", async () => {
|
||||
const localOrigin = "http://127.0.0.1:9222";
|
||||
const mapUrl = `${localOrigin}/m`;
|
||||
const requests = Array.from({ length: 50_000 }, (_, index) => ({
|
||||
@@ -917,11 +1189,43 @@ describe("source-map output admission", () => {
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).toBe("included");
|
||||
expect(result.limitation).toBeUndefined();
|
||||
expect(result.items).toHaveLength(requests.length);
|
||||
const outputLimitBytes = 32 * 1_024 * 1_024;
|
||||
const itemSizes = new Set(
|
||||
result.items.map((item) => Buffer.byteLength(JSON.stringify(item))),
|
||||
);
|
||||
expect(itemSizes.size).toBe(1);
|
||||
const firstItem = result.items[0];
|
||||
if (firstItem === undefined) throw new Error("no source map was admitted");
|
||||
const itemBytes = Buffer.byteLength(JSON.stringify(firstItem));
|
||||
const completeEnvelope = JSON.stringify({
|
||||
...result,
|
||||
status: "included",
|
||||
processed: requests.length,
|
||||
items: [],
|
||||
limitation: undefined,
|
||||
});
|
||||
const projectedCompleteBytes =
|
||||
Buffer.byteLength(completeEnvelope) +
|
||||
itemBytes * requests.length +
|
||||
requests.length -
|
||||
1;
|
||||
const completeOutputFits = projectedCompleteBytes <= outputLimitBytes;
|
||||
|
||||
expect(result.status).toBe(completeOutputFits ? "included" : "partial");
|
||||
if (completeOutputFits) {
|
||||
expect(result.limitation).toBeUndefined();
|
||||
expect(result.items).toHaveLength(requests.length);
|
||||
} else {
|
||||
expect(result.items.length).toBeLessThan(requests.length);
|
||||
expect(result.limitation).toContain(
|
||||
`${String(requests.length - result.items.length)} requested maps`,
|
||||
);
|
||||
expect(projectedCompleteBytes).toBeGreaterThan(outputLimitBytes);
|
||||
}
|
||||
expect(result.processed).toBe(result.items.length);
|
||||
expect(result.requested).toBe(requests.length);
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
|
||||
32 * 1_024 * 1_024,
|
||||
outputLimitBytes,
|
||||
);
|
||||
}, 120_000);
|
||||
|
||||
|
||||
@@ -4,7 +4,11 @@ import { createServer } from "node:http";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { fetchWebSourceMaps } from "../../../src/browser/WebSourceMapFetcher.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
import {
|
||||
analyzeWebBundleInputSchema,
|
||||
webSourceMapsSchema,
|
||||
} from "../../../src/domain/webBundleAnalysis.js";
|
||||
import { WEB_SOURCE_MAP_LIMITS } from "../../../src/domain/webSourceLocation.js";
|
||||
|
||||
it.each([
|
||||
{ status: 300, followsRedirect: false },
|
||||
@@ -70,6 +74,10 @@ it.each([
|
||||
expect(result.items[0]?.status).toBe(
|
||||
followsRedirect ? "included" : "fetch_failed",
|
||||
);
|
||||
expect(result.items[0]).toMatchObject({
|
||||
declared_url: url,
|
||||
effective_url: followsRedirect ? `${origin}/delivered.map` : url,
|
||||
});
|
||||
if (!followsRedirect)
|
||||
expect(result.items[0]?.limitation).toBe(
|
||||
`Source-map server returned HTTP ${String(status)}.`,
|
||||
@@ -118,8 +126,184 @@ it("keeps the declared URL and reports malformed redirect Location evidence", as
|
||||
expect(result.items[0]).toMatchObject({
|
||||
status: "fetch_failed",
|
||||
declared_url: declaredUrl,
|
||||
effective_url: declaredUrl,
|
||||
limitation: expect.stringContaining("invalid Location URL"),
|
||||
});
|
||||
expect(result.items[0]?.limitation).toContain(declaredUrl);
|
||||
expect(result.items[0]?.limitation).toContain("http://[invalid");
|
||||
});
|
||||
|
||||
it.each(["invalid JSON", "invalid UTF-8", "HTTP failure", "response limit"])(
|
||||
"retains a redirected response URL for %s",
|
||||
async (failure) => {
|
||||
const origin = "https://app.example.test";
|
||||
const declaredUrl = `${origin}/declared.map`;
|
||||
const fetchedUrl = `${origin}/maps/current.map?token=source-value#fragment`;
|
||||
const result = await fetchWebSourceMaps(
|
||||
[{ scriptKey: "script", declaredUrl, fetchUrl: declaredUrl }],
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page",
|
||||
allowed_origins: [origin],
|
||||
fetch_source_maps: true,
|
||||
}),
|
||||
undefined,
|
||||
{
|
||||
...(failure === "response limit" ? { maxResponseBytes: 1 } : {}),
|
||||
fetch: (url) =>
|
||||
Promise.resolve(
|
||||
String(url) === declaredUrl
|
||||
? new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: fetchedUrl },
|
||||
})
|
||||
: new Response(
|
||||
failure === "invalid UTF-8"
|
||||
? Uint8Array.from([0xff])
|
||||
: "not-json",
|
||||
{ status: failure === "HTTP failure" ? 503 : 200 },
|
||||
),
|
||||
),
|
||||
},
|
||||
);
|
||||
expect(result.items[0]).toMatchObject({
|
||||
declared_url: declaredUrl,
|
||||
effective_url: fetchedUrl,
|
||||
status:
|
||||
failure === "invalid JSON" || failure === "invalid UTF-8"
|
||||
? "invalid"
|
||||
: "fetch_failed",
|
||||
artifact: null,
|
||||
});
|
||||
const item = result.items[0];
|
||||
if (item === undefined) throw new Error("Expected a fetched map result");
|
||||
const legacyItem = { ...item };
|
||||
delete legacyItem.effective_url;
|
||||
const legacy = webSourceMapsSchema.parse({
|
||||
...result,
|
||||
items: [legacyItem],
|
||||
});
|
||||
expect(legacy.items[0]).not.toHaveProperty("effective_url");
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ cancellationFails: false, reason: null },
|
||||
{ cancellationFails: true, reason: new Error("fixture cancel failure") },
|
||||
{ cancellationFails: true, reason: undefined },
|
||||
])(
|
||||
"reserves a fetched URL before reading an over-cap response; cancellation failure=$cancellationFails, reason=$reason",
|
||||
async ({ cancellationFails, reason }) => {
|
||||
const origin = "https://app.example.test";
|
||||
const fetchedUrl = `${origin}/${"u".repeat(WEB_SOURCE_MAP_LIMITS.outputBytes)}`;
|
||||
let cancelled = false;
|
||||
let read = false;
|
||||
const body = new ReadableStream<Uint8Array>(
|
||||
{
|
||||
pull(controller) {
|
||||
read = true;
|
||||
controller.enqueue(
|
||||
new TextEncoder().encode(
|
||||
'{"version":3,"sources":[],"names":[],"mappings":""}',
|
||||
),
|
||||
);
|
||||
controller.close();
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
if (cancellationFails) throw reason;
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
const pending = fetchWebSourceMaps(
|
||||
[
|
||||
{
|
||||
scriptKey: "script",
|
||||
declaredUrl: `${origin}/declared.map`,
|
||||
fetchUrl: fetchedUrl,
|
||||
},
|
||||
],
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page",
|
||||
allowed_origins: [origin],
|
||||
fetch_source_maps: true,
|
||||
}),
|
||||
undefined,
|
||||
{ fetch: () => Promise.resolve(new Response(body)) },
|
||||
);
|
||||
if (cancellationFails) {
|
||||
await expect(pending).rejects.toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
message: expect.stringContaining("Expanded source-map evidence"),
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: ["source-map-response"],
|
||||
cause: expect.objectContaining({
|
||||
errors: expect.arrayContaining([reason]),
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
status: "unavailable",
|
||||
requested: 1,
|
||||
processed: 0,
|
||||
items: [],
|
||||
limitation: expect.stringContaining("1 requested map"),
|
||||
});
|
||||
}
|
||||
expect(cancelled).toBe(true);
|
||||
expect(read).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("charges complete escaped redirect errors and cancels every discarded response", async () => {
|
||||
const origin = "https://app.example.test";
|
||||
const location = `http://[${'\\"'.repeat(3_000)}`;
|
||||
const request = {
|
||||
scriptKey: "script",
|
||||
declaredUrl: `${origin}/map`,
|
||||
fetchUrl: `${origin}/map`,
|
||||
};
|
||||
const input = analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page",
|
||||
allowed_origins: [origin],
|
||||
fetch_source_maps: true,
|
||||
});
|
||||
let calls = 0;
|
||||
let cancelled = 0;
|
||||
const host = {
|
||||
fetch: () => {
|
||||
calls += 1;
|
||||
return Promise.resolve(
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
cancel() {
|
||||
cancelled += 1;
|
||||
},
|
||||
}),
|
||||
{ status: 302, headers: { location } },
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
const control = await fetchWebSourceMaps([request], input, undefined, host);
|
||||
expect(control.items[0]?.limitation).toContain(JSON.stringify(location));
|
||||
expect(control.items[0]?.limitation?.length).toBeGreaterThan(512);
|
||||
const result = await fetchWebSourceMaps(
|
||||
Array.from({ length: 1_500 }, () => request),
|
||||
input,
|
||||
undefined,
|
||||
host,
|
||||
);
|
||||
expect(result).toMatchObject({ status: "unavailable", requested: 1_500 });
|
||||
expect(result.processed).toBe(result.items.length);
|
||||
expect(result.processed).toBeLessThan(result.requested);
|
||||
expect(result.limitation).toContain("unknown");
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
|
||||
WEB_SOURCE_MAP_LIMITS.outputBytes,
|
||||
);
|
||||
expect(calls).toBeLessThan(1_501);
|
||||
expect(cancelled).toBe(calls);
|
||||
});
|
||||
|
||||
@@ -345,7 +345,7 @@ it.each(cases)(
|
||||
item.mappings.map((entry) => [
|
||||
entry.generated_line,
|
||||
entry.generated_column,
|
||||
entry.source.replace(origin + "/", ""),
|
||||
entry.source?.replace(origin + "/", "") ?? null,
|
||||
]),
|
||||
).toEqual(expected);
|
||||
expect(item.artifact.sha256).toBe(
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { chmod, lstat, readFile } from "node:fs/promises";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import {
|
||||
expectConfigurationRefusal,
|
||||
serveCli as serve,
|
||||
} from "./cliServeHarness.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
it.each([
|
||||
[
|
||||
["inspect-adb-client", "--json"],
|
||||
"/nonexistent/adb",
|
||||
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
|
||||
],
|
||||
[
|
||||
["list-adb-devices", "--json"],
|
||||
"/nonexistent/adb",
|
||||
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
|
||||
],
|
||||
[
|
||||
["list-adb-devices", "--json"],
|
||||
"relative/adb",
|
||||
"REA_ADB_PATH must be an absolute path to the adb binary.",
|
||||
],
|
||||
])(
|
||||
"%j with REA_ADB_PATH=%s names the host requirement",
|
||||
async (argv, binary, reason) => {
|
||||
const result = await serve(argv, { REA_ADB_PATH: binary });
|
||||
expectConfigurationRefusal(result, reason);
|
||||
},
|
||||
);
|
||||
|
||||
it("validates device serials before contacting any device", async () => {
|
||||
const result = await serve(["inspect-adb-device", "bad serial", "--json"]);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires the output directory option on pull", async () => {
|
||||
const result = await serve([
|
||||
"pull-adb-package",
|
||||
"emulator-5554",
|
||||
"com.example",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"refuses a trailing device separator through the CLI before adb or output effects",
|
||||
async () => {
|
||||
const workspace = await createTestWorkspace("rea-adb-cli-pull-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const adb = await workspace.write(
|
||||
"adb",
|
||||
`#!/bin/sh
|
||||
if [ "$1" = "version" ]; then
|
||||
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\nInstalled as %s\\n' "$0"
|
||||
exit 0
|
||||
fi
|
||||
: > '${workspace.path("invoked")}'
|
||||
exit 0
|
||||
`,
|
||||
);
|
||||
await chmod(adb, 0o755);
|
||||
const output = workspace.path("pulls");
|
||||
const result = await serve(
|
||||
[
|
||||
"pull-adb-file",
|
||||
"emulator-5554",
|
||||
"/data/local/tmp/",
|
||||
"--output-directory",
|
||||
output,
|
||||
"--json",
|
||||
],
|
||||
{ REA_ADB_PATH: adb },
|
||||
);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
});
|
||||
await expect(readFile(workspace.path("invoked"))).rejects.toThrow();
|
||||
await expect(lstat(output)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
@@ -1,14 +1,186 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
import { analysisViewLayoutEvidence } from "../../fixtures/analysisView.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
analysisViewLayoutEvidence,
|
||||
analysisViewCaptureFixture,
|
||||
analysisViewCaptureEvidence,
|
||||
analysisViewObjectDenseCapture,
|
||||
} from "../../fixtures/analysisView.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
|
||||
|
||||
cliTest(
|
||||
"projects portable artifact inventory after the original ZIP is removed",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-inventory-view-cli-");
|
||||
const archive = join(root, "fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("main.js", new TextReader("console.log('portable');\n"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-artifact", archive, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode).toBe(0);
|
||||
const parent = parseEvidence(inspected.json);
|
||||
await unlink(archive);
|
||||
const request = join(root, "view.json");
|
||||
await writeFile(
|
||||
request,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: {
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: ["main.js"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const projected = await cli.run({
|
||||
arguments: ["inspect-analysis-view", request, "--json"],
|
||||
});
|
||||
expect(projected.exitCode).toBe(0);
|
||||
expect(projected.json).toMatchObject({
|
||||
operation: "inspect_analysis_view",
|
||||
evidence_links: [parent.evidence_id],
|
||||
normalized_result: {
|
||||
parent_evidence_id: parent.evidence_id,
|
||||
kind: "inventory",
|
||||
source_complete: true,
|
||||
artifact: { path: archive, sha256: parent.subject?.digest.sha256 },
|
||||
items: [expect.objectContaining({ logical_path: "main.js" })],
|
||||
coverage: { total: 1, exhausted: true, next_offset: null },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"admits portable captures before parsing and preserves capture caveats",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-inline-capture-cli-");
|
||||
const path = join(root, "view.json");
|
||||
const environment = {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
};
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
source: {
|
||||
kind: "inline",
|
||||
evidence: analysisViewCaptureEvidence(
|
||||
analysisViewObjectDenseCapture(),
|
||||
),
|
||||
},
|
||||
view: { kind: "api-surface" },
|
||||
}),
|
||||
);
|
||||
const refused = await cli.run({
|
||||
arguments: ["inspect-analysis-view", path, "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(refused.exitCode).toBe(1);
|
||||
expect(refused.json).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: { resource: "memory" },
|
||||
});
|
||||
|
||||
const capture = analysisViewCaptureFixture();
|
||||
capture.records = capture.records.slice(0, 1);
|
||||
capture.total_records = 1;
|
||||
const caveat = "Producer omitted exchanges before capture startup.";
|
||||
capture.limitations = [caveat, caveat];
|
||||
capture.records[0]!.reported = {
|
||||
request: { method: "GET", url: "https://api.test/a" },
|
||||
response: {
|
||||
status: 200,
|
||||
content: { mimeType: "\u000btext/plain\u000b" },
|
||||
},
|
||||
};
|
||||
const parent = analysisViewCaptureEvidence(capture);
|
||||
expect(parent.limitations).not.toContain(caveat);
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: { kind: "api-surface" },
|
||||
}),
|
||||
);
|
||||
const response = await cli.run({
|
||||
arguments: ["inspect-analysis-view", path, "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(response.exitCode, response.stdout).toBe(0);
|
||||
const result = parseEvidence(response.json);
|
||||
expect(result.limitations.filter((value) => value === caveat)).toEqual([
|
||||
caveat,
|
||||
]);
|
||||
expect(result.normalized_result).toMatchObject({
|
||||
groups: [{ content_types: [], flags: ["single-sample"] }],
|
||||
limitations: expect.arrayContaining([caveat]),
|
||||
unknowns: [
|
||||
"Some retained records have unavailable status or content type values.",
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discovers native records from a complete portable bundle using the shared workflow",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-discovery-cli-");
|
||||
const parent = createEvidence(
|
||||
{ path: "/fixtures/native.exe", format: "pe", sha256: "a".repeat(64) },
|
||||
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
|
||||
{
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
result: ghidraFunctionDossier(),
|
||||
},
|
||||
);
|
||||
const bundle = createEvidenceBundle([parent]);
|
||||
const path = join(root, "evidence.json");
|
||||
await writeFile(path, JSON.stringify(bundle));
|
||||
const options = {
|
||||
detail: "summary" as const,
|
||||
filters: { evidence_id: parent.evidence_id },
|
||||
};
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-evidence-bundle",
|
||||
JSON.stringify({ path, ...options }),
|
||||
"--json",
|
||||
],
|
||||
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const expected = inspectEvidenceBundle(bundle, options);
|
||||
if (!expected.ok) throw expected.error;
|
||||
expect(result.json).toEqual(expected.value);
|
||||
const complete = await cli.run({
|
||||
arguments: [
|
||||
"inspect-evidence-bundle",
|
||||
JSON.stringify({ path }),
|
||||
"--json",
|
||||
],
|
||||
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
|
||||
});
|
||||
expect(complete.exitCode).toBe(0);
|
||||
expect(complete.json).toEqual(bundle);
|
||||
},
|
||||
);
|
||||
cliTest(
|
||||
"projects one section from a JSON file of inline layout Evidence",
|
||||
async ({ cli }) => {
|
||||
@@ -169,3 +341,80 @@ for (const [view, reason] of [
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"decodes HAR credentials and projects recorded API paths through the compiled workflows",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-surface-cli-");
|
||||
const fixture = apiSurfaceHar();
|
||||
const entry = fixture.log.entries[0]!;
|
||||
const urls = [
|
||||
"https://user:password@api.example.test/a/%2e%2e/admin?token=ordinary#fragment",
|
||||
"https://api.example.test/admin",
|
||||
"https:user:password@api.example.test/path",
|
||||
"https:///user:password@api.example.test/path",
|
||||
];
|
||||
fixture.log.entries.push(
|
||||
...urls.map((url) => ({
|
||||
...entry,
|
||||
request: { ...entry.request, url },
|
||||
})),
|
||||
);
|
||||
const bytes = JSON.stringify(fixture);
|
||||
const capturePath = join(root, "capture.har");
|
||||
const input = join(root, "view.json");
|
||||
const environment = {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
};
|
||||
await writeFile(capturePath, bytes);
|
||||
const capture = await cli.run({
|
||||
arguments: ["inspect-web-network-capture", capturePath, "har", "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(capture.exitCode, capture.stdout).toBe(0);
|
||||
const parent = parseEvidence(capture.json);
|
||||
expect(parent.subject?.digest.sha256).toBe(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
);
|
||||
expect(JSON.stringify(parent)).not.toContain("password");
|
||||
await writeFile(
|
||||
input,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: { kind: "api-surface" },
|
||||
}),
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-analysis-view", input, "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(result.exitCode, result.stdout).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
confidence: "inferred",
|
||||
evidence_links: [parent.evidence_id],
|
||||
normalized_result: {
|
||||
kind: "api-surface",
|
||||
records: { examined: 17, total: 17, excluded: 2 },
|
||||
coverage: { total: 14, exhausted: true },
|
||||
groups: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path_template: "/a/%2e%2e/admin",
|
||||
record_ordinals: [13],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path_template: "/admin",
|
||||
record_ordinals: [14],
|
||||
}),
|
||||
]),
|
||||
excluded_records: [
|
||||
{ ordinal: 15, reason: "url-redacted" },
|
||||
{ ordinal: 16, reason: "url-redacted" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result.json)).not.toContain("password");
|
||||
expect(JSON.stringify(result.json)).not.toContain("ordinary");
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
expectConfigurationRefusal,
|
||||
serveCli as serve,
|
||||
} from "./cliServeHarness.js";
|
||||
|
||||
it.each([
|
||||
[
|
||||
["inspect-apktool-client", "--json"],
|
||||
"/nonexistent/apktool",
|
||||
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
|
||||
],
|
||||
[
|
||||
["decode-android-resources", "/targets/app.apk", "--json"],
|
||||
"/nonexistent/apktool",
|
||||
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
|
||||
],
|
||||
[
|
||||
["decode-android-resources", "/targets/app.apk", "--json"],
|
||||
"relative/apktool",
|
||||
"REA_APKTOOL_COMMAND must be an absolute path to the apktool launcher.",
|
||||
],
|
||||
])(
|
||||
"%j with REA_APKTOOL_COMMAND=%s names the host requirement",
|
||||
async (argv, command, reason) => {
|
||||
const result = await serve(argv, { REA_APKTOOL_COMMAND: command });
|
||||
expectConfigurationRefusal(result, reason);
|
||||
},
|
||||
);
|
||||
|
||||
it("validates the locale option before launching apktool", async () => {
|
||||
const result = await serve([
|
||||
"decode-android-resources",
|
||||
"/targets/app.apk",
|
||||
"--locale",
|
||||
"not a locale",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
{
|
||||
code: "invalid_format",
|
||||
path: "locale",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -97,6 +97,14 @@ describe("browser comparison JSON file inputs", () => {
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"reports malformed PNG chunks as invalid input and valid unsupported PNGs as unsupported targets",
|
||||
async () => {
|
||||
await assertPngInputErrorProjections();
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"identifies a missing capture file instead of reporting malformed JSON",
|
||||
async () => {
|
||||
@@ -123,3 +131,105 @@ describe("browser comparison JSON file inputs", () => {
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
const assertPngInputErrorProjections = async (): Promise<void> => {
|
||||
const damagedBytes = noisePng(1, 1);
|
||||
damagedBytes[29] = (damagedBytes[29] ?? 0) ^ 1;
|
||||
const damaged = JSON.stringify(createWebScreenshotArtifact(damagedBytes));
|
||||
expect(
|
||||
await runCli(["compare-web-screenshots", damaged, damaged, "--json"]),
|
||||
).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_screenshots",
|
||||
issues: [
|
||||
{ path: [], reason: "invalid_format", message: expect.any(String) },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(1, 0);
|
||||
header.writeUInt32BE(1, 4);
|
||||
header.set([8, 2, 0, 0, 0], 8);
|
||||
const malformedDeflate = JSON.stringify(
|
||||
createWebScreenshotArtifact(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk("IHDR", header),
|
||||
pngChunk("IDAT", Buffer.from("bad")),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await runCli([
|
||||
"compare-web-screenshots",
|
||||
malformedDeflate,
|
||||
malformedDeflate,
|
||||
"--json",
|
||||
]),
|
||||
).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_screenshots",
|
||||
issues: [{ path: [], reason: "invalid_format" }],
|
||||
},
|
||||
});
|
||||
|
||||
const grayscaleHeader = Buffer.alloc(13);
|
||||
grayscaleHeader.writeUInt32BE(1, 0);
|
||||
grayscaleHeader.writeUInt32BE(1, 4);
|
||||
grayscaleHeader.set([8, 0, 0, 0, 0], 8);
|
||||
const grayscale = JSON.stringify(
|
||||
createWebScreenshotArtifact(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk("IHDR", grayscaleHeader),
|
||||
pngChunk("IDAT", deflateSync(Buffer.from([0, 30]))),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await runCli(["compare-web-screenshots", grayscale, grayscale, "--json"]),
|
||||
).toMatchObject({
|
||||
code: "unsupported_target",
|
||||
details: { operation: "compare_web_screenshots" },
|
||||
});
|
||||
|
||||
const oversizedHeader = Buffer.alloc(13);
|
||||
oversizedHeader.writeUInt32BE(0x7fffffff, 0);
|
||||
oversizedHeader.writeUInt32BE(1, 4);
|
||||
oversizedHeader.set([8, 6, 0, 0, 0], 8);
|
||||
const hugeDimensions = JSON.stringify(
|
||||
createWebScreenshotArtifact(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk("IHDR", oversizedHeader),
|
||||
pngChunk("IDAT", deflateSync(Buffer.from([0]))),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await runCli([
|
||||
"compare-web-screenshots",
|
||||
hugeDimensions,
|
||||
hugeDimensions,
|
||||
"--json",
|
||||
]),
|
||||
).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
operation: "compare_web_screenshots",
|
||||
resource: "memory",
|
||||
reported_limits: {
|
||||
maximum_working_memory_bytes: 256 * 1024 * 1024,
|
||||
estimated_working_memory_bytes: "34359738499",
|
||||
before_dimensions: { width: 0x7fffffff, height: 1 },
|
||||
after_dimensions: { width: 0x7fffffff, height: 1 },
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { readdir } from "node:fs/promises";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest, createTestCli } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reuses an owned CLI compile cache and preserves a caller-selected cache",
|
||||
async ({ cli, cliCompileCache }) => {
|
||||
const cached = await cli.run({ arguments: ["--version"] });
|
||||
expect(cached.exitCode).toBe(0);
|
||||
expect(cached.stdout).toContain(PRODUCT_IDENTITY.packageVersion);
|
||||
expect(await readdir(cliCompileCache)).not.toHaveLength(0);
|
||||
|
||||
const selected = await createTestTempDirectory("rea-cli-selected-cache-");
|
||||
const overridden = await cli.run({
|
||||
arguments: ["--version"],
|
||||
environment: { NODE_COMPILE_CACHE: selected },
|
||||
});
|
||||
expect(overridden.exitCode).toBe(0);
|
||||
expect(overridden.stdout).toBe(cached.stdout);
|
||||
expect(await readdir(selected)).not.toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"collects requested child coverage without populating the fixture cache",
|
||||
async ({ processes }) => {
|
||||
const cache = await createTestTempDirectory("rea-cli-coverage-cache-");
|
||||
const coverage = await createTestTempDirectory("rea-cli-child-coverage-");
|
||||
const cli = createTestCli(processes, cache);
|
||||
const result = await cli.run({
|
||||
arguments: ["--version"],
|
||||
environment: { NODE_V8_COVERAGE: coverage },
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(PRODUCT_IDENTITY.packageVersion);
|
||||
expect(await readdir(cache)).toEqual([]);
|
||||
expect(
|
||||
(await readdir(coverage)).some((path) => path.endsWith(".json")),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest("preserves a caller's cold CLI launch", async ({ processes }) => {
|
||||
const cache = await createTestTempDirectory("rea-cli-disabled-cache-");
|
||||
const cli = createTestCli(processes, cache);
|
||||
const result = await cli.run({
|
||||
arguments: ["--version"],
|
||||
environment: { NODE_DISABLE_COMPILE_CACHE: "1" },
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(PRODUCT_IDENTITY.packageVersion);
|
||||
expect(await readdir(cache)).toEqual([]);
|
||||
});
|
||||
@@ -13,7 +13,7 @@ const registeredCommands: WeakMap<object, CommandMap> = Cli.toCommands;
|
||||
|
||||
const advertisedGroupSchema = z
|
||||
.object({
|
||||
properties: z.record(z.string(), z.unknown()).optional(),
|
||||
properties: z.record(z.string(), z.unknown()),
|
||||
required: z.array(z.string()).optional(),
|
||||
})
|
||||
.loose();
|
||||
@@ -70,8 +70,27 @@ describe("CLI advertised input schemas", () => {
|
||||
for (const command of createCliInventory(cli).primary) {
|
||||
const advertised = await advertisedSchema(cli, command);
|
||||
for (const group of INPUT_GROUPS) {
|
||||
const required = (advertised[group]?.required ?? []).toSorted();
|
||||
const rejected = omissionRejected(parserSchema(cli, command, group));
|
||||
const parser = parserSchema(cli, command, group);
|
||||
const advertisedGroup = advertised[group];
|
||||
if (parser === undefined) {
|
||||
if (advertisedGroup !== undefined)
|
||||
mismatches.push(`${command} ${group}: advertised without parser`);
|
||||
continue;
|
||||
}
|
||||
if (advertisedGroup === undefined) {
|
||||
mismatches.push(`${command} ${group}: parser group not advertised`);
|
||||
continue;
|
||||
}
|
||||
const parserProperties = Object.keys(parser.shape).toSorted();
|
||||
const advertisedProperties = Object.keys(
|
||||
advertisedGroup.properties,
|
||||
).toSorted();
|
||||
if (advertisedProperties.join() !== parserProperties.join())
|
||||
mismatches.push(
|
||||
`${command} ${group}: advertised properties [${advertisedProperties.join()}], parser properties [${parserProperties.join()}]`,
|
||||
);
|
||||
const required = (advertisedGroup.required ?? []).toSorted();
|
||||
const rejected = omissionRejected(parser);
|
||||
if (required.join() !== rejected.join())
|
||||
mismatches.push(
|
||||
`${command} ${group}: advertised [${required.join()}], parser rejects [${rejected.join()}]`,
|
||||
@@ -112,3 +131,73 @@ describe("CLI advertised input schemas", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("firmware CLI advertised input schema", () => {
|
||||
it("keeps limits and defaults from its shared input contract", async () => {
|
||||
const cli = createCli({});
|
||||
const advertised = await advertisedSchema(cli, "extract-firmware");
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const args = ajv.compile(advertised.args ?? {});
|
||||
const options = ajv.compile(advertised.options ?? {});
|
||||
|
||||
expect(args({ path: "firmware.bin", outputDirectory: "output" })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(args({ path: "", outputDirectory: "output" })).toBe(false);
|
||||
expect(args({ path: "firmware.bin", outputDirectory: "" })).toBe(false);
|
||||
expect(options({})).toBe(true);
|
||||
expect(options({ maxDepth: 0 })).toBe(false);
|
||||
expect(options({ maxDepth: 11 })).toBe(false);
|
||||
expect(options({ maxOutputBytes: 0 })).toBe(false);
|
||||
expect(options({ maxOutputBytes: 512 * 1024 * 1024 + 1 })).toBe(false);
|
||||
expect(options({ maxOutputFiles: 100_001 })).toBe(false);
|
||||
expect(advertised.options?.properties?.["maxDepth"]).toMatchObject({
|
||||
default: 3,
|
||||
});
|
||||
expect(advertised.options?.properties?.["maxOutputBytes"]).toMatchObject({
|
||||
default: 256 * 1024 * 1024,
|
||||
});
|
||||
expect(advertised.options?.properties?.["maxOutputFiles"]).toMatchObject({
|
||||
default: 10_000,
|
||||
});
|
||||
|
||||
const maxOffset = Number.MAX_SAFE_INTEGER;
|
||||
expect(options({ offset: maxOffset + 1 })).toBe(false);
|
||||
expect(options({ length: maxOffset + 1 })).toBe(false);
|
||||
|
||||
expect(
|
||||
parserSchema(cli, "extract-firmware", "options")?.parse({}),
|
||||
).toMatchObject({
|
||||
maxDepth: 3,
|
||||
maxOutputBytes: 256 * 1024 * 1024,
|
||||
maxOutputFiles: 10_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web module CLI advertised input schema", () => {
|
||||
it("advertises the shared path and URL constraints", async () => {
|
||||
const cli = createCli({});
|
||||
const advertised = await advertisedSchema(cli, "trace-web-module-imports");
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const args = ajv.compile(advertised.args ?? {});
|
||||
const options = ajv.compile(advertised.options ?? {});
|
||||
|
||||
expect(
|
||||
args({ manifestPath: resolve("manifest.json"), scriptIndex: 0 }),
|
||||
).toBe(true);
|
||||
expect(args({ manifestPath: "", scriptIndex: 0 })).toBe(false);
|
||||
expect(args({ manifestPath: "manifest\u0000.json", scriptIndex: 0 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(args({ manifestPath: "./manifest.json", scriptIndex: -1 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(options({})).toBe(true);
|
||||
expect(options({ importerUrl: "" })).toBe(false);
|
||||
expect(options({ importMapPath: "" })).toBe(false);
|
||||
expect(options({ importMapPath: "map\u0000.json" })).toBe(false);
|
||||
expect(options({ importMapBaseUrl: "" })).toBe(false);
|
||||
});
|
||||
});
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const level of ["loud", "INFO"])
|
||||
cliTest(
|
||||
`reports REA_LOG_LEVEL=${level} as invalid configuration`,
|
||||
async ({ cli }) => {
|
||||
for (const arguments_ of [["doctor", "--json"], ["--help"]]) {
|
||||
const result = await cli.run({
|
||||
arguments: arguments_,
|
||||
environment: { REA_LOG_LEVEL: level },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toBe("");
|
||||
expect(result.stderr).toBe(
|
||||
'REA configuration is invalid: REA_LOG_LEVEL: Invalid option: expected one of "trace"|"debug"|"info"|"warn"|"error"|"fatal"|"silent".\n',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -41,6 +41,7 @@ describe("CLI option aliases", () => {
|
||||
it("register only single-character short flags", async () => {
|
||||
const cli = createCli({});
|
||||
const invalid: string[] = [];
|
||||
const undescribed: string[] = [];
|
||||
for (const command of createCliInventory(cli).primary) {
|
||||
for (const [option, short] of Object.entries(
|
||||
registeredAliases(cli, command),
|
||||
@@ -52,8 +53,13 @@ describe("CLI option aliases", () => {
|
||||
const help = await serve(cli, [command, "--help"]);
|
||||
for (const match of help.stdout.matchAll(/(?:^|[\s,])-([a-z][\w-]+)/gmu))
|
||||
invalid.push(`${command} help: -${match[1] ?? ""}`);
|
||||
const options = /^Options:\n((?: {2}.*\n?)*)/mu.exec(help.stdout)?.[1];
|
||||
for (const line of options?.split("\n") ?? [])
|
||||
if (/^ {2}--\S+(?: <[^>]+>)?\s*$/u.test(line))
|
||||
undescribed.push(`${command} ${line.trim()}`);
|
||||
}
|
||||
expect(invalid).toEqual([]);
|
||||
expect(undescribed).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts kebab-case long options without registered aliases", async () => {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
|
||||
/** Captured CLI invocation for boundary tests. */
|
||||
export interface ServedCli {
|
||||
readonly stdout: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
/** Serve one CLI invocation with captured output and exit code. */
|
||||
export const serveCli = async (
|
||||
argv: readonly string[],
|
||||
environment: Readonly<Record<string, string | undefined>> = {},
|
||||
): Promise<ServedCli> => {
|
||||
const cli = createCli(environment);
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve([...argv], {
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
});
|
||||
return { stdout, exitCode };
|
||||
};
|
||||
|
||||
/** A host tool configuration refusal names what to configure, not the target. */
|
||||
export const expectConfigurationRefusal = (
|
||||
result: ServedCli,
|
||||
reason: string,
|
||||
): void => {
|
||||
const output = JSON.parse(result.stdout) as {
|
||||
code?: unknown;
|
||||
message?: unknown;
|
||||
remediation?: { action?: unknown };
|
||||
};
|
||||
expect(output.code).toBe("capability_unavailable");
|
||||
expect(output.message).toEqual(expect.stringContaining(reason));
|
||||
expect(output.remediation?.action).toEqual(expect.stringContaining(reason));
|
||||
};
|
||||
@@ -216,11 +216,20 @@ describe("interactive setup journey", () => {
|
||||
|
||||
describe("interactive setup completion", () => {
|
||||
it.each([
|
||||
{ npmCommand: "", launcher: "rea" },
|
||||
{ npmCommand: "exec", launcher: "npx rea-agents" },
|
||||
{ npmCommand: "", userAgent: "", launcher: "rea" },
|
||||
{
|
||||
npmCommand: "exec",
|
||||
userAgent: "npm/10.9.0 node/v24.11.0 linux x64",
|
||||
launcher: "npx rea-agents",
|
||||
},
|
||||
{
|
||||
npmCommand: "exec",
|
||||
userAgent: "bun/1.4.2 npm/? node/v26.3.0 linux x64",
|
||||
launcher: "bunx rea-agents",
|
||||
},
|
||||
])(
|
||||
"prints an available next command for $launcher invocation",
|
||||
async ({ npmCommand, launcher }) => {
|
||||
async ({ npmCommand, userAgent, launcher }) => {
|
||||
const { stderr } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
@@ -246,7 +255,12 @@ describe("interactive setup completion", () => {
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, npm_command: npmCommand, NO_COLOR: "1" },
|
||||
env: {
|
||||
...process.env,
|
||||
npm_command: npmCommand,
|
||||
npm_config_user_agent: userAgent,
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
@@ -9,25 +11,137 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const MARKER = "REA_TEST_RESOLVED ";
|
||||
// Dependencies that only one command uses; startup must not resolve them.
|
||||
const DEFERRED_PACKAGES = ["playwright-core", "isomorphic-git"] as const;
|
||||
// Dependencies and composition modules used by one command family; startup
|
||||
// must not resolve them just to register the complete command catalog.
|
||||
const DEFERRED_IMPORTS = [
|
||||
{
|
||||
name: "direct-analysis",
|
||||
path: "/dist/application/DirectAnalysis.js",
|
||||
},
|
||||
{
|
||||
name: "direct-analysis-status",
|
||||
path: "/dist/application/DirectAnalysisStatus.js",
|
||||
},
|
||||
{
|
||||
name: "doctor",
|
||||
path: "/dist/application/Doctor.js",
|
||||
},
|
||||
{
|
||||
name: "doctor-runtime",
|
||||
path: "/dist/doctorRuntime.js",
|
||||
},
|
||||
{
|
||||
name: "setup",
|
||||
path: "/dist/application/Setup.js",
|
||||
},
|
||||
{
|
||||
name: "setup-host",
|
||||
path: "/dist/application/SetupHost.js",
|
||||
},
|
||||
{
|
||||
name: "uninstall",
|
||||
path: "/dist/application/Uninstall.js",
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
path: "/dist/application/Update.js",
|
||||
},
|
||||
{
|
||||
name: "update-runtime",
|
||||
path: "/dist/application/UpdateRuntime.js",
|
||||
},
|
||||
{
|
||||
name: "catalog-identity",
|
||||
path: "/dist/catalogIdentity.js",
|
||||
},
|
||||
{
|
||||
name: "server-identity",
|
||||
path: "/dist/serverIdentity.js",
|
||||
},
|
||||
{
|
||||
name: "tool-contracts",
|
||||
path: "/dist/contracts/toolContracts.js",
|
||||
},
|
||||
{
|
||||
name: "playwright-core",
|
||||
path: "/node_modules/playwright-core/",
|
||||
},
|
||||
{
|
||||
name: "isomorphic-git",
|
||||
path: "/node_modules/isomorphic-git/",
|
||||
},
|
||||
{
|
||||
name: "binary-composition",
|
||||
path: "/dist/composition/binary.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-application",
|
||||
path: "/dist/application/javascript/JavaScriptApplicationService.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-workflows",
|
||||
path: "/dist/application/javascript/JavaScriptApplicationWorkflowService.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-semantic-trace",
|
||||
path: "/dist/application/javascript/JavaScriptSemanticTraceService.js",
|
||||
},
|
||||
{
|
||||
name: "electron-observation",
|
||||
path: "/dist/application/javascript/ElectronObservationService.js",
|
||||
},
|
||||
{
|
||||
name: "electron-active-observation",
|
||||
path: "/dist/application/javascript/ElectronActiveObservationService.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-runtime-reconciliation",
|
||||
path: "/dist/application/javascript/JavaScriptRuntimeReconciliationService.js",
|
||||
},
|
||||
{
|
||||
name: "android-application",
|
||||
path: "/dist/application/android/AndroidApplicationService.js",
|
||||
},
|
||||
{
|
||||
name: "apple-application",
|
||||
path: "/dist/application/apple/AppleApplicationService.js",
|
||||
},
|
||||
{
|
||||
name: "reconstruction-coverage",
|
||||
path: "/dist/application/ReconstructionCoverageService.js",
|
||||
},
|
||||
{
|
||||
name: "reconstruction-obligation-ledger",
|
||||
path: "/dist/application/ReconstructionObligationLedgerService.js",
|
||||
},
|
||||
] as const;
|
||||
// Report each resolved deferred package on stderr without changing resolution.
|
||||
const RESOLUTION_HOOK = `data:text/javascript,${encodeURIComponent(`
|
||||
import { registerHooks } from "node:module";
|
||||
const packages = ${JSON.stringify(DEFERRED_PACKAGES)};
|
||||
const imports = ${JSON.stringify(DEFERRED_IMPORTS)};
|
||||
registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
const resolved = next(specifier, context);
|
||||
const name = packages.find((item) =>
|
||||
resolved.url.includes("/node_modules/" + item + "/"),
|
||||
const name = imports.find((item) =>
|
||||
resolved.url.includes(item.path) ||
|
||||
(item.path.startsWith("/dist/") && item.path.endsWith(".js") &&
|
||||
resolved.url.includes("/dist/cli-runtime/" + item.path.slice(6, -3).split("/").join("__") + "-")),
|
||||
);
|
||||
if (name !== undefined)
|
||||
process.stderr.write(${JSON.stringify(MARKER)} + name + "\\n");
|
||||
process.stderr.write(${JSON.stringify(MARKER)} + name.name + "\\n");
|
||||
return resolved;
|
||||
},
|
||||
});
|
||||
`)}`;
|
||||
|
||||
const resolvedMarkers = (stderr: string): ReadonlySet<string> =>
|
||||
new Set(
|
||||
stderr
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(MARKER))
|
||||
.map((line) => line.slice(MARKER.length)),
|
||||
);
|
||||
|
||||
const resolvedPackages = async (
|
||||
arguments_: readonly string[],
|
||||
): Promise<ReadonlySet<string>> => {
|
||||
@@ -36,12 +150,7 @@ const resolvedPackages = async (
|
||||
[`--import=${RESOLUTION_HOOK}`, ...arguments_],
|
||||
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
|
||||
);
|
||||
return new Set(
|
||||
stderr
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(MARKER))
|
||||
.map((line) => line.slice(MARKER.length)),
|
||||
);
|
||||
return resolvedMarkers(stderr);
|
||||
};
|
||||
|
||||
const evaluate = (source: string): readonly string[] => [
|
||||
@@ -52,9 +161,19 @@ const evaluate = (source: string): readonly string[] => [
|
||||
|
||||
describe("CLI startup imports", () => {
|
||||
it("detects each deferred package when its command code loads", async () => {
|
||||
const missingBrowser = join(
|
||||
await createTestTempDirectory("rea-startup-browser-"),
|
||||
"missing-browser",
|
||||
);
|
||||
const scenario = {
|
||||
browser: { mode: "launch", executable_path: missingBrowser },
|
||||
environment: { viewport: { width: 1, height: 1 } },
|
||||
};
|
||||
await expect(
|
||||
resolvedPackages(
|
||||
evaluate('await import("./dist/composition/browserScenario.js");'),
|
||||
evaluate(
|
||||
`const { openPlaywrightScenarioBrowser } = await import("./dist/browser/PlaywrightScenarioBrowser.js"); await openPlaywrightScenarioBrowser(${JSON.stringify(scenario)}, {}).catch(() => undefined);`,
|
||||
),
|
||||
),
|
||||
).resolves.toContain("playwright-core");
|
||||
const source = await createTestTempDirectory("rea-startup-imports-");
|
||||
@@ -62,15 +181,84 @@ describe("CLI startup imports", () => {
|
||||
await expect(
|
||||
resolvedPackages(
|
||||
evaluate(
|
||||
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`,
|
||||
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); const { ArtifactResourceScope } = await import("./dist/artifacts/ArtifactResourceScope.js"); const resources = new ArtifactResourceScope(); try { await readReferenceSourceVcs(${JSON.stringify(source)}, resources); } finally { await resources.close(); }`,
|
||||
),
|
||||
),
|
||||
).resolves.toContain("isomorphic-git");
|
||||
});
|
||||
|
||||
it("does not load command-specific packages to register commands", async () => {
|
||||
it("does not load command-specific code to register the command catalog", async () => {
|
||||
await expect(
|
||||
resolvedPackages(["scripts/rea.mjs", "--help"]),
|
||||
).resolves.toEqual(new Set());
|
||||
});
|
||||
|
||||
it("does not load native provider composition for JavaScript application analysis", async () => {
|
||||
const source = await createTestTempDirectory("rea-cli-js-startup-");
|
||||
await mkdir(join(source, "src"));
|
||||
await writeFile(
|
||||
join(source, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "startup-fixture",
|
||||
version: "1.0.0",
|
||||
main: "src/index.js",
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(source, "src/index.js"),
|
||||
"export const answer = 42;\n",
|
||||
);
|
||||
|
||||
await expect(
|
||||
resolvedPackages([
|
||||
"scripts/rea.mjs",
|
||||
"analyze-javascript-application",
|
||||
source,
|
||||
"--json",
|
||||
]),
|
||||
).resolves.toEqual(new Set(["javascript-application"]));
|
||||
});
|
||||
|
||||
it("loads native provider composition when a provider operation is called", async () => {
|
||||
const resolved = await resolvedPackages(
|
||||
evaluate(
|
||||
'const { createDirectAnalysis } = await import("./dist/composition/directAnalysis.js"); await createDirectAnalysis({}).runSessionStatus();',
|
||||
),
|
||||
);
|
||||
expect(resolved).toContain("binary-composition");
|
||||
expect(resolved).not.toContain("direct-analysis");
|
||||
expect(resolved).toContain("direct-analysis-status");
|
||||
expect(resolved).toContain("server-identity");
|
||||
expect(resolved).toContain("catalog-identity");
|
||||
expect(resolved).toContain("tool-contracts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP startup imports", () => {
|
||||
it("does not load command-specific dependencies to initialize and list tools", async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [`--import=${RESOLUTION_HOOK}`, "scripts/rea.mjs", "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
});
|
||||
const client = new Client({ name: "rea-startup-imports", version: "1" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const { tools } = await client.listTools();
|
||||
expect(tools.map((tool) => tool.name)).toContain(
|
||||
"capture_browser_scenario",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
const resolved = resolvedMarkers(stderr);
|
||||
expect(resolved).not.toContain("playwright-core");
|
||||
expect(resolved).not.toContain("isomorphic-git");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import {
|
||||
access,
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
realpath,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
client: "gemini_cli",
|
||||
env: { GEMINI_CLI_HOME: "profile" },
|
||||
config: "profile/.gemini/settings.json",
|
||||
skill: "profile/.agents/skills",
|
||||
},
|
||||
{
|
||||
client: "opencode",
|
||||
env: { OPENCODE_CONFIG_DIR: "profile" },
|
||||
config: "profile/opencode.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "codex",
|
||||
env: { CODEX_HOME: "" },
|
||||
config: ".codex/config.toml",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "grok_build",
|
||||
env: { GROK_HOME: "" },
|
||||
config: ".grok/config.toml",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "omp",
|
||||
env: { PI_CODING_AGENT_DIR: "profile" },
|
||||
config: "profile/mcp.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "antigravity",
|
||||
env: {},
|
||||
config: ".gemini/config/mcp_config.json",
|
||||
skill: ".gemini/config/skills",
|
||||
},
|
||||
];
|
||||
const groups = [
|
||||
{
|
||||
name: "selected client profiles",
|
||||
cases,
|
||||
},
|
||||
...(process.platform === "win32"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
// XDG also changes OpenCode's global config layers. Exercise this
|
||||
// override independently of either OpenCode scenario.
|
||||
name: "Devin XDG profile",
|
||||
cases: [
|
||||
{
|
||||
client: "devin",
|
||||
env: { XDG_CONFIG_HOME: "profile" },
|
||||
config: "profile/devin/mcp_config.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
{
|
||||
// Devin's XDG override changes OpenCode's default root, so keep this
|
||||
// empty-override scenario in its own home and environment.
|
||||
name: "default OpenCode profile",
|
||||
cases: [
|
||||
{
|
||||
client: "opencode",
|
||||
env: { OPENCODE_CONFIG_DIR: "" },
|
||||
config: ".config/opencode/opencode.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
cliTest(
|
||||
"uninstall purge retains unrelated data behind a managed-root symlink",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-uninstall-root-link-");
|
||||
const home = join(root, "home");
|
||||
const unrelated = join(root, "unrelated-application");
|
||||
await mkdir(home);
|
||||
for (const name of ["cache", "state"]) {
|
||||
await mkdir(join(unrelated, name), { recursive: true });
|
||||
await writeFile(join(unrelated, name, "keep.txt"), `unrelated ${name}`);
|
||||
}
|
||||
const managedRoot = join(home, ".rea");
|
||||
await symlink(
|
||||
unrelated,
|
||||
managedRoot,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["uninstall", "--purge-data", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(root, "xdg-config"),
|
||||
XDG_CACHE_HOME: join(root, "xdg-cache"),
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
expect.soft(result.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "cache", status: "retained" }),
|
||||
expect.objectContaining({ name: "state", status: "retained" }),
|
||||
]),
|
||||
});
|
||||
expect((await lstat(managedRoot)).isSymbolicLink()).toBe(true);
|
||||
expect(await realpath(managedRoot)).toBe(await realpath(unrelated));
|
||||
for (const name of ["cache", "state"])
|
||||
await expect
|
||||
.soft(readFile(join(unrelated, name, "keep.txt"), "utf8"))
|
||||
.resolves.toBe(`unrelated ${name}`);
|
||||
},
|
||||
);
|
||||
|
||||
for (const group of groups) {
|
||||
cliTest(
|
||||
`${group.name} lifecycle follows the selected roots`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-client-profile-");
|
||||
const environment: NodeJS.ProcessEnv = { HOME: home, USERPROFILE: home };
|
||||
for (const testCase of group.cases)
|
||||
for (const [key, value] of Object.entries(testCase.env))
|
||||
environment[key] = value === "profile" ? join(home, value) : value;
|
||||
// OMP's relative override is relative to the caller, not silently ignored.
|
||||
if (group.cases.some(({ client }) => client === "omp"))
|
||||
environment.PI_CODING_AGENT_DIR = "profile";
|
||||
const profiles = group.cases.map((testCase) => ({
|
||||
...testCase,
|
||||
config: join(home, testCase.config),
|
||||
skillDirectory: join(home, testCase.skill, "reverse-engineer-anything"),
|
||||
}));
|
||||
const clientArguments = profiles.flatMap(({ client }) => [
|
||||
"--client",
|
||||
client,
|
||||
]);
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
for (const { client, config, skillDirectory } of profiles) {
|
||||
const planned = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
client,
|
||||
"--dry-run",
|
||||
"--json",
|
||||
]);
|
||||
expect(planned.exitCode, client).toBe(0);
|
||||
expect(planned.json, client).toMatchObject({
|
||||
status: "planned",
|
||||
plannedActions: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: `configure_client:${client}`,
|
||||
target: config,
|
||||
}),
|
||||
expect.objectContaining({ target: skillDirectory }),
|
||||
]),
|
||||
});
|
||||
await expect(access(skillDirectory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
for (const { config } of profiles)
|
||||
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const setup = await run(["setup", ...clientArguments, "--yes", "--json"]);
|
||||
expect(setup.exitCode).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
for (const { config, skillDirectory } of profiles) {
|
||||
await expect(access(config)).resolves.toBeUndefined();
|
||||
expect(
|
||||
await readFile(join(skillDirectory, "SKILL.md"), "utf8"),
|
||||
).toContain("reverse-engineer-anything");
|
||||
}
|
||||
await expect(access(join(home, "config.toml"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
for (const { client, config } of profiles) {
|
||||
const doctor = await run([
|
||||
"doctor",
|
||||
"--client",
|
||||
client,
|
||||
"--skill",
|
||||
"--json",
|
||||
]);
|
||||
expect(doctor.exitCode, client).toBe(0);
|
||||
expect(doctor.json, client).toMatchObject({
|
||||
healthy: true,
|
||||
scope: { mode: "explicit", clients: [client], skill: true },
|
||||
identity: {
|
||||
skill: { state: "aligned" },
|
||||
registrations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
client,
|
||||
config_path: config,
|
||||
state: "aligned",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
if (client === "grok_build") {
|
||||
const original = await readFile(config, "utf8");
|
||||
await writeFile(
|
||||
config,
|
||||
original.replace(
|
||||
"[mcp_servers.rea]",
|
||||
"[mcp_servers.rea]\ndisabled = true",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
(await run(["doctor", "--client", "grok_build", "--json"]))
|
||||
.exitCode,
|
||||
).toBe(0);
|
||||
await writeFile(config, original);
|
||||
}
|
||||
}
|
||||
const repeat = await run([
|
||||
"setup",
|
||||
...clientArguments,
|
||||
"--yes",
|
||||
"--json",
|
||||
]);
|
||||
expect(repeat.exitCode).toBe(0);
|
||||
expect(repeat.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: [],
|
||||
});
|
||||
const uninstall = await run(["uninstall", "--json"]);
|
||||
expect(uninstall.exitCode).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({ status: "complete" });
|
||||
for (const { skillDirectory } of profiles)
|
||||
await expect(
|
||||
access(join(skillDirectory, "SKILL.md")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest("uninstall names each retained skill directory", async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-paths-");
|
||||
const shared = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
|
||||
const claude = join(home, ".claude", "skills", PRODUCT_IDENTITY.skillName);
|
||||
for (const directory of [shared, claude]) {
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(join(directory, "SKILL.md"), "---\nname: unrelated\n---\n");
|
||||
}
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["uninstall", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CLAUDE_CONFIG_DIR: join(home, ".claude"),
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const report = result.json as {
|
||||
items?: readonly { name: string; status: string; detail: string }[];
|
||||
};
|
||||
const skill = report.items?.find(({ name }) => name === "skill");
|
||||
expect(skill?.status).toBe("retained");
|
||||
for (const directory of [shared, claude]) {
|
||||
expect(skill?.detail).toContain(
|
||||
`${directory}: retained (Skill manifest is not REA-owned.)`,
|
||||
);
|
||||
expect(await readFile(join(directory, "SKILL.md"), "utf8")).toBe(
|
||||
"---\nname: unrelated\n---\n",
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -6,161 +6,6 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
client: "gemini_cli",
|
||||
env: { GEMINI_CLI_HOME: "profile" },
|
||||
config: "profile/.gemini/settings.json",
|
||||
skill: "profile/.agents/skills",
|
||||
},
|
||||
{
|
||||
client: "opencode",
|
||||
env: { OPENCODE_CONFIG_DIR: "profile" },
|
||||
config: "profile/opencode.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "opencode",
|
||||
env: { OPENCODE_CONFIG_DIR: "" },
|
||||
config: ".config/opencode/opencode.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "codex",
|
||||
env: { CODEX_HOME: "" },
|
||||
config: ".codex/config.toml",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "grok_build",
|
||||
env: { GROK_HOME: "" },
|
||||
config: ".grok/config.toml",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "omp",
|
||||
env: { PI_CODING_AGENT_DIR: "profile" },
|
||||
config: "profile/mcp.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "devin",
|
||||
env: { XDG_CONFIG_HOME: "profile" },
|
||||
config: "profile/devin/mcp_config.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
{
|
||||
client: "antigravity",
|
||||
env: {},
|
||||
config: ".gemini/config/mcp_config.json",
|
||||
skill: ".gemini/config/skills",
|
||||
},
|
||||
];
|
||||
for (const testCase of cases.filter(
|
||||
({ client }) => process.platform !== "win32" || client !== "devin",
|
||||
)) {
|
||||
cliTest(
|
||||
`${testCase.client} lifecycle follows the selected roots (${testCase.config})`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-client-profile-");
|
||||
const environment: NodeJS.ProcessEnv = { HOME: home, USERPROFILE: home };
|
||||
for (const [key, value] of Object.entries(testCase.env))
|
||||
environment[key] = value === "profile" ? join(home, value) : value;
|
||||
// OMP's relative override is relative to the caller, not silently ignored.
|
||||
if (testCase.client === "omp")
|
||||
environment.PI_CODING_AGENT_DIR = "profile";
|
||||
const config = join(home, testCase.config);
|
||||
const skillDirectory = join(
|
||||
home,
|
||||
testCase.skill,
|
||||
"reverse-engineer-anything",
|
||||
);
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
const planned = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
testCase.client,
|
||||
"--dry-run",
|
||||
"--json",
|
||||
]);
|
||||
expect(planned.exitCode).toBe(0);
|
||||
expect(planned.json).toMatchObject({
|
||||
status: "planned",
|
||||
plannedActions: expect.arrayContaining([
|
||||
expect.objectContaining({ target: config }),
|
||||
expect.objectContaining({ target: skillDirectory }),
|
||||
]),
|
||||
});
|
||||
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const setup = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
testCase.client,
|
||||
"--yes",
|
||||
"--json",
|
||||
]);
|
||||
expect(setup.exitCode).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
await expect(access(config)).resolves.toBeUndefined();
|
||||
expect(
|
||||
await readFile(join(skillDirectory, "SKILL.md"), "utf8"),
|
||||
).toContain("reverse-engineer-anything");
|
||||
await expect(access(join(home, "config.toml"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const doctor = await run([
|
||||
"doctor",
|
||||
"--client",
|
||||
testCase.client,
|
||||
"--skill",
|
||||
"--json",
|
||||
]);
|
||||
expect(doctor.exitCode).toBe(0);
|
||||
expect(doctor.json).toMatchObject({
|
||||
healthy: true,
|
||||
identity: { skill: { state: "aligned" } },
|
||||
});
|
||||
if (testCase.client === "grok_build") {
|
||||
const original = await readFile(config, "utf8");
|
||||
await writeFile(
|
||||
config,
|
||||
original.replace(
|
||||
"[mcp_servers.rea]",
|
||||
"[mcp_servers.rea]\ndisabled = true",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
(await run(["doctor", "--client", "grok_build", "--json"])).exitCode,
|
||||
).toBe(0);
|
||||
await writeFile(config, original);
|
||||
}
|
||||
const repeat = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
testCase.client,
|
||||
"--yes",
|
||||
"--json",
|
||||
]);
|
||||
expect(repeat.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: [],
|
||||
});
|
||||
const uninstall = await run(["uninstall", "--json"]);
|
||||
expect(uninstall.exitCode).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({ status: "complete" });
|
||||
await expect(
|
||||
access(join(skillDirectory, "SKILL.md")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
for (const policy of [{ excluded: ["rea"] }, { allowed: ["other"] }]) {
|
||||
cliTest(
|
||||
`Gemini refuses a registration blocked by ${Object.keys(policy)[0]}`,
|
||||
|
||||
@@ -11,7 +11,8 @@ describe("executable dispatcher", () => {
|
||||
async ({ processes, workspace }) => {
|
||||
const scripts = await workspace.mkdir("scripts");
|
||||
await workspace.mkdir("dist");
|
||||
await workspace.mkdir("dist/cli");
|
||||
await workspace.mkdir("dist/cli-runtime");
|
||||
await workspace.mkdir("dist/mcp");
|
||||
await Promise.all([
|
||||
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
|
||||
workspace.write(
|
||||
@@ -19,23 +20,23 @@ describe("executable dispatcher", () => {
|
||||
JSON.stringify({ type: "module", version: "1.0.0" }),
|
||||
),
|
||||
workspace.write(
|
||||
"dist/main.js",
|
||||
"dist/mcp/main.js",
|
||||
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" }));\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli.js",
|
||||
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
"dist/cli-runtime/cli.js",
|
||||
'export const cliConfigurationError = () => undefined; export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cliOutput.js",
|
||||
"dist/cli-runtime/cliOutput.js",
|
||||
"export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli/streamedJsonOutput.js",
|
||||
"dist/cli-runtime/streamedJsonOutput.js",
|
||||
"export const createStreamedCliJsonOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/mcpDoctor.js",
|
||||
"dist/cli-runtime/mcpDoctor.js",
|
||||
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -252,6 +252,130 @@ describe("trace-dylib-resolution CLI", () => {
|
||||
);
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"rejects build-version tool records outside their load command",
|
||||
async ({ cli }) => {
|
||||
const app = await fixtureApp();
|
||||
const withTool = new Uint8Array(32);
|
||||
withTool.set(buildVersionCommand(0xffffffff));
|
||||
const toolView = new DataView(withTool.buffer);
|
||||
toolView.setUint32(4, 32, true);
|
||||
toolView.setUint32(20, 1, true);
|
||||
toolView.setUint32(24, 3, true);
|
||||
toolView.setUint32(28, 0x10000, true);
|
||||
|
||||
const missingTool = buildVersionCommand(1);
|
||||
new DataView(missingTool.buffer).setUint32(20, 1, true);
|
||||
const excessiveTools = buildVersionCommand(1);
|
||||
new DataView(excessiveTools.buffer).setUint32(20, 0xffffffff, true);
|
||||
const missingSecondTool = withTool.slice();
|
||||
new DataView(missingSecondTool.buffer).setUint32(20, 2, true);
|
||||
const shortHeader = buildVersionCommand(1).slice(0, 16);
|
||||
new DataView(shortHeader.buffer).setUint32(4, 16, true);
|
||||
const cases = [
|
||||
["no-tools", [buildVersionCommand(1)], "parsed"],
|
||||
["one-tool", [withTool], "parsed"],
|
||||
// The following command and the image's trailing bytes cannot satisfy ntools.
|
||||
["missing-tool", [missingTool, rpathCommand("x")], "malformed"],
|
||||
["excessive-tools", [excessiveTools], "malformed"],
|
||||
["missing-second-tool", [missingSecondTool], "malformed"],
|
||||
["short-header", [shortHeader], "malformed"],
|
||||
] as const;
|
||||
for (const [name, commands] of cases) {
|
||||
await writeFiles(app, {
|
||||
[`Contents/Helpers/${name}`]: machoImage({ commands }),
|
||||
});
|
||||
}
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["trace-dylib-resolution", app, "--json"],
|
||||
environment: ENVIRONMENT,
|
||||
});
|
||||
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
|
||||
const trace = dylibResolutionResultSchema.parse(
|
||||
(result.json as { normalized_result: unknown }).normalized_result,
|
||||
);
|
||||
for (const [name, , status] of cases) {
|
||||
const path = `Contents/Helpers/${name}`;
|
||||
const image = trace.images.find((item) => item.path === path);
|
||||
expect(image, name).toMatchObject({ parse_status: status });
|
||||
if (status === "malformed") {
|
||||
expect(image).toMatchObject({
|
||||
reason: expect.stringContaining("LC_BUILD_VERSION"),
|
||||
slices: [],
|
||||
});
|
||||
expect(trace.roots.some((root) => root.image === path)).toBe(false);
|
||||
expect(trace.coverage.unparsed_images).toContain(path);
|
||||
} else {
|
||||
expect(image).toMatchObject({
|
||||
reason: null,
|
||||
slices: [{ platforms: [name === "one-tool" ? 0xffffffff : 1] }],
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(trace.coverage.status).toBe("partial");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains directory requirements when resolving dylib install names",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-dylib-path-cli-");
|
||||
const names = [
|
||||
"@loader_path/lib/libhelper.dylib/",
|
||||
"@loader_path/lib/libhelper.dylib/.",
|
||||
"@rpath/libhelper.dylib/",
|
||||
"@rpath/libhelper.dylib/.",
|
||||
"@rpath/",
|
||||
"@loader_path/lib/./libhelper.dylib",
|
||||
"@loader_path/lib//libhelper.dylib",
|
||||
];
|
||||
await writeFiles(directory, {
|
||||
tool: machoImage({
|
||||
commands: [
|
||||
buildVersionCommand(1),
|
||||
rpathCommand("@loader_path/lib/libhelper.dylib"),
|
||||
rpathCommand("@loader_path/lib"),
|
||||
...names.map((name) => dylibCommand(LC.LOAD_DYLIB, name)),
|
||||
],
|
||||
}),
|
||||
"lib/libhelper.dylib": machoImage({
|
||||
fileType: FILE_TYPE.dylib,
|
||||
commands: [buildVersionCommand(1)],
|
||||
}),
|
||||
});
|
||||
const result = await cli.run({
|
||||
arguments: ["trace-dylib-resolution", join(directory, "tool"), "--json"],
|
||||
environment: ENVIRONMENT,
|
||||
});
|
||||
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
|
||||
const trace = dylibResolutionResultSchema.parse(
|
||||
parseEvidence(result.json).normalized_result,
|
||||
);
|
||||
expect(
|
||||
trace.edges.map(({ install_name, candidates, resolution }) => ({
|
||||
install_name,
|
||||
outcome: candidates[0]?.outcome,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual(
|
||||
names.map((name, index) => ({
|
||||
install_name: name,
|
||||
outcome: index < 5 ? "absent" : "resolved",
|
||||
resolution:
|
||||
index < 5
|
||||
? { status: "unresolved", image: null }
|
||||
: { status: "resolved", image: "lib/libhelper.dylib" },
|
||||
})),
|
||||
);
|
||||
expect(
|
||||
trace.findings.map(({ kind, edge_index }) => [kind, edge_index]),
|
||||
).toEqual(
|
||||
[0, 1, 2, 3, 4].map((index) => ["required-load-unresolved", index]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.getuid?.() === 0)(
|
||||
"trace-dylib-resolution permissions",
|
||||
() => {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
import { expect } from "vitest";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { z } from "zod";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const analyze = async (cli: TestCli, extra = "") => {
|
||||
const root = await createTestTempDirectory("rea-electron-wrapped-paths-");
|
||||
await writeFixtureFiles(root, {
|
||||
"preload.js": `const e=require("electron");
|
||||
const sender=channel=>(...args)=>e.ipcRenderer.send(channel,...args);
|
||||
e.contextBridge.exposeInMainWorld("desktop",{copy:sender("test:copy"),cut:sender("test:cut")});`,
|
||||
"main.js": `const e=require("electron");
|
||||
function register(channel,handler){e.ipcMain.addListener(channel,event=>allowed(event)&&handler(event))}
|
||||
register("test:copy",event=>event.sender.copy());
|
||||
register("test:cut",event=>event.sender.cut());${extra}`,
|
||||
});
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const { normalized_result: result } = z
|
||||
.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
})
|
||||
.parse(output.json);
|
||||
return { root, application: output.json, ...result };
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"traces a wrapped bridge member through a unique IPC channel using the public CLI",
|
||||
async ({ cli }) => {
|
||||
const { root, application, graph } = await analyze(cli);
|
||||
const byId = new Map(graph.nodes.map((n) => [n.node_id, n]));
|
||||
const joins = graph.edges.filter(
|
||||
(e) => e.evidence.extractor.operation === "join-electron-wrapper-paths",
|
||||
);
|
||||
expect(joins).toHaveLength(2);
|
||||
for (const edge of joins) {
|
||||
expect(edge.evidence).toMatchObject({
|
||||
state: "inferred",
|
||||
authority: "static-relationship-inference",
|
||||
});
|
||||
expect(edge.properties.pairing_basis).toBe(
|
||||
"unique-exact-literal-channel",
|
||||
);
|
||||
expect(
|
||||
byId.get(edge.source_node_id)?.observations[0]?.properties.channel,
|
||||
).toBe(edge.properties.channel);
|
||||
expect(
|
||||
byId.get(edge.target_node_id)?.observations[0]?.properties.channel,
|
||||
).toBe(edge.properties.channel);
|
||||
expect(edge.properties.conditions).toEqual([
|
||||
expect.objectContaining({ expression: "allowed(event)" }),
|
||||
]);
|
||||
}
|
||||
const start = graph.nodes.find((n) =>
|
||||
n.observations.some(
|
||||
(o) =>
|
||||
o.properties.entry === "desktop.copy" &&
|
||||
o.properties.step_kind === "exposure",
|
||||
),
|
||||
);
|
||||
expect(start).toBeDefined();
|
||||
const visited = new Set<string>(),
|
||||
pending = start ? [start.node_id] : [];
|
||||
while (pending.length) {
|
||||
const id = pending.pop();
|
||||
if (!id || visited.has(id)) continue;
|
||||
visited.add(id);
|
||||
for (const edge of graph.edges)
|
||||
if (edge.source_node_id === id) pending.push(edge.target_node_id);
|
||||
}
|
||||
expect(
|
||||
[...visited].some((id) =>
|
||||
byId
|
||||
.get(id)
|
||||
?.observations.some((o) => o.label === "ipc-event.sender.copy"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
[...visited].some((id) =>
|
||||
byId
|
||||
.get(id)
|
||||
?.observations.some((o) => o.label === "ipc-event.sender.cut"),
|
||||
),
|
||||
).toBe(false);
|
||||
const input = join(root, "trace-input.json");
|
||||
await writeFile(
|
||||
input,
|
||||
JSON.stringify({
|
||||
application,
|
||||
seed: { kind: "api", value: "desktop.copy", match: "exact" },
|
||||
direction: "outgoing",
|
||||
}),
|
||||
);
|
||||
const traced = await cli.run({
|
||||
arguments: ["trace-application-feature", input, "--json"],
|
||||
});
|
||||
expect(traced.exitCode).toBe(0);
|
||||
const { normalized_result: trace } = z
|
||||
.object({
|
||||
normalized_result: applicationFeatureTraceResultSchema,
|
||||
})
|
||||
.parse(traced.json);
|
||||
expect(trace.seed_matches).toHaveLength(1);
|
||||
expect(
|
||||
trace.paths.some(
|
||||
(path) =>
|
||||
path.contains_inference &&
|
||||
path.node_ids.length > 8 &&
|
||||
byId
|
||||
.get(path.end_node_id)
|
||||
?.observations.some((o) => o.label === "ipc-event.sender.copy"),
|
||||
),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
for (const surface of ["CLI", "stdio MCP"] as const) {
|
||||
cliTest(
|
||||
`preserves handler ambiguity and short-circuit factory paths through ${surface}`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-branch-paths-");
|
||||
await writeFixtureFiles(root, {
|
||||
"preload.js": `const e=require("electron");
|
||||
e.contextBridge.exposeInMainWorld("empty", {});
|
||||
function choose(){
|
||||
if(flag)return ()=>e.ipcRenderer.send("test:copy");
|
||||
else return ()=>e.ipcRenderer.send("test:cut");
|
||||
return ()=>e.ipcRenderer.send("test:dead");
|
||||
}
|
||||
e.contextBridge.exposeInMainWorld("desktop", {
|
||||
choose:choose(),
|
||||
ambiguous:()=>e.ipcRenderer.send("test:ambiguous"),
|
||||
competing:()=>e.ipcRenderer.send("test:competing"),
|
||||
conditional:()=>e.ipcRenderer.send("test:conditional"),
|
||||
fallback:()=>e.ipcRenderer.send("test:fallback"),
|
||||
});`,
|
||||
"main.js": `const e=require("electron");
|
||||
const copy=event=>event.sender.copy(), cut=event=>event.sender.cut();
|
||||
function register(channel,handler){e.ipcMain.on(channel,handler)}
|
||||
register("test:copy",copy);register("test:cut",cut);
|
||||
register("test:ambiguous",flag?copy:cut);
|
||||
register("test:competing",copy);
|
||||
register("test:competing",flag?copy:unknownHandler);
|
||||
if(flag) register("test:conditional",copy);
|
||||
register("test:fallback",event=>{false ?? event.sender.copy()});`,
|
||||
});
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const empty = graph.nodes
|
||||
.filter((node) => node.kind === "context-bridge-api")
|
||||
.flatMap((node) => node.observations)
|
||||
.find((observation) => observation.properties.api_key === "empty");
|
||||
expect(empty).toMatchObject({
|
||||
properties: {
|
||||
api_status: "object-literal",
|
||||
members: [],
|
||||
unknown_members: 0,
|
||||
resolution_basis: "direct-syntax",
|
||||
},
|
||||
evidence: { state: "observed" },
|
||||
});
|
||||
const joins = graph.edges.filter(
|
||||
(edge) =>
|
||||
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
|
||||
);
|
||||
expect(joins.map((edge) => edge.properties.channel).sort()).toEqual([
|
||||
"test:copy",
|
||||
"test:cut",
|
||||
]);
|
||||
const steps = graph.nodes
|
||||
.flatMap((node) => node.observations)
|
||||
.filter(
|
||||
(observation) => observation.properties.step_kind === "terminal",
|
||||
);
|
||||
expect(
|
||||
[
|
||||
...new Set(
|
||||
steps
|
||||
.filter((step) => step.properties.entry === "desktop.choose")
|
||||
.map((step) => step.properties.channel),
|
||||
),
|
||||
].sort(),
|
||||
).toEqual(["test:copy", "test:cut"]);
|
||||
for (const [channel, expression] of [
|
||||
["test:copy", "flag"],
|
||||
["test:cut", "!(flag)"],
|
||||
])
|
||||
expect(
|
||||
steps.find(
|
||||
(step) =>
|
||||
step.properties.entry === "desktop.choose" &&
|
||||
step.properties.channel === channel,
|
||||
)?.properties.conditions,
|
||||
).toEqual([expect.objectContaining({ expression })]);
|
||||
expect(
|
||||
steps.some(
|
||||
(step) =>
|
||||
step.properties.entry_kind === "ipc-handler" &&
|
||||
["test:ambiguous", "test:fallback"].includes(
|
||||
String(step.properties.channel),
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"does not join a channel with another untraced compatible handler",
|
||||
async ({ cli }) => {
|
||||
const { graph } = await analyze(
|
||||
cli,
|
||||
'e.ipcMain.on("test:copy",event=>unresolved(event));',
|
||||
);
|
||||
const joins = graph.edges.filter(
|
||||
(e) => e.evidence.extractor.operation === "join-electron-wrapper-paths",
|
||||
);
|
||||
expect(joins.map((e) => e.properties.channel)).toEqual(["test:cut"]);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,117 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
updateResidualUnknown,
|
||||
} from "../../../src/domain/residualUnknown.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const revisionBundle = () => {
|
||||
const records = ["open", "investigate"].map((operation) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation, parameters: {}, result: { observed: operation } },
|
||||
),
|
||||
);
|
||||
const [opened, investigated] = records;
|
||||
if (opened === undefined || investigated === undefined)
|
||||
throw new Error("Missing mutation Evidence");
|
||||
const details = {
|
||||
severity: "high" as const,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: null,
|
||||
required_confidence: "observed" as const,
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
};
|
||||
const initial = createResidualUnknown(
|
||||
{ question: "How is this input handled?", domain: "protocol", ...details },
|
||||
opened.evidence_id,
|
||||
null,
|
||||
);
|
||||
const revised = updateResidualUnknown(
|
||||
initial,
|
||||
{
|
||||
unknown_id: initial.unknown_id,
|
||||
expected_revision: initial.revision,
|
||||
status: "investigating",
|
||||
...details,
|
||||
resolution: null,
|
||||
},
|
||||
investigated.evidence_id,
|
||||
);
|
||||
return createEvidenceBundle(records, [initial, revised]);
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"reports standalone import counts for every unknown revision",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-import-");
|
||||
const path = join(root, "bundle.json");
|
||||
await writeFile(path, JSON.stringify(revisionBundle()));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toEqual({ imported: 2, unknowns_added: 2, total: 2 });
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"reports a standalone Evidence record as the wrong input file kind",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-record-input-");
|
||||
const path = join(root, "record.json");
|
||||
const record = revisionBundle().records[0];
|
||||
if (record === undefined) throw new Error("Missing fixture Evidence");
|
||||
await writeFile(path, JSON.stringify(record));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: { path },
|
||||
message: expect.stringContaining("this JSON is one Evidence record"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects altered Evidence and incomplete unknown history before reporting counts",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-import-invalid-");
|
||||
const path = join(root, "bundle.json");
|
||||
const bundle = revisionBundle();
|
||||
for (const invalid of [
|
||||
{
|
||||
...bundle,
|
||||
records: bundle.records.map((record) => ({
|
||||
...record,
|
||||
normalized_result: "altered",
|
||||
})),
|
||||
},
|
||||
{ ...bundle, unknowns: bundle.unknowns.slice(1) },
|
||||
]) {
|
||||
await writeFile(path, JSON.stringify(invalid));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "evidence_integrity_mismatch",
|
||||
});
|
||||
expect(result.json).not.toHaveProperty("imported");
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { serveCli } from "./cliServeHarness.js";
|
||||
|
||||
it.each(["identify-flutter-build", "inspect-dart-aot"])(
|
||||
"%s advertises a schema through the public CLI",
|
||||
async (command) => {
|
||||
const result = await serveCli([command, "--schema", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toBeTruthy();
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an unreadable target with an input refusal", async () => {
|
||||
const result = await serveCli([
|
||||
"identify-flutter-build",
|
||||
"/nonexistent/app.apk",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.stdout).toContain("invalid_request");
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
|
||||
|
||||
it("maps one-shot Frida CLI target, script, duration, and remote options", async () => {
|
||||
const calls: unknown[] = [];
|
||||
const provider: FridaInstrumentationPort = {
|
||||
async listDevices() {
|
||||
calls.push({ operation: "devices" });
|
||||
return { ok: true, value: { devices: [], cleanupError: null } };
|
||||
},
|
||||
async listProcesses() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { deviceId: "local", processes: [], cleanupError: null },
|
||||
};
|
||||
},
|
||||
async startSession(input) {
|
||||
calls.push({ operation: "start", input });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: input.mode,
|
||||
state: "running",
|
||||
},
|
||||
};
|
||||
},
|
||||
async loadScript(sessionId, source) {
|
||||
calls.push({ operation: "load", sessionId, source });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
scriptId: "00000000-0000-4000-8000-000000000002",
|
||||
sourceKind: source.sourceKind,
|
||||
sourcePath: source.sourceKind === "file" ? source.path : null,
|
||||
sourceSha256: "a".repeat(64),
|
||||
messages: [{ type: "send", payload: "observed" }],
|
||||
messagesTruncated: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
async resumeSession(sessionId) {
|
||||
calls.push({ operation: "resume", sessionId });
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
async unloadScript() {
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
status(sessionId) {
|
||||
return {
|
||||
sessionId,
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: "attach",
|
||||
state: "running",
|
||||
targetResumeObserved: false,
|
||||
scripts: [],
|
||||
messages: [],
|
||||
messagesTruncated: false,
|
||||
};
|
||||
},
|
||||
async closeSession(sessionId) {
|
||||
calls.push({ operation: "close", sessionId });
|
||||
return { ok: true, value: { targetResumeObserved: false } };
|
||||
},
|
||||
async closeAll() {},
|
||||
};
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"attach",
|
||||
"71",
|
||||
"--script",
|
||||
"send('hello')",
|
||||
"--remote-address",
|
||||
"127.0.0.1:27042",
|
||||
"--token",
|
||||
"synthetic-secret-token",
|
||||
"--keepalive-interval",
|
||||
"10",
|
||||
"--duration-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).toBe(0);
|
||||
const result: unknown = JSON.parse(stdout);
|
||||
expect(JSON.stringify(result)).not.toContain("synthetic-secret-token");
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
operation: "start",
|
||||
input: {
|
||||
mode: "attach",
|
||||
pid: 71,
|
||||
remote: {
|
||||
address: "127.0.0.1:27042",
|
||||
token: "synthetic-secret-token",
|
||||
keepaliveInterval: 10,
|
||||
},
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
durationMs: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: "load",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
},
|
||||
{
|
||||
operation: "close",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
},
|
||||
]);
|
||||
|
||||
stdout = "";
|
||||
exitCode = 0;
|
||||
await cli.serve(
|
||||
["list-frida-devices", "--token", "synthetic-secret-token", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(stdout).not.toContain("synthetic-secret-token");
|
||||
});
|
||||
|
||||
it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {
|
||||
for (const cleanupFails of [false, true]) {
|
||||
const calls: string[] = [];
|
||||
const provider: FridaInstrumentationPort =
|
||||
new FridaInstrumentationManager();
|
||||
provider.startSession = async () => {
|
||||
calls.push("start");
|
||||
return {
|
||||
ok: false,
|
||||
error: new AnalysisCapabilityUnavailableError(
|
||||
"frida",
|
||||
"start_frida_session",
|
||||
"attach failed after spawn",
|
||||
{
|
||||
cleanup: {
|
||||
reason: "first resume failed",
|
||||
resources: ["paused spawn"],
|
||||
},
|
||||
},
|
||||
),
|
||||
};
|
||||
};
|
||||
provider.closeAll = async () => {
|
||||
calls.push("cleanup");
|
||||
if (cleanupFails) throw new Error("resume still failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"spawn",
|
||||
"/tmp/fixture",
|
||||
"--script",
|
||||
"send('ready')",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(calls).toEqual(["start", "cleanup"]);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: cleanupFails ? "cleanup_incomplete" : "capability_unavailable",
|
||||
});
|
||||
expect(stdout).toContain("attach failed after spawn");
|
||||
if (cleanupFails) expect(stdout).toContain("primary_error");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves observed devices when CLI provider cleanup fails", async () => {
|
||||
const provider: FridaInstrumentationPort = new FridaInstrumentationManager();
|
||||
const devices = [
|
||||
{ deviceId: "remote-device", name: "selected endpoint", type: "remote" },
|
||||
];
|
||||
provider.listDevices = async () => ({
|
||||
ok: true,
|
||||
value: { devices, cleanupError: null },
|
||||
});
|
||||
provider.closeAll = async () => {
|
||||
throw new Error("remote removal failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
["list-frida-devices", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { partial_observation: { devices } } },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
["attach", "abc", "--script", "send(1)"],
|
||||
"target",
|
||||
"attach mode needs a positive integer process ID.",
|
||||
],
|
||||
[
|
||||
["attach", "71"],
|
||||
"script",
|
||||
"Provide exactly one of --script or --script-file.",
|
||||
],
|
||||
])(
|
||||
"names the rejected instrument-with-frida argument for %j",
|
||||
async (argv, path, message) => {
|
||||
let starts = 0;
|
||||
const provider = {
|
||||
async startSession() {
|
||||
starts += 1;
|
||||
throw new Error("Frida must not start for invalid input");
|
||||
},
|
||||
} as unknown as FridaInstrumentationPort;
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
await cli.serve(["instrument-with-frida", ...argv, "--json"], {
|
||||
env: {},
|
||||
exit: () => undefined,
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
});
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: [path], reason: "invalid_value", message }],
|
||||
},
|
||||
});
|
||||
expect(starts).toBe(0);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,98 @@
|
||||
import { chmod, copyFile, rm } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
|
||||
import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js";
|
||||
|
||||
const FAILED_LAUNCHER = `#!/bin/sh
|
||||
printf 'Cannot launch Hopper!\\nDocument state is unknown.\\n' >&2
|
||||
exit 2
|
||||
`;
|
||||
|
||||
/** The private runtime directory a failed launch reports as retained. */
|
||||
const RetainedRuntime = z.object({
|
||||
details: z.object({
|
||||
diagnostics: z.object({
|
||||
cleanup_error: z.object({
|
||||
details: z.object({
|
||||
diagnostics: z.object({ runtime_root: z.string() }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
describe("Hopper launcher failure through the one-shot CLI", () => {
|
||||
// Hopper target leases are acquired only for the macOS launcher route.
|
||||
workspaceCliTest.skipIf(process.platform !== "darwin")(
|
||||
"exits after a retained-cleanup failure and releases the target to a retry",
|
||||
{ timeout: 90_000 },
|
||||
async ({ cli, workspace }) => {
|
||||
const launcherPath = await workspace.write(
|
||||
"failure-helper",
|
||||
FAILED_LAUNCHER,
|
||||
);
|
||||
await chmod(launcherPath, 0o700);
|
||||
const targetPath = workspace.path("probe");
|
||||
await copyFile("/usr/bin/true", targetPath);
|
||||
const loaderArgs = ["--probe"];
|
||||
onTestFinished(async () => {
|
||||
const recovered = await acquireHopperTargetLease({
|
||||
targetPath,
|
||||
targetKind: "executable",
|
||||
loaderArgs,
|
||||
runId: "failed-cli-test-cleanup",
|
||||
});
|
||||
expect(recovered.acquired).toBe(true);
|
||||
if (recovered.acquired) await recovered.lease.release();
|
||||
});
|
||||
|
||||
for (const attempt of ["first", "retry"]) {
|
||||
const result = await cli.run({
|
||||
arguments: ["analyze", targetPath, "--provider", "hopper", "--json"],
|
||||
environment: {
|
||||
...workspace.environment,
|
||||
HOPPER_LAUNCHER_PATH: launcherPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
timeoutMs: 45_000,
|
||||
});
|
||||
const retained = RetainedRuntime.safeParse(result.json);
|
||||
if (retained.success)
|
||||
await rm(
|
||||
retained.data.details.diagnostics.cleanup_error.details.diagnostics
|
||||
.runtime_root,
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
|
||||
expect(result.exitCode, attempt).toBe(1);
|
||||
expect(result.json, attempt).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
cleanup: "incomplete",
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
stage: "launch",
|
||||
launcher: {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Document state is unknown",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,15 +1,15 @@
|
||||
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 { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.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";
|
||||
const filter = "evidence_id,normalized_result.graph.nodes[0,1].node_id";
|
||||
|
||||
for (const scenario of [
|
||||
{
|
||||
@@ -34,6 +34,9 @@ for (const scenario of [
|
||||
await writeFile(join(root, "main.js"), "fetch('');\n");
|
||||
const direct = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!direct.ok) throw direct.error;
|
||||
const normalized = javascriptApplicationAnalysisResultSchema.parse(
|
||||
direct.value.normalized_result,
|
||||
);
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
scenario.command,
|
||||
@@ -61,9 +64,20 @@ for (const scenario of [
|
||||
}
|
||||
expect(data).toEqual(
|
||||
scenario.filtered
|
||||
? Filter.apply(direct.value, Filter.parse(filter))
|
||||
? {
|
||||
evidence_id: direct.value.evidence_id,
|
||||
normalized_result: {
|
||||
graph: {
|
||||
nodes: normalized.graph.nodes
|
||||
.slice(0, 1)
|
||||
.map(({ node_id }) => ({ node_id })),
|
||||
},
|
||||
},
|
||||
}
|
||||
: direct.value,
|
||||
);
|
||||
if (scenario.filtered)
|
||||
expect(normalized.graph.nodes.length).toBeGreaterThan(0);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -123,3 +137,67 @@ cliTest(
|
||||
expect(output.json).toEqual({});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"honors caller-selected semantic node limits across files and records them in Evidence",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-node-budgets-");
|
||||
await writeFile(join(root, "first.js"), "external;\n".repeat(40));
|
||||
await writeFile(join(root, "second.js"), "another;\n".repeat(40));
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--format",
|
||||
"json",
|
||||
"--max-semantic-nodes",
|
||||
"50",
|
||||
"--max-semantic-nodes-per-file",
|
||||
"30",
|
||||
],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const result = z
|
||||
.object({
|
||||
parameters: z.object({
|
||||
max_semantic_nodes: z.number(),
|
||||
max_semantic_nodes_per_file: z.number(),
|
||||
}),
|
||||
normalized_result: z.object({
|
||||
semantic_graph: z.object({
|
||||
nodes: z.array(
|
||||
z.object({ identity: z.object({ module_path: z.string() }) }),
|
||||
),
|
||||
coverage: z.object({
|
||||
truncated: z.boolean(),
|
||||
omitted_nodes: z.number().nullable(),
|
||||
limits: z.array(
|
||||
z.object({ name: z.string(), value: z.number() }),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(output.json);
|
||||
expect(result.parameters).toEqual({
|
||||
max_semantic_nodes: 50,
|
||||
max_semantic_nodes_per_file: 30,
|
||||
});
|
||||
const graph = result.normalized_result.semantic_graph;
|
||||
expect(graph.nodes).toHaveLength(50);
|
||||
expect(
|
||||
graph.nodes.filter((node) => node.identity.module_path === "first.js"),
|
||||
).toHaveLength(30);
|
||||
expect(
|
||||
graph.nodes.filter((node) => node.identity.module_path === "second.js"),
|
||||
).toHaveLength(20);
|
||||
expect(graph.coverage.truncated).toBe(true);
|
||||
expect(graph.coverage.omitted_nodes).toBeNull();
|
||||
expect(graph.coverage.limits).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ name: "semantic_graph_node_ceiling", value: 50 },
|
||||
{ name: "semantic_graph_file_node_ceiling", value: 30 },
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
|
||||
@@ -6,33 +6,33 @@ import {
|
||||
typeScriptDialectCases,
|
||||
createTypeScriptDialectArtifact,
|
||||
expectTypeScriptDialectReference,
|
||||
expectValidTypeScriptInput,
|
||||
} from "../../fixtures/javascriptArtifactTypeScriptDialect.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const format of ["directory", "asar"] as const) {
|
||||
for (const command of ["analyze-javascript-application", "analyze"]) {
|
||||
cliTest(
|
||||
`${command} retains TypeScript dialect reference facts for ${format}`,
|
||||
async ({ cli }) => {
|
||||
for (const fixture of typeScriptDialectCases)
|
||||
await expectValidTypeScriptInput(fixture.path, fixture.source);
|
||||
const input = await createTypeScriptDialectArtifact(
|
||||
format,
|
||||
typeScriptDialectCases,
|
||||
);
|
||||
const output = await cli.run({ arguments: [command, input, "--json"] });
|
||||
expect(output.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
expect(result.statistics).toMatchObject({
|
||||
parse_failures: 0,
|
||||
invalid_utf8_files: 0,
|
||||
});
|
||||
for (const fixture of typeScriptDialectCases)
|
||||
expectTypeScriptDialectReference(result.graph, fixture);
|
||||
},
|
||||
);
|
||||
}
|
||||
// These complementary rows cover both CLI adapters and carrier formats; both
|
||||
// adapters enter the same JavaScript application workflow.
|
||||
for (const { command, format } of [
|
||||
{ command: "analyze-javascript-application", format: "asar" },
|
||||
{ command: "analyze", format: "directory" },
|
||||
] as const) {
|
||||
cliTest(
|
||||
`${command} retains TypeScript dialect reference facts for ${format}`,
|
||||
async ({ cli }) => {
|
||||
const input = await createTypeScriptDialectArtifact(
|
||||
format,
|
||||
typeScriptDialectCases,
|
||||
);
|
||||
const output = await cli.run({ arguments: [command, input, "--json"] });
|
||||
expect(output.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
expect(result.statistics).toMatchObject({
|
||||
parse_failures: 0,
|
||||
invalid_utf8_files: 0,
|
||||
});
|
||||
for (const fixture of typeScriptDialectCases)
|
||||
expectTypeScriptDialectReference(result.graph, fixture);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const runtimeSource = (
|
||||
runtime: string,
|
||||
name: string,
|
||||
entry = 1,
|
||||
dependency = 2,
|
||||
) => `
|
||||
globalThis.${runtime}.push([["main"], {
|
||||
${String(entry)}: (module, exports, req) => {
|
||||
req(${String(dependency)}); req.e("lazy"); fetch("/${name}");
|
||||
localStorage.setItem("${name}", "value");
|
||||
const { BrowserWindow } = require("electron"); new BrowserWindow({});
|
||||
},
|
||||
${String(dependency)}: (module) => { module.exports = "${name}"; }
|
||||
}, (req) => req(${String(entry)})]);
|
||||
globalThis.${runtime}.push([["lazy"], {9: () => {}}]);
|
||||
`;
|
||||
|
||||
const appA = runtimeSource("webpackChunkAppA", "a");
|
||||
const appB = runtimeSource("webpackChunkAppB", "b");
|
||||
|
||||
cliTest(
|
||||
"keeps source-derived runtime, module and chunk tuples collision-free",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-bundler-runtime-tuple-");
|
||||
const registrations = [
|
||||
{
|
||||
runtime: "webpackChunkA",
|
||||
module: "x\0y",
|
||||
chunk: "x\0lazy",
|
||||
endpoint: "/a",
|
||||
},
|
||||
{
|
||||
runtime: "webpackChunkA\0x",
|
||||
module: "y",
|
||||
chunk: "lazy",
|
||||
endpoint: "/b",
|
||||
},
|
||||
];
|
||||
const source = registrations
|
||||
.map(
|
||||
({ runtime, module, chunk, endpoint }) => `
|
||||
globalThis[${JSON.stringify(runtime)}].push([["main"], {
|
||||
[${JSON.stringify(module)}]: (m, e, req) => { fetch(${JSON.stringify(endpoint)}); req.e(${JSON.stringify(chunk)}); }
|
||||
}, (req) => req(${JSON.stringify(module)})]);
|
||||
globalThis[${JSON.stringify(runtime)}].push([[${JSON.stringify(chunk)}], {}]);
|
||||
`,
|
||||
)
|
||||
.join("\n");
|
||||
await writeFixtureFiles(root, { "bundle.js": source });
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
for (const { runtime, module, chunk, endpoint } of registrations) {
|
||||
const entry = graph.edges.find(
|
||||
(edge) =>
|
||||
edge.properties.kind === "bundler-entry-module" &&
|
||||
edge.properties.runtime === runtime,
|
||||
);
|
||||
expect(nodes.get(entry?.target_node_id ?? "")?.identity).toMatchObject({
|
||||
namespace: `${runtime}:module`,
|
||||
key: module,
|
||||
});
|
||||
const call = graph.edges.find(
|
||||
(edge) =>
|
||||
edge.relation === "calls" &&
|
||||
nodes.get(edge.target_node_id)?.observations[0]?.properties.value ===
|
||||
endpoint,
|
||||
);
|
||||
expect(call?.source_node_id).toBe(entry?.target_node_id);
|
||||
const lazy = graph.edges.find(
|
||||
(edge) =>
|
||||
edge.source_node_id === entry?.target_node_id &&
|
||||
edge.properties.specifier === `chunk:${chunk}`,
|
||||
);
|
||||
expect(
|
||||
nodes.get(lazy?.target_node_id ?? "")?.observations[0]?.properties,
|
||||
).toMatchObject({ runtime, chunk_keys: [chunk] });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
for (const scenario of [
|
||||
{
|
||||
name: "colliding module IDs",
|
||||
source: appA + appB,
|
||||
runtimes: ["webpackChunkAppA", "webpackChunkAppB"],
|
||||
keys: [1, 1],
|
||||
},
|
||||
{
|
||||
name: "reversed registrations",
|
||||
source: appB + appA,
|
||||
runtimes: ["webpackChunkAppA", "webpackChunkAppB"],
|
||||
keys: [1, 1],
|
||||
},
|
||||
{
|
||||
name: "single runtime",
|
||||
source: appA,
|
||||
runtimes: ["webpackChunkAppA"],
|
||||
keys: [1],
|
||||
},
|
||||
{
|
||||
name: "disjoint module IDs",
|
||||
source: appA + runtimeSource("webpackChunkAppB", "b", 3, 4),
|
||||
runtimes: ["webpackChunkAppA", "webpackChunkAppB"],
|
||||
keys: [1, 3],
|
||||
},
|
||||
{
|
||||
name: "Webpack and Rspack collision",
|
||||
source: appA + runtimeSource("rspackChunkAppB", "b"),
|
||||
runtimes: ["webpackChunkAppA", "rspackChunkAppB"],
|
||||
keys: [1, 1],
|
||||
},
|
||||
]) {
|
||||
cliTest(
|
||||
`keeps bundled relationships within their runtime for ${scenario.name}`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-bundler-runtime-scope-");
|
||||
await writeFixtureFiles(root, { "bundle.js": scenario.source });
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
for (const [index, runtime] of scenario.runtimes.entries()) {
|
||||
const name = index === 0 ? "a" : "b";
|
||||
const key = String(scenario.keys[index]);
|
||||
const module = graph.nodes.find(
|
||||
(node) =>
|
||||
node.identity.strategy === "artifact-local-key" &&
|
||||
node.identity.namespace === `${runtime}:module` &&
|
||||
node.identity.key === key,
|
||||
);
|
||||
expect(module).toBeDefined();
|
||||
const entry = graph.edges.find(
|
||||
(edge) =>
|
||||
edge.properties.kind === "bundler-entry-module" &&
|
||||
edge.properties.runtime === runtime,
|
||||
);
|
||||
expect(entry?.target_node_id).toBe(module?.node_id);
|
||||
expect(entry?.properties.resolution_status).toBe("resolved");
|
||||
const ownedEdges = graph.edges.filter(
|
||||
(edge) => edge.source_node_id === module?.node_id,
|
||||
);
|
||||
expect(
|
||||
ownedEdges.find(
|
||||
(edge) =>
|
||||
edge.relation === "calls" &&
|
||||
nodes.get(edge.target_node_id)?.observations[0]?.properties
|
||||
.value === `/${name}`,
|
||||
),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
ownedEdges.find(
|
||||
(edge) =>
|
||||
edge.relation === "persists_to" &&
|
||||
nodes.get(edge.target_node_id)?.observations[0]?.properties
|
||||
.name === name,
|
||||
),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
ownedEdges.find(
|
||||
(edge) =>
|
||||
edge.relation === "contains" &&
|
||||
nodes.get(edge.target_node_id)?.kind === "browser-window",
|
||||
),
|
||||
).toBeDefined();
|
||||
const dependency = ownedEdges.find(
|
||||
(edge) =>
|
||||
edge.properties.kind === "require" &&
|
||||
edge.properties.specifier === String(Number(key) + 1),
|
||||
);
|
||||
expect(
|
||||
nodes.get(dependency?.target_node_id ?? "")?.identity,
|
||||
).toMatchObject({
|
||||
namespace: `${runtime}:module`,
|
||||
key: String(Number(key) + 1),
|
||||
});
|
||||
const lazy = ownedEdges.find(
|
||||
(edge) => edge.properties.specifier === "chunk:lazy",
|
||||
);
|
||||
expect(
|
||||
nodes.get(lazy?.target_node_id ?? "")?.observations[0]?.properties,
|
||||
).toMatchObject({ runtime, chunk_keys: ["lazy"] });
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"shares module IDs across chunks only within the same runtime",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-bundler-shared-runtime-");
|
||||
await writeFixtureFiles(root, {
|
||||
"bundle.js": `
|
||||
globalThis.webpackChunkApp.push([["main"], {1: (module, exports, req) => { req(2); }} , (req) => req(1)]);
|
||||
globalThis.webpackChunkApp.push([["other"], {2: (module) => { module.exports = "dependency"; }}]);
|
||||
`,
|
||||
});
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const module = (key: string) =>
|
||||
graph.nodes.find(
|
||||
(node) =>
|
||||
node.identity.strategy === "artifact-local-key" &&
|
||||
node.identity.namespace === "webpackChunkApp:module" &&
|
||||
node.identity.key === key,
|
||||
);
|
||||
expect(
|
||||
graph.edges.find(
|
||||
(edge) =>
|
||||
edge.properties.kind === "require" &&
|
||||
edge.properties.specifier === "2",
|
||||
),
|
||||
).toMatchObject({
|
||||
source_node_id: module("1")?.node_id,
|
||||
target_node_id: module("2")?.node_id,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -11,6 +11,78 @@ import {
|
||||
writeFixtureFiles,
|
||||
} from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
cliTest(
|
||||
"resolves emitted module imports without substituting Electron runtime paths",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-typescript-runtime-paths-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": JSON.stringify({ main: "main.ts" }),
|
||||
"main.ts": `import { BrowserWindow, utilityProcess } from "electron";
|
||||
import "./worker.js";
|
||||
import "./config.mjs";
|
||||
import "./legacy.cjs";
|
||||
import "./view.js";
|
||||
import "./runtime.js";
|
||||
const win = new BrowserWindow({webPreferences:{preload:"./worker.js"}});
|
||||
win.loadURL("./renderer.js");
|
||||
utilityProcess.fork("./worker.js");
|
||||
utilityProcess.fork("./runtime.js");
|
||||
throw new Error("source must stay inert");`,
|
||||
"worker.ts": "export const worker = 1;",
|
||||
"config.mts": "export const config = 1;",
|
||||
"legacy.cts": "export const legacy = 1;",
|
||||
"view.tsx": "export const view = <div />;",
|
||||
"renderer.ts": "export const renderer = 1;",
|
||||
"runtime.ts": "export const source = 1;",
|
||||
"runtime.js": "throw new Error('runtime must stay inert');",
|
||||
});
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const { graph } = result;
|
||||
const source = findSourceModule(graph, "main.ts");
|
||||
for (const [specifier, target] of [
|
||||
["./worker.js", "worker.ts"],
|
||||
["./config.mjs", "config.mts"],
|
||||
["./legacy.cjs", "legacy.cts"],
|
||||
["./view.js", "view.tsx"],
|
||||
["./runtime.js", "runtime.js"],
|
||||
] as const)
|
||||
expect(
|
||||
findGraphEdge(graph, source, findSourceModule(graph, target), "imports")
|
||||
?.properties,
|
||||
).toMatchObject({ specifier, resolved_path: target });
|
||||
expect(result.summary).toMatchObject({
|
||||
utility_processes: 2,
|
||||
resolved_utility_entrypoints: 1,
|
||||
});
|
||||
expect(
|
||||
graph.edges.find(
|
||||
(edge) =>
|
||||
edge.evidence.extractor.operation ===
|
||||
"associate-browser-window-preload",
|
||||
)?.properties,
|
||||
).toMatchObject({
|
||||
declared_path: "./worker.js",
|
||||
resolved_path: null,
|
||||
resolution_status: "not-found",
|
||||
});
|
||||
expect(
|
||||
graph.edges
|
||||
.filter(
|
||||
(edge) =>
|
||||
edge.properties.declared_path === "./worker.js" ||
|
||||
edge.properties.declared_path === "./renderer.js",
|
||||
)
|
||||
.some((edge) => edge.properties.resolved_path != null),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"returns literal self-import evidence while preserving sibling imports and self-re-exports",
|
||||
async ({ cli }) => {
|
||||
@@ -75,7 +147,7 @@ cliTest(
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discloses CommonJS and TypeScript self-imports while retaining unresolved extension rewrites",
|
||||
"discloses CommonJS and TypeScript self-imports including emitted-name rewrites",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-self-require-");
|
||||
await writeFixtureFiles(root, {
|
||||
@@ -94,8 +166,10 @@ cliTest(
|
||||
expect(
|
||||
graph.edges.filter((edge) => edge.source_node_id === edge.target_node_id),
|
||||
).toEqual([]);
|
||||
// ./util.ts is a literal self-import and ./util.js resolves under NodeNext
|
||||
// emitted-name semantics back to util.ts itself, as ./c.cjs does for CJS.
|
||||
expect(graph.limitations).toContainEqual(
|
||||
expect.stringMatching(/^2 import specifiers .*were omitted;/u),
|
||||
expect.stringMatching(/^3 import specifiers .*were omitted;/u),
|
||||
);
|
||||
expect(result.limitations).toEqual(
|
||||
expect.arrayContaining(graph.limitations),
|
||||
@@ -128,12 +202,21 @@ cliTest(
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
graph.edges.find(
|
||||
graph.edges.some(
|
||||
(edge) =>
|
||||
edge.source_node_id === findSourceModule(graph, "util.ts")?.node_id &&
|
||||
edge.properties.specifier === "./util.js" &&
|
||||
edge.properties.module_link_kind === "import",
|
||||
)?.properties,
|
||||
).toMatchObject({ resolved_path: null, resolution_status: "not-found" });
|
||||
(edge.properties.module_link_kind === "import" ||
|
||||
edge.properties.resolution_status === "not-found"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
graph.nodes.some((node) =>
|
||||
node.observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "module-reference" &&
|
||||
properties.declared_specifier === "./util.js",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { serveCli } from "./cliServeHarness.js";
|
||||
|
||||
const jebEnvironment = {
|
||||
REA_JEB_MCP_URL: "http://127.0.0.1:1/mcp",
|
||||
};
|
||||
|
||||
const serve = async (
|
||||
argv: readonly string[],
|
||||
): Promise<{ readonly stdout: string; readonly exitCode: number }> =>
|
||||
serveCli(argv, jebEnvironment);
|
||||
|
||||
it("reports an unreachable engine endpoint with recovery guidance", async () => {
|
||||
const result = await serve(["inspect-jeb-client", "--json"]);
|
||||
expect(result.stdout).toContain("capability_unavailable");
|
||||
expect(result.stdout).toContain("REA_JEB_MCP_URL");
|
||||
});
|
||||
|
||||
it("validates decompile item input before contacting the engine", async () => {
|
||||
const result = await serve(["decompile-jeb-item", "", "method", "--json"]);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
{
|
||||
code: "too_small",
|
||||
path: "item-address",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an invalid endpoint without breaking other commands", async () => {
|
||||
const environment = { REA_JEB_MCP_URL: "http://localhost:8425/mcp" };
|
||||
const jeb = await serveCli(["inspect-jeb-client", "--json"], environment);
|
||||
expect(JSON.parse(jeb.stdout)).toMatchObject({
|
||||
code: "configuration_invalid",
|
||||
details: { settings: [{ setting: "REA_JEB_MCP_URL" }] },
|
||||
});
|
||||
const capabilities = await serveCli(["capabilities", "--json"], environment);
|
||||
expect(capabilities.exitCode).toBe(0);
|
||||
});
|
||||
@@ -8,23 +8,18 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"rejects malformed oversized CLI input and preserves Evidence decoder resource failures",
|
||||
"rejects malformed oversized JSON through both CLI and Evidence readers",
|
||||
async ({ cli, processes }) => {
|
||||
const root = await createTestTempDirectory("rea-json-string-limit-");
|
||||
const input = join(root, "oversized.json");
|
||||
const file = await open(input, "wx");
|
||||
try {
|
||||
// Sparse zero bytes are valid UTF-8. The Evidence reader reaches the
|
||||
// decoded-length limit; the streamed CLI rejects their invalid JSON syntax.
|
||||
// Sparse zero bytes are valid UTF-8 but invalid JSON. Both readers
|
||||
// stream the input and reject the syntax before assembling a value.
|
||||
await file.truncate(constants.MAX_STRING_LENGTH + 1);
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
const limits = {
|
||||
input_path: input,
|
||||
input_bytes: constants.MAX_STRING_LENGTH + 1,
|
||||
max_string_code_units: constants.MAX_STRING_LENGTH,
|
||||
};
|
||||
// Run readers sequentially in owned child processes, releasing each large
|
||||
// read buffer when its process exits instead of retaining it in Vitest.
|
||||
const result = await cli.run({
|
||||
@@ -48,11 +43,11 @@ cliTest(
|
||||
input,
|
||||
]);
|
||||
expect(JSON.parse(evidence.stdout)).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
code: "evidence_integrity_mismatch",
|
||||
details: {
|
||||
operation: "read_evidence_file",
|
||||
resource: "memory",
|
||||
reported_limits: limits,
|
||||
operation: "read",
|
||||
reason: "invalid-json",
|
||||
path: input,
|
||||
},
|
||||
});
|
||||
expect(evidence.stderr).toBe("");
|
||||
@@ -121,6 +116,63 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"returns a typed container assembly constraint and allows a following read",
|
||||
async ({ cli, processes }) => {
|
||||
const root = await createTestTempDirectory("rea-json-container-headroom-");
|
||||
const input = join(root, "containers.json");
|
||||
const following = join(root, "following.json");
|
||||
const file = await open(input, "wx");
|
||||
try {
|
||||
await file.writeFile("[");
|
||||
const chunk = Buffer.from("[],".repeat(65_536));
|
||||
for (let index = 0; index < 128; index++) await file.writeFile(chunk);
|
||||
await file.writeFile("null]");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
await writeFile(following, '{"after":true}');
|
||||
const result = await cli.run({
|
||||
arguments: ["trace-application-feature", input, "--json"],
|
||||
environment: { NODE_OPTIONS: "--max-old-space-size=768" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.json).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
resource: "memory",
|
||||
reported_limits: {
|
||||
input_path: input,
|
||||
projected_value_bytes: expect.any(Number),
|
||||
assembly_headroom_bytes: expect.any(Number),
|
||||
},
|
||||
},
|
||||
});
|
||||
const evidence = await processes.run(process.execPath, [
|
||||
"--max-old-space-size=768",
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`import { readJsonFile } from "./dist/application/JsonFiles.js";
|
||||
import { projectAnalysisError } from "./dist/domain/analysisErrorProjection.js";
|
||||
const large = await readJsonFile(process.argv[1]);
|
||||
const following = await readJsonFile(process.argv[2]);
|
||||
console.log(JSON.stringify({large: large.ok ? large : projectAnalysisError(large.error), following}));`,
|
||||
input,
|
||||
following,
|
||||
]);
|
||||
expect(evidence.exitCode).toBe(0);
|
||||
expect(evidence.stderr).toBe("");
|
||||
expect(JSON.parse(evidence.stdout)).toMatchObject({
|
||||
large: {
|
||||
code: "resource_constraint",
|
||||
details: { reported_limits: { input_path: input } },
|
||||
},
|
||||
following: { ok: true, value: { after: true } },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"returns a typed string assembly constraint under a bounded heap",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
expectKeyedArchivePrototypeKeys,
|
||||
keyedArchivePrototypeKeyFixture,
|
||||
} from "../../fixtures/keyedArchivePrototypeKeys.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"compiled CLI decodes formatted XML prototype keys",
|
||||
async ({ cli }) => {
|
||||
const fixture = await keyedArchivePrototypeKeyFixture();
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", fixture.path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
expectKeyedArchivePrototypeKeys(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
fixture.digest,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -44,15 +44,20 @@ describe.skipIf(process.platform !== "darwin")(
|
||||
});
|
||||
|
||||
cliTest("rejects a symbol spanning lines as input", async ({ cli }) => {
|
||||
const missingTarget = join(
|
||||
await createTestTempDirectory("rea-demangle-invalid-input-"),
|
||||
"absent",
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"demangle-swift",
|
||||
await evidenceTarget(),
|
||||
missingTarget,
|
||||
"$s4main3FooV",
|
||||
"$s4main\n3FooV",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({ code: "VALIDATION_ERROR" });
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { packageRunnerRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const ompConfigurationSchema = z.object({
|
||||
mcpServers: z.object({
|
||||
rea: z.object({ command: z.string(), args: z.array(z.string()) }),
|
||||
}),
|
||||
});
|
||||
|
||||
// Package runners set these variables for the bin they launch from a temporary cache.
|
||||
for (const { runner, userAgent } of [
|
||||
{ runner: "npx", userAgent: "npm/10.9.0 node/v24.11.0 linux x64" },
|
||||
{ runner: "bunx", userAgent: "bun/1.4.2 npm/? node/v26.3.0 linux x64" },
|
||||
] as const) {
|
||||
cliTest(
|
||||
`${runner} setup registers the pinned ${runner} launcher instead of its cache`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-package-runner-");
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
npm_command: "exec",
|
||||
npm_config_user_agent: userAgent,
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
const setup = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
"omp",
|
||||
"--no-skill",
|
||||
"--yes",
|
||||
"--json",
|
||||
]);
|
||||
expect(setup.exitCode).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
const configuration = ompConfigurationSchema.parse(
|
||||
JSON.parse(
|
||||
await readFile(join(home, ".omp", "agent", "mcp.json"), "utf8"),
|
||||
),
|
||||
);
|
||||
const { command, args } = configuration.mcpServers.rea;
|
||||
expect([command, ...args]).toEqual(
|
||||
packageRunnerRegistrationCommand(runner, process.platform),
|
||||
);
|
||||
const doctor = await run(["doctor", "--client", "omp", "--json"]);
|
||||
expect(doctor.json).toMatchObject({
|
||||
identity: { registrations: [{ client: "omp", state: "aligned" }] },
|
||||
});
|
||||
const repeat = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
"omp",
|
||||
"--no-skill",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
]);
|
||||
expect(repeat.json).toMatchObject({ plannedActions: [] });
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"rejects a headerless image until architecture and entry are supplied",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const before = await cli.run({
|
||||
arguments: ["inspect", path, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(before.exitCode).not.toBe(0);
|
||||
expect(JSON.stringify(before.json)).not.toContain("raw-binary");
|
||||
const missing = await cli.run({
|
||||
arguments: ["inspect", path, "--target-format", "raw-binary", "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(missing.exitCode).toBe(1);
|
||||
expect(missing.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { reason: expect.stringContaining("architecture") },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects an unaligned AArch64 entry before provider startup",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-alignment-");
|
||||
const path = join(root, "image.bin");
|
||||
await writeFile(path, Buffer.from("c0035fd6", "hex"));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm64",
|
||||
"--entry-point",
|
||||
"0x8000001",
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--json",
|
||||
],
|
||||
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { reason: expect.stringContaining("must be 4-byte aligned") },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"stops Hopper from claiming a caller-supplied raw-binary image",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-hopper-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm",
|
||||
"--entry-point",
|
||||
"0x8000000",
|
||||
"--provider",
|
||||
"hopper",
|
||||
"--json",
|
||||
],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.stringify(result.json)).toMatch(/Hopper|ghidra|Ghidra|hopper/i);
|
||||
expect(JSON.stringify(result.json)).not.toMatch(
|
||||
/unsupported binary format/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,66 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"compiled reference-source exclusion provenance",
|
||||
() => {
|
||||
cliTest(
|
||||
"reports project, default, and explicit secret exclusions",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-reference-exclusions-");
|
||||
const logs = join(root, "logs");
|
||||
await mkdir(logs);
|
||||
await Promise.all([
|
||||
writeFile(join(root, ".gitignore"), "project.tmp\n"),
|
||||
writeFile(join(root, "project.tmp"), "project policy\n"),
|
||||
writeFile(join(logs, "application.log"), "default policy\n"),
|
||||
writeFile(join(root, "private.txt"), "sensitive local file\n"),
|
||||
writeFile(join(root, "source.ts"), "export const value = 1;\n"),
|
||||
]);
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["import-reference-source", root, "--json"],
|
||||
cwd: root,
|
||||
environment: {
|
||||
HOME: root,
|
||||
USERPROFILE: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
REA_REFERENCE_SECRET_PATTERNS_JSON: '["private.txt"]',
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const graph = historicalSourceGraphSchema.parse(result.json);
|
||||
expect(graph.exclusions).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
path: "project.tmp",
|
||||
reason: "project-ignored",
|
||||
pattern: "project.tmp",
|
||||
},
|
||||
{
|
||||
path: "logs/application.log",
|
||||
reason: "default-ignored",
|
||||
pattern: "*.log",
|
||||
},
|
||||
{
|
||||
path: "private.txt",
|
||||
reason: "configured-secret",
|
||||
pattern: "private.txt",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(graph.entries).toContainEqual(
|
||||
expect.objectContaining({ path: "source.ts", kind: "file" }),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
@@ -6,20 +6,17 @@ import { describe, expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const invalidRootOutput = {
|
||||
error: "Import failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
|
||||
};
|
||||
|
||||
const unsupportedHostOutput = {
|
||||
error: "Import failed",
|
||||
category: "unsupported_host",
|
||||
message:
|
||||
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
|
||||
message: expect.stringContaining(
|
||||
"Safe no-follow file opens are unavailable on this host.",
|
||||
),
|
||||
};
|
||||
|
||||
const permissionChecksUnavailable =
|
||||
process.platform === "win32" || process.getuid?.() === 0;
|
||||
|
||||
describe("compiled Windows reference-source import", () => {
|
||||
for (const scenario of [
|
||||
{ fullOutput: false, logging: false },
|
||||
@@ -83,7 +80,11 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-reference-cli-status-",
|
||||
);
|
||||
const root = join(directory, "input");
|
||||
// Exercise JSON escaping on POSIX too; Windows paths already need it.
|
||||
const root = join(
|
||||
directory,
|
||||
process.platform === "win32" ? "input" : "input\\escaped",
|
||||
);
|
||||
if (scenario.rootKind === "regular-file")
|
||||
await writeFile(root, "inert input\n");
|
||||
const result = await cli.run({
|
||||
@@ -102,6 +103,15 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
...(scenario.logging ? { REA_LOG_LEVEL: "info" } : {}),
|
||||
},
|
||||
});
|
||||
const rootReason =
|
||||
scenario.rootKind === "missing"
|
||||
? "Reference source root could not be resolved"
|
||||
: "Reference source root is not a directory";
|
||||
const invalidRootOutput = {
|
||||
error: "Import failed",
|
||||
category: "invalid_input",
|
||||
message: expect.stringContaining(rootReason),
|
||||
};
|
||||
if (scenario.fullOutput) {
|
||||
// Incur's legacy wrapper remains unchanged; operation status is
|
||||
// conveyed by the exit code and command log, not this `ok` field.
|
||||
@@ -110,8 +120,19 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
data: invalidRootOutput,
|
||||
});
|
||||
} else {
|
||||
expect(result.json).toEqual(invalidRootOutput);
|
||||
expect(result.json).toMatchObject(invalidRootOutput);
|
||||
}
|
||||
const messagePath = scenario.fullOutput ? "data.message" : "message";
|
||||
expect(result.json).toHaveProperty(
|
||||
messagePath,
|
||||
expect.stringContaining(
|
||||
"Check that the path exists, is readable, and points to a directory.",
|
||||
),
|
||||
);
|
||||
expect(result.json).toHaveProperty(
|
||||
messagePath,
|
||||
expect.stringContaining(root),
|
||||
);
|
||||
expect.soft(result.exitCode).toBe(1);
|
||||
if (scenario.logging) {
|
||||
const records: unknown[] = result.stderr
|
||||
@@ -132,4 +153,45 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest.skipIf(permissionChecksUnavailable)(
|
||||
"classifies a blocked parent directory as an execution failure",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-reference-cli-blocked-root-",
|
||||
);
|
||||
const parent = join(directory, "blocked-parent");
|
||||
const root = join(parent, "input");
|
||||
await mkdir(root, { recursive: true });
|
||||
await chmod(parent, 0);
|
||||
try {
|
||||
const result = await cli.run({
|
||||
arguments: ["import-reference-source", root, "--json"],
|
||||
cwd: directory,
|
||||
environment: {
|
||||
HOME: directory,
|
||||
USERPROFILE: directory,
|
||||
XDG_CONFIG_HOME: directory,
|
||||
XDG_CACHE_HOME: directory,
|
||||
},
|
||||
});
|
||||
expect(result.json).toMatchObject({
|
||||
error: "Import failed",
|
||||
category: "execution_failure",
|
||||
message: expect.stringContaining("EACCES: permission denied"),
|
||||
});
|
||||
expect(result.json).toHaveProperty(
|
||||
"message",
|
||||
expect.stringContaining(root),
|
||||
);
|
||||
expect(result.json).toHaveProperty(
|
||||
"message",
|
||||
expect.stringContaining("Check directory permissions and try again."),
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
} finally {
|
||||
await chmod(parent, 0o700);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import { projectAnalysisError } from "../../../src/domain/analysisErrorProjectio
|
||||
import { evmInterfaceSchema } from "../../../src/domain/evm/evmInterface.js";
|
||||
import { EvmoleInterfaceProvider } from "../../../src/evm/EvmoleInterfaceProvider.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
@@ -128,31 +129,75 @@ it.runIf(!unsupportedHost)(
|
||||
async () => {
|
||||
const { path } = await fixture();
|
||||
let ownedPath = "";
|
||||
let failCleanup = true;
|
||||
let launches = 0;
|
||||
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
|
||||
launches += 1;
|
||||
ownedPath = spawn.cwd ?? "";
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
command: process.execPath,
|
||||
arguments: ["-e", 'process.stdout.write("x".repeat(1048577))'],
|
||||
});
|
||||
const cleanupOwned =
|
||||
launched.cleanup ??
|
||||
(() => cleanupOwnedProcessGroup(launched.ownership));
|
||||
return {
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
await launched.cleanup?.();
|
||||
throw new Error("injected post-cleanup reporting failure");
|
||||
const cleaned = await cleanupOwned();
|
||||
if (failCleanup)
|
||||
throw new Error("injected post-cleanup reporting failure");
|
||||
return cleaned;
|
||||
},
|
||||
};
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
failCleanup = false;
|
||||
await provider.close();
|
||||
});
|
||||
const result = await provider.inspect({ path, encoding: "hex" });
|
||||
if (result.ok) throw new Error("Expected compounded lifecycle failure");
|
||||
expect(result.error).toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: {
|
||||
reason: "injected post-cleanup reporting failure",
|
||||
previous_error: { failure_kind: "output-limit" },
|
||||
captured_output: { truncated: true, stderr: "" },
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
// Inspect the retained error chain without diffing a megabyte of stdout.
|
||||
const cleanup = z
|
||||
.object({
|
||||
reason: z.string(),
|
||||
previous_error: z
|
||||
.object({
|
||||
failure_kind: z.string(),
|
||||
stdout: z.unknown().optional(),
|
||||
stderr: z.unknown().optional(),
|
||||
})
|
||||
.transform(({ failure_kind, stdout, stderr }) => ({
|
||||
failure_kind,
|
||||
output_repeated: stdout !== undefined || stderr !== undefined,
|
||||
})),
|
||||
captured_output: z.object({
|
||||
truncated: z.boolean(),
|
||||
stderr: z.literal(""),
|
||||
stdout: z.string().transform((value) => Buffer.byteLength(value)),
|
||||
}),
|
||||
})
|
||||
.parse(projectAnalysisError(result.error).details?.["diagnostics"]);
|
||||
expect(cleanup).toEqual({
|
||||
reason: "injected post-cleanup reporting failure",
|
||||
previous_error: {
|
||||
failure_kind: "output-limit",
|
||||
output_repeated: false,
|
||||
},
|
||||
captured_output: { truncated: true, stderr: "", stdout: 1048576 },
|
||||
});
|
||||
expect(result.error.cleanupResources).toContain(ownedPath);
|
||||
await access(ownedPath);
|
||||
const blocked = await provider.inspect({ path, encoding: "hex" });
|
||||
expect(blocked.ok).toBe(false);
|
||||
expect(launches).toBe(1);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
failCleanup = false;
|
||||
await provider.close();
|
||||
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
|
||||
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
@@ -13,6 +15,8 @@ import {
|
||||
import {
|
||||
createAnalysisSnapshotEntry,
|
||||
parseAnalysisSnapshot,
|
||||
parsePreparedAnalysisSnapshot,
|
||||
prepareSnapshotEntry,
|
||||
snapshotBinding,
|
||||
snapshotTarget,
|
||||
type AnalysisSnapshot,
|
||||
@@ -24,21 +28,25 @@ import {
|
||||
} from "../../../src/domain/analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { readJsonObjectFile } from "../../../src/application/JsonInputFile.js";
|
||||
import { RegularFileChangedError } from "../../../src/filesystem/RegularFile.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
|
||||
describe("analysis snapshots: persistence", () => {
|
||||
it("writes canonical private v2 JSON and rejects changed query identity", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-");
|
||||
const path = join(directory, "analysis.json");
|
||||
const target = snapshotTarget(TARGET);
|
||||
const binding = snapshotBinding(PROFILE);
|
||||
const entry = createAnalysisSnapshotEntry({
|
||||
target,
|
||||
binding,
|
||||
operation: "address_name",
|
||||
parameters: { address: "0x1000" },
|
||||
execution: createAnalysisExecution("main", PROVIDER, {
|
||||
const snapshotFixture = (): AnalysisSnapshot => {
|
||||
const target = snapshotTarget(TARGET);
|
||||
const binding = snapshotBinding(PROFILE);
|
||||
const entry = createAnalysisSnapshotEntry({
|
||||
target,
|
||||
binding,
|
||||
operation: "address_name",
|
||||
parameters: { address: "0x1000" },
|
||||
execution: createAnalysisExecution(
|
||||
{ name: "main", "😀": { "\uE000": "unicode" } },
|
||||
PROVIDER,
|
||||
{
|
||||
analysisProfile: PROFILE,
|
||||
rawResult: "main",
|
||||
rawResult: { name: "main", "😀": { "\uE000": "unicode" } },
|
||||
subject: {
|
||||
path: TARGET.path,
|
||||
sha256: TARGET.sha256,
|
||||
@@ -47,27 +55,39 @@ describe("analysis snapshots: persistence", () => {
|
||||
? {}
|
||||
: { architecture: TARGET.architecture }),
|
||||
},
|
||||
}),
|
||||
});
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "address_name",
|
||||
parameters: { address: "0x1000" },
|
||||
result: "main",
|
||||
rawResult: "main",
|
||||
analysisProfile: PROFILE,
|
||||
});
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
target,
|
||||
binding,
|
||||
entries: [entry],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
};
|
||||
const written = await writeAnalysisSnapshot(snapshot, path, false);
|
||||
expect(written.ok).toBe(true);
|
||||
},
|
||||
),
|
||||
});
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "address_name",
|
||||
parameters: { address: "0x1000" },
|
||||
result: { name: "main", "😀": { "\uE000": "unicode" } },
|
||||
rawResult: { name: "main", "😀": { "\uE000": "unicode" } },
|
||||
analysisProfile: PROFILE,
|
||||
});
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
target,
|
||||
binding,
|
||||
entries: [entry],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
};
|
||||
return snapshot;
|
||||
};
|
||||
|
||||
describe("analysis snapshots: persistence", () => {
|
||||
it("writes canonical private v2 JSON and rejects changed query identity", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-");
|
||||
const path = join(directory, "analysis.json");
|
||||
const snapshot = snapshotFixture();
|
||||
const written = await withArtifactResourceScope((resources) =>
|
||||
writeAnalysisSnapshot(snapshot, path, false, resources),
|
||||
);
|
||||
if (!written.ok) throw written.error;
|
||||
expect((await readFile(path, "utf8")).endsWith("\n")).toBe(true);
|
||||
expect((await stat(path)).mode & 0o777).toBe(0o600);
|
||||
expect((await readAnalysisSnapshot(path)).ok).toBe(true);
|
||||
const roundTrip = await readAnalysisSnapshot(path);
|
||||
if (!roundTrip.ok) throw roundTrip.error;
|
||||
|
||||
const altered: unknown = JSON.parse(await readFile(path, "utf8"));
|
||||
if (
|
||||
@@ -89,8 +109,231 @@ describe("analysis snapshots: persistence", () => {
|
||||
Reflect.set(first.parameters, "address", "0x2000");
|
||||
await writeFile(path, JSON.stringify(altered));
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
expect(loaded.ok).toBe(false);
|
||||
if (!loaded.ok) expect(loaded.error._tag).toBe("EvidenceIntegrityError");
|
||||
if (loaded.ok)
|
||||
throw new Error("Expected changed snapshot identity rejection");
|
||||
expect(loaded.error._tag).toBe("EvidenceIntegrityError");
|
||||
expect(() => parseAnalysisSnapshot(altered)).toThrow(/identifier/u);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis snapshot member decoding", () => {
|
||||
it("restores reordered legacy members with last-key semantics and authenticated shared payloads", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-members-");
|
||||
const path = join(directory, "snapshot.json");
|
||||
const snapshot = snapshotFixture();
|
||||
const entry = snapshot.entries[0];
|
||||
if (entry === undefined) throw new Error("Missing fixture entry");
|
||||
const parts = [
|
||||
`"evidence_bundle":${JSON.stringify(snapshot.evidence_bundle)}`,
|
||||
'"entries":[{"bad":true}]',
|
||||
'"workflow_entries":null',
|
||||
`"binding":${JSON.stringify(snapshot.binding)}`,
|
||||
`"entries":${JSON.stringify(snapshot.entries)}`,
|
||||
`"target":${JSON.stringify(snapshot.target)}`,
|
||||
'"workflow_entries":[]',
|
||||
'"ignored":{"entries":["nested"]}',
|
||||
];
|
||||
await writeFile(path, `${" ".repeat(9 * 1024 * 1024)}{${parts.join(",")}}`);
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
if (!loaded.ok) throw loaded.error;
|
||||
expect(loaded.value).toEqual(snapshot);
|
||||
const restored = loaded.value.entries[0];
|
||||
const evidence = loaded.value.evidence_bundle.records[0];
|
||||
if (restored === undefined || evidence === undefined)
|
||||
throw new Error("Missing restored content");
|
||||
expect(restored.execution.result).toBe(evidence.normalized_result);
|
||||
expect(restored.execution.raw_result).toBe(evidence.raw_result);
|
||||
expect(Object.isFrozen(restored.execution)).toBe(true);
|
||||
expect(parseAnalysisSnapshot(loaded.value)).toBe(loaded.value);
|
||||
|
||||
await writeFile(
|
||||
path,
|
||||
`${" ".repeat(9 * 1024 * 1024)}{${parts.join(",")},"entries":null}`,
|
||||
);
|
||||
const rejected = await readAnalysisSnapshot(path);
|
||||
expect(rejected).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["result", "raw_result", "limitations", "provider", "query_id"])(
|
||||
"rejects cache %s changes even when bundled Evidence is intact",
|
||||
async (field) => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-tamper-");
|
||||
const path = join(directory, "snapshot.json");
|
||||
const snapshot = snapshotFixture();
|
||||
const entry = snapshot.entries[0];
|
||||
if (entry === undefined) throw new Error("Missing fixture entry");
|
||||
if (field === "query_id") entry.query_id = `query_${"f".repeat(64)}`;
|
||||
else
|
||||
Reflect.set(
|
||||
entry.execution,
|
||||
field,
|
||||
field === "limitations"
|
||||
? ["changed"]
|
||||
: field === "provider"
|
||||
? { ...PROVIDER, version: "changed" }
|
||||
: "changed",
|
||||
);
|
||||
await writeFile(path, JSON.stringify(snapshot));
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
expect(loaded).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
if (!loaded.ok)
|
||||
expect(loaded.error.message).toMatch(
|
||||
field === "query_id"
|
||||
? /identifier/u
|
||||
: field === "provider"
|
||||
? /provider/u
|
||||
: /differs from/u,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("validates skipped JSON syntax and UTF-8 and does not turn missing arrays into empty caches", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-invalid-");
|
||||
const path = join(directory, "snapshot.json");
|
||||
const snapshot = snapshotFixture();
|
||||
const encoded = JSON.stringify(snapshot);
|
||||
for (const bytes of [
|
||||
Buffer.from(`${encoded.slice(0, -1)},"ignored":[1,]}`),
|
||||
Buffer.concat([
|
||||
Buffer.from(`${encoded.slice(0, -1)},"ignored":"`),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
Buffer.from(`\uFEFF${encoded}`),
|
||||
]) {
|
||||
await writeFile(path, bytes);
|
||||
expect(await readAnalysisSnapshot(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
|
||||
});
|
||||
}
|
||||
const { workflow_entries: _workflows, ...missing } = snapshot;
|
||||
await writeFile(path, JSON.stringify(missing));
|
||||
expect(await readAnalysisSnapshot(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns cancellation and permits the next complete read", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-cancel-");
|
||||
const path = join(directory, "snapshot.json");
|
||||
const snapshot = snapshotFixture();
|
||||
await writeFile(
|
||||
path,
|
||||
`${" ".repeat(9 * 1024 * 1024)}${JSON.stringify(snapshot)}`,
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const reads = await holdFirstFileRead(path);
|
||||
onTestFinished(() => {
|
||||
controller.abort();
|
||||
reads.release();
|
||||
});
|
||||
const pending = readAnalysisSnapshot(path, controller.signal);
|
||||
await reads.firstRead;
|
||||
controller.abort();
|
||||
reads.release();
|
||||
try {
|
||||
expect(await pending).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(reads.readCount).toBe(1);
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
if (!loaded.ok) throw loaded.error;
|
||||
expect(loaded.value).toEqual(snapshot);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis snapshot file ownership", () => {
|
||||
it.each([false, true])(
|
||||
"retains the file owner when snapshot close fails (cancelled: %s)",
|
||||
async (cancelDuringClose) => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-cleanup-");
|
||||
const path = join(directory, "snapshot.json");
|
||||
await writeFile(path, JSON.stringify(snapshotFixture()));
|
||||
const controller = new AbortController();
|
||||
const cleanupCause = new Error("injected snapshot file close failure");
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementationOnce(async () => {
|
||||
if (cancelDuringClose) controller.abort();
|
||||
throw cleanupCause;
|
||||
});
|
||||
let failure: unknown;
|
||||
try {
|
||||
try {
|
||||
await readAnalysisSnapshot(
|
||||
path,
|
||||
cancelDuringClose ? controller.signal : undefined,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
if (!(failure instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Expected the retained snapshot file handle owner");
|
||||
expect(failure.cleanupCause).toBe(cleanupCause);
|
||||
expect(failure.owner.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
if (failure instanceof RegularFileCleanupFailure)
|
||||
await failure.owner.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects changed bytes between scans on the same descriptor", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-changed-");
|
||||
const path = join(directory, "input.json");
|
||||
await writeFile(path, `${" ".repeat(9 * 1024 * 1024)}{"value":1}`);
|
||||
const reader = new Map([
|
||||
[
|
||||
"value",
|
||||
{
|
||||
mode: "value" as const,
|
||||
begin: () => undefined,
|
||||
accept: async () => {
|
||||
await writeFile(path, `${" ".repeat(9 * 1024 * 1024)}{"value":2}`);
|
||||
},
|
||||
reject: (cause: unknown) => {
|
||||
throw cause;
|
||||
},
|
||||
},
|
||||
],
|
||||
]);
|
||||
await expect(
|
||||
readJsonObjectFile(path, "test-input", [reader, new Map()]),
|
||||
).rejects.toBeInstanceOf(RegularFileChangedError);
|
||||
expect((await readFile(path, "utf8")).trim()).toBe('{"value":2}');
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects copied preparation handles and prevents mutable caller values from changing authenticated cache content", () => {
|
||||
const snapshot = snapshotFixture();
|
||||
const entry = snapshot.entries[0];
|
||||
if (entry === undefined) throw new Error("Missing fixture entry");
|
||||
const prepared = prepareSnapshotEntry(entry, "provider");
|
||||
const forged = { ...prepared };
|
||||
expect(() => parsePreparedAnalysisSnapshot(snapshot, [forged], [])).toThrow(
|
||||
/not parsed in this realm/u,
|
||||
);
|
||||
const restored = parsePreparedAnalysisSnapshot(snapshot, [prepared], []);
|
||||
Reflect.set(entry.execution, "result", "changed after preparation");
|
||||
expect(restored.entries[0]?.execution.result).toEqual({
|
||||
name: "main",
|
||||
"😀": { "\uE000": "unicode" },
|
||||
});
|
||||
expect(() => parsePreparedAnalysisSnapshot(snapshot, [prepared], [])).toThrow(
|
||||
/not parsed in this realm/u,
|
||||
);
|
||||
});
|
||||
|
||||
+44
-7
@@ -9,16 +9,16 @@ import {
|
||||
} from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
createNonApplicationZipInventory,
|
||||
requireSuccessfulProjection,
|
||||
} from "../../support/applicationSessionFixture.js";
|
||||
} from "../../../support/applicationSessionFixture.js";
|
||||
|
||||
import { projectAndroidApplicationEvidence } from "../../../src/application/android/AndroidApplicationService.js";
|
||||
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
|
||||
import { androidApplicationProjectionResultSchema } from "../../../src/domain/android/androidApplication.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { projectAndroidApplicationEvidence } from "../../../../src/application/android/AndroidApplicationService.js";
|
||||
import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js";
|
||||
import { androidApplicationProjectionResultSchema } from "../../../../src/domain/android/androidApplication.js";
|
||||
import { parseEvidence } from "../../../../src/domain/evidence.js";
|
||||
|
||||
const { runProviderAnalysis } = createDirectAnalysis({});
|
||||
|
||||
@@ -119,7 +119,14 @@ describe("Android application projection", () => {
|
||||
projectAndroidApplicationEvidence({ inventory_evidence: [inventory] }),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining("root format is zip"),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -168,6 +175,36 @@ describe("Android application projection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("APK family without a root manifest", () => {
|
||||
const missingManifest =
|
||||
"No root AndroidManifest.xml occurrence was observed. The APK family comes from the .apk suffix of a ZIP archive, so these bytes may not be an APK.";
|
||||
const projectApk = async (entries: Record<string, string>) => {
|
||||
const root = await createTestTempDirectory("rea-android-manifest-");
|
||||
const path = join(root, "Plain.apk");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
for (const [entry, text] of Object.entries(entries))
|
||||
await writer.add(entry, new TextReader(text));
|
||||
await writeFile(path, await writer.close());
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
return androidApplicationProjectionResultSchema.parse(
|
||||
requireSuccessfulProjection(
|
||||
projectAndroidApplicationEvidence({ inventory_evidence: [inventory] }),
|
||||
).normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
it("says when the APK family rests only on the ZIP filename suffix", async () => {
|
||||
expect((await projectApk({ "readme.txt": "hello" })).limitations).toContain(
|
||||
missingManifest,
|
||||
);
|
||||
expect(
|
||||
(await projectApk({ "AndroidManifest.xml": "manifest" })).limitations,
|
||||
).not.toContain(missingManifest);
|
||||
});
|
||||
});
|
||||
|
||||
describe("case-distinct APK resource names", () => {
|
||||
it("inventories and projects an APK whose resource names differ only in case", async () => {
|
||||
const root = await createTestTempDirectory("rea-android-case-");
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
import {
|
||||
artifactComparisonResultSchema,
|
||||
@@ -3,14 +3,23 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { compareArtifacts } from "../../../src/domain/artifactComparison.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const observe = async (path: string) => {
|
||||
const inventory = await inventoryArtifact(path);
|
||||
const observe = async (
|
||||
path: string,
|
||||
omit: { readonly nodes?: boolean; readonly occurrences?: boolean } = {},
|
||||
) => {
|
||||
const observed = await inventoryArtifact(path);
|
||||
const inventory = {
|
||||
...observed,
|
||||
...(omit.nodes === true ? { nodes: [] } : {}),
|
||||
...(omit.occurrences === true ? { occurrences: [] } : {}),
|
||||
};
|
||||
const partial = omit.nodes === true || omit.occurrences === true;
|
||||
return createEvidence(
|
||||
{
|
||||
path,
|
||||
@@ -22,7 +31,7 @@ const observe = async (path: string) => {
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(inventory),
|
||||
confidence: "observed",
|
||||
confidence: partial ? "derived" : "observed",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
@@ -60,4 +69,75 @@ describe("artifact comparison summary", () => {
|
||||
});
|
||||
expect(comparison.changes).toHaveLength(3);
|
||||
});
|
||||
|
||||
const writeChangedFiles = async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-partial-root-");
|
||||
const leftPath = join(root, "left.txt");
|
||||
const rightPath = join(root, "right.txt");
|
||||
await Promise.all([
|
||||
writeFile(leftPath, "before"),
|
||||
writeFile(rightPath, "after"),
|
||||
]);
|
||||
return { leftPath, rightPath };
|
||||
};
|
||||
|
||||
it("counts a changed root once when partial inventories omit node details", async () => {
|
||||
const { leftPath, rightPath } = await writeChangedFiles();
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath, { nodes: true }),
|
||||
observe(rightPath, { nodes: true }),
|
||||
]);
|
||||
const comparison = compareArtifacts(left, right);
|
||||
|
||||
expect(comparison.status).toBe("truncated");
|
||||
expect(comparison.summary).toMatchObject({ changed: 1, unknown: 0 });
|
||||
expect(comparison.changes).toEqual([
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "changed",
|
||||
dimensions: ["content", "availability"],
|
||||
left_occurrence_id: expect.stringMatching(/^occ_/u),
|
||||
right_occurrence_id: expect.stringMatching(/^occ_/u),
|
||||
evidence_links: [left.evidence_id, right.evidence_id],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a root content change when partial inventories omit every member", async () => {
|
||||
const { leftPath, rightPath } = await writeChangedFiles();
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath, { nodes: true, occurrences: true }),
|
||||
observe(rightPath, { nodes: true, occurrences: true }),
|
||||
]);
|
||||
const comparison = compareArtifacts(left, right);
|
||||
|
||||
expect(comparison.status).toBe("truncated");
|
||||
expect(comparison.summary).toMatchObject({ changed: 1 });
|
||||
expect(comparison.changes).toEqual([
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "changed",
|
||||
dimensions: ["content"],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not infer a content change between identical partial inventories", async () => {
|
||||
const { leftPath } = await writeChangedFiles();
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath, { nodes: true }),
|
||||
observe(leftPath, { nodes: true }),
|
||||
]);
|
||||
const comparison = compareArtifacts(left, right);
|
||||
|
||||
expect(comparison.status).toBe("truncated");
|
||||
expect(comparison.summary).toMatchObject({ changed: 0, unknown: 1 });
|
||||
expect(comparison.changes).toEqual([
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "unknown",
|
||||
dimensions: ["availability"],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { compareUnicodeCodePoints } from "../../../src/domain/unicodeCodePointOrder.js";
|
||||
import { digestCanonicalValue } from "../../../src/domain/canonicalDigest.js";
|
||||
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { compareArtifacts } from "../../../src/domain/artifactComparison.js";
|
||||
import type { ArtifactInventoryResult } from "../../../src/domain/artifactGraph.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user