chore: merge main into feat/signature-posture
main now carries #964 at skill version 29, so this branch moves to 30. Regenerate the product catalog, conformance manifest, skill digest and package metadata on top of it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const cases = [
|
||||
['<script data-src="decoy.js"></script>', []],
|
||||
['<script x:src="decoy.js"></script>', []],
|
||||
[`<script title='src="decoy.js"'></script>`, []],
|
||||
["<script src=actual.js></script>", ["actual.js"]],
|
||||
['<script title=">" src="actual.js"></script>', ["actual.js"]],
|
||||
['<script src="actual.js"></script>', ["actual.js"]],
|
||||
["<script src='actual.js'></script>", ["actual.js"]],
|
||||
['<script data-src="decoy.js" src="actual.js"></script>', ["actual.js"]],
|
||||
['<!-- <script src="decoy.js"></script> -->', []],
|
||||
['<textarea><script src="decoy.js"></script></textarea>', []],
|
||||
['<template><script src="decoy.js"></script></template>', []],
|
||||
['<script src="actual.js" src="decoy.js"></script>', ["actual.js"]],
|
||||
] as const;
|
||||
|
||||
it.each(cases)(
|
||||
"projects local loads from actual HTML attributes in %s",
|
||||
async (html, expected) => {
|
||||
const root = await createTestTempDirectory("rea-html-entrypoints-");
|
||||
await Promise.all([
|
||||
writeFile(join(root, "index.html"), html),
|
||||
writeFile(join(root, "actual.js"), "globalThis.ownedActual = true;"),
|
||||
writeFile(join(root, "decoy.js"), "globalThis.ownedDecoy = true;"),
|
||||
]);
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const loads = result.graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "loads" && properties.script_path !== undefined,
|
||||
);
|
||||
expect(loads.map(({ properties }) => properties.resolved_path)).toEqual(
|
||||
expected,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves source digest, opening-tag range and decoded local base resolution", async () => {
|
||||
const root = await createTestTempDirectory("rea-html-entrypoint-evidence-");
|
||||
const opening = '<script title=">" src="actual.js">';
|
||||
const prefix = '<base data-href="decoy/"><base href=assets/>\n';
|
||||
const html = `${prefix}${opening}</script>`;
|
||||
await mkdir(join(root, "assets"));
|
||||
await Promise.all([
|
||||
writeFile(join(root, "index.html"), html),
|
||||
writeFile(
|
||||
join(root, "assets", "actual.js"),
|
||||
"globalThis.ownedActual = true;",
|
||||
),
|
||||
]);
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const loads = result.graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "loads" && properties.script_path !== undefined,
|
||||
);
|
||||
expect(loads).toHaveLength(1);
|
||||
expect(loads[0]).toMatchObject({
|
||||
properties: {
|
||||
script_path: "actual.js",
|
||||
base_href: "assets/",
|
||||
resolved_path: "assets/actual.js",
|
||||
},
|
||||
evidence: {
|
||||
authority: "static-relationship-inference",
|
||||
artifact: {
|
||||
available: true,
|
||||
sha256: createHash("sha256").update(html).digest("hex"),
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "index.html",
|
||||
start: { line: 2, column: 0 },
|
||||
end: { line: 2, column: opening.length },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative, sep } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const cases: readonly {
|
||||
name: string;
|
||||
html: string;
|
||||
files: Readonly<Record<string, string>>;
|
||||
expected: readonly string[];
|
||||
}[] = [
|
||||
{
|
||||
name: "extension fallback",
|
||||
html: '<script src="./app"></script>',
|
||||
files: { "app.js": "globalThis.owned = true;" },
|
||||
expected: [],
|
||||
},
|
||||
{
|
||||
name: "directory index",
|
||||
html: '<script src="./app"></script>',
|
||||
files: { "app/index.js": "globalThis.owned = true;" },
|
||||
expected: [],
|
||||
},
|
||||
{
|
||||
name: "directory package",
|
||||
html: '<script src="./app"></script>',
|
||||
files: {
|
||||
"app/package.json": '{"main":"entry.js"}',
|
||||
"app/entry.js": "globalThis.owned = true;",
|
||||
},
|
||||
expected: [],
|
||||
},
|
||||
{
|
||||
name: "base directory",
|
||||
html: '<base href="assets/"><script src="./app"></script>',
|
||||
files: { "assets/app.js": "globalThis.owned = true;" },
|
||||
expected: [],
|
||||
},
|
||||
{
|
||||
name: "exact base resource",
|
||||
html: '<base href="assets/"><script src="./app.js?cache=1#v2"></script>',
|
||||
files: {
|
||||
"assets/app.js": "globalThis.owned = true;",
|
||||
"app.js": "globalThis.decoy = true;",
|
||||
},
|
||||
expected: ["assets/app.js"],
|
||||
},
|
||||
{
|
||||
name: "exact script resource",
|
||||
html: '<script src="./app.js?cache=1#v2"></script>',
|
||||
files: { "app.js": "globalThis.owned = true;" },
|
||||
expected: ["app.js"],
|
||||
},
|
||||
];
|
||||
|
||||
it.each(cases)(
|
||||
"uses exact HTML resource identity for $name",
|
||||
async ({ html, files, expected }) => {
|
||||
const root = await createTestTempDirectory("rea-html-resources-");
|
||||
await Promise.all(
|
||||
Object.entries({ ...files, "index.html": html }).map(
|
||||
async ([path, text]) => {
|
||||
await mkdir(dirname(join(root, path)), { recursive: true });
|
||||
await writeFile(join(root, path), text);
|
||||
},
|
||||
),
|
||||
);
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const loads = result.graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "loads" && properties.script_path !== undefined,
|
||||
);
|
||||
expect(loads.map(({ properties }) => properties.resolved_path)).toEqual(
|
||||
expected,
|
||||
);
|
||||
if (expected.length === 0) {
|
||||
const reference = result.graph.nodes
|
||||
.flatMap(({ observations }) => observations)
|
||||
.find(
|
||||
({ properties }) => properties.mechanism === "html-script-reference",
|
||||
);
|
||||
expect(reference).toMatchObject({
|
||||
properties: {
|
||||
script_path: "./app",
|
||||
resolution_context: "html-reference",
|
||||
resolution_status: "not-found",
|
||||
resolved_path: null,
|
||||
},
|
||||
evidence: {
|
||||
authority: "static-relationship-inference",
|
||||
location: {
|
||||
available: true,
|
||||
value: { kind: "source-range", source: "index.html" },
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("exact HTML resource"),
|
||||
]),
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("retains CommonJS extension resolution against Node", async () => {
|
||||
const root = await createTestTempDirectory("rea-html-node-control-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.cjs"),
|
||||
'const value = require("./app"); module.exports = value;',
|
||||
),
|
||||
writeFile(join(root, "app.js"), 'module.exports = "actual";'),
|
||||
]);
|
||||
const expected = relative(
|
||||
root,
|
||||
createRequire(join(root, "main.cjs")).resolve("./app"),
|
||||
)
|
||||
.split(sep)
|
||||
.join("/");
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
const edge = result.graph.edges.find(
|
||||
({ properties }) =>
|
||||
properties.module_link_kind === "require" &&
|
||||
properties.specifier === "./app",
|
||||
);
|
||||
expect(edge?.properties).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: expected,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const cases: readonly {
|
||||
name: string;
|
||||
exports: unknown;
|
||||
expected: string | null;
|
||||
nodeError?: string;
|
||||
rejectedTarget?: string;
|
||||
}[] = [
|
||||
...[
|
||||
"./../outside.cjs",
|
||||
"./lib/../actual.cjs",
|
||||
"././actual.cjs",
|
||||
"./node_modules/actual.cjs",
|
||||
"./NODE_MODULES/actual.cjs",
|
||||
"./%2e%2e/outside.cjs",
|
||||
"./n%6fde_modules/actual.cjs",
|
||||
"./lib\\..\\actual.cjs",
|
||||
"../outside.cjs",
|
||||
"actual.cjs",
|
||||
"/actual.cjs",
|
||||
"file:./actual.cjs",
|
||||
"",
|
||||
].map((target) => ({
|
||||
name: `invalid target ${JSON.stringify(target)}`,
|
||||
exports: target,
|
||||
expected: null,
|
||||
nodeError: "ERR_INVALID_PACKAGE_TARGET",
|
||||
rejectedTarget: target,
|
||||
})),
|
||||
{
|
||||
name: "root subpath rejects a parent segment",
|
||||
exports: { ".": "./../outside.cjs" },
|
||||
expected: null,
|
||||
nodeError: "ERR_INVALID_PACKAGE_TARGET",
|
||||
rejectedTarget: "./../outside.cjs",
|
||||
},
|
||||
{
|
||||
name: "active condition rejects instead of selecting default",
|
||||
exports: { node: "./../outside.cjs", default: "./actual.cjs" },
|
||||
expected: null,
|
||||
nodeError: "ERR_INVALID_PACKAGE_TARGET",
|
||||
rejectedTarget: "./../outside.cjs",
|
||||
},
|
||||
{
|
||||
name: "top-level array skips an invalid target",
|
||||
exports: ["./../outside.cjs", "./actual.cjs"],
|
||||
expected: "node_modules/fixture/actual.cjs",
|
||||
},
|
||||
{
|
||||
name: "root array skips encoded invalid segments",
|
||||
exports: { ".": ["./%2e%2e/outside.cjs", "./actual.cjs"] },
|
||||
expected: "node_modules/fixture/actual.cjs",
|
||||
},
|
||||
{
|
||||
name: "nested arrays skip invalid package-local segments",
|
||||
exports: { node: [["./n%6fde_modules/actual.cjs", "./actual.cjs"]] },
|
||||
expected: "node_modules/fixture/actual.cjs",
|
||||
},
|
||||
{
|
||||
name: "last invalid target retains its reason",
|
||||
exports: ["./../outside.cjs", "././actual.cjs"],
|
||||
expected: null,
|
||||
nodeError: "ERR_INVALID_PACKAGE_TARGET",
|
||||
rejectedTarget: "././actual.cjs",
|
||||
},
|
||||
{
|
||||
name: "null following an invalid target blocks exports",
|
||||
exports: ["./../outside.cjs", null],
|
||||
expected: null,
|
||||
nodeError: "ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
},
|
||||
{
|
||||
name: "an invalid target following null remains invalid",
|
||||
exports: [null, "./../outside.cjs"],
|
||||
expected: null,
|
||||
nodeError: "ERR_INVALID_PACKAGE_TARGET",
|
||||
rejectedTarget: "./../outside.cjs",
|
||||
},
|
||||
{
|
||||
name: "inactive invalid condition does not block default",
|
||||
exports: { browser: "./../outside.cjs", default: "./actual.cjs" },
|
||||
expected: "node_modules/fixture/actual.cjs",
|
||||
},
|
||||
...["./bad%.cjs", "./bad%C3.cjs"].map((target) => ({
|
||||
name: `malformed URL ${target} is selected before URL decoding`,
|
||||
exports: [target, "./actual.cjs"],
|
||||
expected: null,
|
||||
nodeError: "URIError",
|
||||
})),
|
||||
{
|
||||
name: "encoded separator is selected before final path refusal",
|
||||
exports: ["./lib%2Factual.cjs", "./actual.cjs"],
|
||||
expected: null,
|
||||
nodeError: "ERR_INVALID_MODULE_SPECIFIER",
|
||||
},
|
||||
{
|
||||
name: "missing first target does not select a second file",
|
||||
exports: ["./missing.cjs", "./actual.cjs"],
|
||||
expected: null,
|
||||
nodeError: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
name: "nested directory is valid",
|
||||
exports: "./lib/actual.cjs",
|
||||
expected: "node_modules/fixture/lib/actual.cjs",
|
||||
},
|
||||
{
|
||||
name: "node_modules substring is not a forbidden segment",
|
||||
exports: "./node_modules.cjs",
|
||||
expected: "node_modules/fixture/node_modules.cjs",
|
||||
},
|
||||
{
|
||||
name: "encoded underscore and letters do not borrow a forbidden directory",
|
||||
exports: ["./%6eode%5fmodules/actual.cjs", "./actual.cjs"],
|
||||
expected: "node_modules/fixture/actual.cjs",
|
||||
},
|
||||
{
|
||||
name: "percent encoding is applied once",
|
||||
exports: "./literal%252e.cjs",
|
||||
expected: "node_modules/fixture/literal%2e.cjs",
|
||||
},
|
||||
];
|
||||
|
||||
const nativeResultSchema = z.object({
|
||||
value: z.string().nullable(),
|
||||
code: z.string().nullable(),
|
||||
});
|
||||
|
||||
it.each(
|
||||
(["import", "require"] as const).flatMap((moduleKind) =>
|
||||
cases.map((testCase) => ({ ...testCase, moduleKind })),
|
||||
),
|
||||
)(
|
||||
"matches Node $moduleKind target selection for $name",
|
||||
async ({
|
||||
moduleKind,
|
||||
name,
|
||||
exports,
|
||||
expected,
|
||||
nodeError,
|
||||
rejectedTarget,
|
||||
}) => {
|
||||
const root = await createTestTempDirectory("rea-package-target-");
|
||||
const mainPath = moduleKind === "import" ? "main.mjs" : "main.cjs";
|
||||
const files = {
|
||||
[mainPath]:
|
||||
moduleKind === "import"
|
||||
? 'import value from "fixture"; export default value;'
|
||||
: 'module.exports = require("fixture");',
|
||||
"node_modules/fixture/package.json": JSON.stringify({ exports }),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
"node_modules/fixture/actual.cjs",
|
||||
"node_modules/outside.cjs",
|
||||
"node_modules/fixture/lib/actual.cjs",
|
||||
"node_modules/fixture/node_modules/actual.cjs",
|
||||
"node_modules/fixture/node_modules.cjs",
|
||||
"node_modules/fixture/literal%2e.cjs",
|
||||
].map((path) => [path, `module.exports = ${JSON.stringify(path)};`]),
|
||||
),
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([path, text]) => {
|
||||
await mkdir(dirname(join(root, path)), { recursive: true });
|
||||
await writeFile(join(root, path), text);
|
||||
}),
|
||||
);
|
||||
const runner =
|
||||
moduleKind === "import"
|
||||
? 'const load = async () => (await import("fixture")).default;'
|
||||
: 'const load = async () => require("fixture");';
|
||||
const native = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type",
|
||||
moduleKind === "import" ? "module" : "commonjs",
|
||||
"--eval",
|
||||
`${runner} load().then(value => console.log(JSON.stringify({value,code:null})), error => console.log(JSON.stringify({value:null,code:error.code ?? error.name})));`,
|
||||
],
|
||||
{ cwd: root, timeout: 5_000 },
|
||||
);
|
||||
const oracle = nativeResultSchema.parse(JSON.parse(native.stdout));
|
||||
expect(oracle.value, name).toBe(expected);
|
||||
if (nodeError !== undefined)
|
||||
expect(oracle.code).toBe(
|
||||
moduleKind === "import" && nodeError === "MODULE_NOT_FOUND"
|
||||
? "ERR_MODULE_NOT_FOUND"
|
||||
: nodeError,
|
||||
);
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
});
|
||||
const edge = result.graph.edges.find(
|
||||
({ properties }) =>
|
||||
properties.specifier === "fixture" &&
|
||||
properties.resolution_status !== undefined &&
|
||||
properties.resolution_status !== null,
|
||||
);
|
||||
expect(edge).toBeDefined();
|
||||
expect(edge?.properties.resolved_path).toBe(expected);
|
||||
if (expected !== null) {
|
||||
expect(edge?.properties.resolution_status).toBe("resolved");
|
||||
} else {
|
||||
expect(edge?.properties.resolution_status).not.toBe("resolved");
|
||||
}
|
||||
if (rejectedTarget !== undefined) {
|
||||
expect(edge?.properties.resolution_status).toBe("rejected");
|
||||
expect(edge?.evidence.limitations.join(" ")).toContain(
|
||||
JSON.stringify(rejectedTarget),
|
||||
);
|
||||
expect(edge?.evidence.limitations.join(" ")).toContain("exports target");
|
||||
expect(edge?.evidence.limitations.join(" ")).not.toContain(
|
||||
"not valid package JSON",
|
||||
);
|
||||
expect(edge?.evidence.location).toMatchObject({
|
||||
value: { kind: "source-range", source: mainPath },
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -25,6 +25,26 @@ const cases: readonly {
|
||||
metadata: { main: "actual.cjs" },
|
||||
index: false,
|
||||
},
|
||||
{
|
||||
name: "top-level exports array",
|
||||
metadata: { exports: ["./actual.cjs"] },
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "root subpath exports array",
|
||||
metadata: { exports: { ".": ["./actual.cjs"] } },
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "exports array skips invalid and unmatched entries",
|
||||
metadata: { exports: [42, { browser: "./browser.js" }, "./actual.cjs"] },
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "nested root exports array",
|
||||
metadata: { exports: { ".": [[null, { require: "./actual.cjs" }]] } },
|
||||
index: true,
|
||||
},
|
||||
{ name: "index fallback", metadata: {}, index: true },
|
||||
{
|
||||
name: "missing legacy main fallback",
|
||||
|
||||
@@ -237,18 +237,23 @@ describe("unmatched package export conditions", () => {
|
||||
},
|
||||
);
|
||||
it("does not report valid metadata as malformed", async () => {
|
||||
const { outcome } = await compareWithNode({ default: 7 }, "import");
|
||||
expect(outcome.resolution_status).toBe("unavailable");
|
||||
expect(outcome.limitations[0]).toContain("not valid package JSON");
|
||||
const { node_error, outcome } = await compareWithNode(
|
||||
{ default: 7 },
|
||||
"import",
|
||||
);
|
||||
expect(node_error).toBe("ERR_INVALID_PACKAGE_TARGET");
|
||||
expect(outcome.resolution_status).toBe("rejected");
|
||||
expect(outcome.limitations[0]).toContain("exports target 7");
|
||||
expect(outcome.limitations[0]).not.toContain("not valid package JSON");
|
||||
});
|
||||
});
|
||||
|
||||
describe("package exports fallback refusal reasons", () => {
|
||||
it.each([
|
||||
[{ import: [42, 7] }, "ERR_INVALID_PACKAGE_TARGET", "unavailable"],
|
||||
[{ import: [42, 7] }, "ERR_INVALID_PACKAGE_TARGET", "rejected"],
|
||||
[{ import: [null, null] }, "ERR_PACKAGE_PATH_NOT_EXPORTED", "external"],
|
||||
[{ import: [42, null] }, "ERR_PACKAGE_PATH_NOT_EXPORTED", "external"],
|
||||
[{ import: [null, 42] }, "ERR_INVALID_PACKAGE_TARGET", "unavailable"],
|
||||
[{ import: [null, 42] }, "ERR_INVALID_PACKAGE_TARGET", "rejected"],
|
||||
[
|
||||
{ import: { node: null }, default: "./default.cjs" },
|
||||
"ERR_PACKAGE_PATH_NOT_EXPORTED",
|
||||
@@ -265,6 +270,10 @@ describe("package exports fallback refusal reasons", () => {
|
||||
expect(node_error).toBe(code);
|
||||
expect(outcome.resolved_path).toBeNull();
|
||||
expect(outcome.resolution_status).toBe(status);
|
||||
if (code === "ERR_INVALID_PACKAGE_TARGET") {
|
||||
expect(outcome.limitations[0]).toContain("exports target");
|
||||
expect(outcome.limitations[0]).not.toContain("not valid package JSON");
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { nativeCallObservationResultSchema } from "../../../src/domain/native/nativeCallObservation.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import type { NativeCallTracer } from "../../../src/native/LldbCallTracer.js";
|
||||
import { NativeMacOSProvider } from "../../../src/native/NativeMacOSProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { NativeFixtureRunner } from "../../fixtures/nativeCommands.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
/** A thin little-endian arm64 MH_EXECUTE header with no load commands. */
|
||||
const machoHeader = (): Buffer => {
|
||||
const header = Buffer.alloc(32);
|
||||
header.writeUInt32LE(0xfeedfacf, 0);
|
||||
header.writeUInt32LE(0x0100000c, 4);
|
||||
header.writeUInt32LE(2, 12);
|
||||
return header;
|
||||
};
|
||||
|
||||
const tracer: NativeCallTracer & { calls: number } = {
|
||||
calls: 0,
|
||||
trace(request) {
|
||||
this.calls++;
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
debugger: {
|
||||
path: "/usr/bin/lldb",
|
||||
sha256: "b".repeat(64),
|
||||
version: "lldb-fixture",
|
||||
},
|
||||
run: {
|
||||
status: "traced",
|
||||
version: "lldb-fixture",
|
||||
pid: 99,
|
||||
outcome: "exited",
|
||||
exit_status: 0,
|
||||
exit_description: null,
|
||||
killed: false,
|
||||
terminated: true,
|
||||
elapsed_ms: 1,
|
||||
breakpoints: request.input.breakpoints.map((_, index) => ({
|
||||
index,
|
||||
location_count: 1,
|
||||
locations: [],
|
||||
})),
|
||||
events: [],
|
||||
other_stops: [],
|
||||
},
|
||||
stdout: { text: "", bytes: 0, truncated: false },
|
||||
stderr: { text: "", bytes: 0, truncated: false },
|
||||
terminated: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
it("routes observe_native_calls through MCP with schema-checked input and output", async () => {
|
||||
const directory = await createTestTempDirectory("rea-native-calls-mcp-");
|
||||
const path = join(directory, "Tool");
|
||||
await writeFile(path, machoHeader());
|
||||
const session = createTestBinarySession(
|
||||
new NativeMacOSProvider(new NativeFixtureRunner(), "darwin", tracer),
|
||||
);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "native-calls-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
|
||||
const called = await client.callTool({
|
||||
name: "observe_native_calls",
|
||||
arguments: {
|
||||
breakpoints: [{ kind: "function", name: "open" }],
|
||||
duration_ms: 1000,
|
||||
},
|
||||
});
|
||||
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const result = nativeCallObservationResultSchema.parse(
|
||||
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
|
||||
);
|
||||
expect(result.process).toMatchObject({ pid: 99, outcome: "exited" });
|
||||
expect(result.breakpoints[0]?.request).toEqual({
|
||||
kind: "function",
|
||||
name: "open",
|
||||
module: null,
|
||||
});
|
||||
const rejected = await client.callTool({
|
||||
name: "observe_native_calls",
|
||||
arguments: {
|
||||
breakpoints: [{ kind: "function", name: "open" }],
|
||||
duration_ms: 1,
|
||||
},
|
||||
});
|
||||
expect(rejected.isError).toBe(true);
|
||||
expect(tracer.calls).toBe(1);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,293 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../../../src/domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../../../src/domain/analysisErrorBase.js";
|
||||
import { EvidenceIntegrityError } from "../../../../src/domain/evidenceErrors.js";
|
||||
import { nativeCallObservationResultSchema } from "../../../../src/domain/native/nativeCallObservation.js";
|
||||
import { err, ok, type Result } from "../../../../src/domain/result.js";
|
||||
import type {
|
||||
NativeCallTrace,
|
||||
NativeCallTracer,
|
||||
} from "../../../../src/native/LldbCallTracer.js";
|
||||
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
|
||||
import {
|
||||
NativeFixtureRunner,
|
||||
nativeMachoTarget,
|
||||
} from "../../../fixtures/nativeCommands.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const LOCATION = {
|
||||
load_address: "0x100000928",
|
||||
file_address: "0x100000928",
|
||||
module: "Fixture",
|
||||
module_path: "/tmp/Fixture",
|
||||
symbol: "-[Greeter greet:times:]",
|
||||
};
|
||||
|
||||
const run = (
|
||||
overrides: Partial<NativeCallTrace["run"]> = {},
|
||||
): NativeCallTrace["run"] => ({
|
||||
status: "traced",
|
||||
version: "lldb-2100.0.17.203",
|
||||
pid: 4242,
|
||||
outcome: "exited",
|
||||
exit_status: 0,
|
||||
exit_description: null,
|
||||
killed: false,
|
||||
terminated: true,
|
||||
elapsed_ms: 12.5,
|
||||
breakpoints: [
|
||||
{ index: 0, location_count: 1, locations: [LOCATION] },
|
||||
{ index: 1, location_count: 1, locations: [LOCATION] },
|
||||
],
|
||||
events: [
|
||||
{
|
||||
sequence: 0,
|
||||
elapsed_ms: 3,
|
||||
thread_id: 7,
|
||||
breakpoint_index: 0,
|
||||
...LOCATION,
|
||||
receiver_class: "Greeter",
|
||||
selector: "greet:times:",
|
||||
registers: [
|
||||
{ name: "x0", value: "0x6000" },
|
||||
{ name: "x1", value: "0x7000" },
|
||||
],
|
||||
backtrace: [],
|
||||
},
|
||||
],
|
||||
other_stops: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
/** Records the request and returns a canned run or failure. */
|
||||
class FixtureTracer implements NativeCallTracer {
|
||||
readonly requests: Parameters<NativeCallTracer["trace"]>[0][] = [];
|
||||
|
||||
constructor(
|
||||
private readonly outcome: Result<NativeCallTrace, AnalysisError> = ok({
|
||||
debugger: {
|
||||
path: "/usr/bin/lldb",
|
||||
sha256: "a".repeat(64),
|
||||
version: "lldb-2100.0.17.203",
|
||||
},
|
||||
run: run(),
|
||||
stdout: { text: "hello\n", bytes: 6, truncated: false },
|
||||
stderr: { text: "", bytes: 0, truncated: false },
|
||||
terminated: true,
|
||||
}),
|
||||
) {}
|
||||
|
||||
trace(request: Parameters<NativeCallTracer["trace"]>[0]) {
|
||||
this.requests.push(request);
|
||||
return Promise.resolve(this.outcome);
|
||||
}
|
||||
}
|
||||
|
||||
const BREAKPOINTS = [
|
||||
{ kind: "objc-method", class_name: "Greeter", selector: "greet:times:" },
|
||||
{ kind: "function", name: "rea_add" },
|
||||
];
|
||||
|
||||
const fixtureTarget = async () => {
|
||||
const directory = await createTestTempDirectory("rea-native-calls-");
|
||||
const path = join(directory, "Fixture");
|
||||
await writeFile(path, "fixture executable");
|
||||
return {
|
||||
...nativeMachoTarget(path),
|
||||
sha256: createHash("sha256").update("fixture executable").digest("hex"),
|
||||
};
|
||||
};
|
||||
|
||||
const observe = async (
|
||||
tracer: NativeCallTracer,
|
||||
parameters: Record<string, unknown>,
|
||||
target?: Awaited<ReturnType<typeof fixtureTarget>>,
|
||||
signal?: AbortSignal,
|
||||
) =>
|
||||
new NativeMacOSProvider(new NativeFixtureRunner(), "darwin", tracer)
|
||||
.createClient(target ?? (await fixtureTarget()))
|
||||
.execute(
|
||||
"observe_native_calls",
|
||||
// The provider parses JSON-like parameters itself.
|
||||
JSON.parse(JSON.stringify(parameters)),
|
||||
signal === undefined ? undefined : { signal },
|
||||
);
|
||||
|
||||
describe("observe_native_calls projection", () => {
|
||||
it("launches the active Mach-O through the tracer and projects its run", async () => {
|
||||
const tracer = new FixtureTracer();
|
||||
const target = await fixtureTarget();
|
||||
const observed = await observe(
|
||||
tracer,
|
||||
{ breakpoints: BREAKPOINTS, arguments: ["--flag"] },
|
||||
target,
|
||||
);
|
||||
if (!observed.ok) throw observed.error;
|
||||
expect(tracer.requests[0]).toMatchObject({
|
||||
executable: target.path,
|
||||
architecture: "arm64",
|
||||
input: {
|
||||
arguments: ["--flag"],
|
||||
duration_ms: 10_000,
|
||||
max_events: 1_000,
|
||||
argument_registers: 4,
|
||||
backtrace_frames: 0,
|
||||
},
|
||||
});
|
||||
const result = nativeCallObservationResultSchema.parse(
|
||||
observed.value.result,
|
||||
);
|
||||
expect(result.breakpoints.map(({ request }) => request)).toEqual([
|
||||
{
|
||||
kind: "objc-method",
|
||||
class_name: "Greeter",
|
||||
selector: "greet:times:",
|
||||
method_type: "any",
|
||||
},
|
||||
{ kind: "function", name: "rea_add", module: null },
|
||||
]);
|
||||
expect(result.process).toMatchObject({
|
||||
pid: 4242,
|
||||
outcome: "exited",
|
||||
exit_status: 0,
|
||||
terminated: true,
|
||||
stdout: { text: "hello\n" },
|
||||
});
|
||||
expect(result.events[0]).toMatchObject({
|
||||
receiver_class: "Greeter",
|
||||
selector: "greet:times:",
|
||||
});
|
||||
expect(result.coverage).toEqual({
|
||||
status: "complete",
|
||||
event_limit_reached: false,
|
||||
unresolved_breakpoints: [],
|
||||
});
|
||||
expect(observed.value.locations).toEqual([
|
||||
{ kind: "artifact-path", path: target.path },
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks event limits, unresolved breakpoints and unconfirmed exits", async () => {
|
||||
const tracer = new FixtureTracer(
|
||||
ok({
|
||||
debugger: {
|
||||
path: "/usr/bin/lldb",
|
||||
sha256: "a".repeat(64),
|
||||
version: null,
|
||||
},
|
||||
run: run({
|
||||
outcome: "event-limit",
|
||||
exit_status: null,
|
||||
killed: true,
|
||||
terminated: false,
|
||||
breakpoints: [
|
||||
{ index: 0, location_count: 1, locations: [LOCATION] },
|
||||
{ index: 1, location_count: 0, locations: [] },
|
||||
],
|
||||
}),
|
||||
stdout: { text: "", bytes: 0, truncated: false },
|
||||
stderr: { text: "x".repeat(16), bytes: 2_000_000, truncated: true },
|
||||
terminated: true,
|
||||
}),
|
||||
);
|
||||
const observed = await observe(tracer, {
|
||||
breakpoints: BREAKPOINTS,
|
||||
max_events: 1,
|
||||
});
|
||||
if (!observed.ok) throw observed.error;
|
||||
const result = nativeCallObservationResultSchema.parse(
|
||||
observed.value.result,
|
||||
);
|
||||
expect(result.coverage).toEqual({
|
||||
status: "partial",
|
||||
event_limit_reached: true,
|
||||
unresolved_breakpoints: [1],
|
||||
});
|
||||
expect(result.process.terminated).toBe(false);
|
||||
expect(result.limitations).toEqual(
|
||||
expect.arrayContaining([
|
||||
"Observation stopped at max_events (1); later calls were not recorded and the process was killed.",
|
||||
"Breakpoints 1 matched no code in any image loaded while observing; their calls could not be observed.",
|
||||
"Target output beyond 1 MiB per stream is counted but not kept.",
|
||||
"REA could not confirm that process 4242 exited; check for it before relying on host state.",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("observe_native_calls failures", () => {
|
||||
it("rejects malformed input before launching anything", async () => {
|
||||
for (const parameters of [
|
||||
{ breakpoints: [] },
|
||||
{ breakpoints: [{ kind: "objc-method", selector: "-[A b]" }] },
|
||||
{ breakpoints: BREAKPOINTS, environment: { "A=B": "x" } },
|
||||
{ breakpoints: BREAKPOINTS, argument_registers: 9 },
|
||||
]) {
|
||||
const tracer = new FixtureTracer();
|
||||
const observed = await observe(tracer, parameters);
|
||||
expect(observed.ok).toBe(false);
|
||||
if (!observed.ok)
|
||||
expect(observed.error).toBeInstanceOf(AnalysisInputError);
|
||||
expect(tracer.requests).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a changed or non-Mach-O target", async () => {
|
||||
const tracer = new FixtureTracer();
|
||||
const target = await fixtureTarget();
|
||||
const changed = await observe(
|
||||
tracer,
|
||||
{ breakpoints: BREAKPOINTS },
|
||||
{ ...target, sha256: "f".repeat(64) },
|
||||
);
|
||||
expect(!changed.ok && changed.error).toBeInstanceOf(EvidenceIntegrityError);
|
||||
const database = await new NativeMacOSProvider(
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
tracer,
|
||||
)
|
||||
.createClient({
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
})
|
||||
.execute("observe_native_calls", { breakpoints: [] });
|
||||
expect(!database.ok && database.error).toBeInstanceOf(
|
||||
AnalysisCapabilityUnavailableError,
|
||||
);
|
||||
expect(tracer.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps the tracer's failure reason and caller cancellation", async () => {
|
||||
const denied = new AnalysisCapabilityUnavailableError(
|
||||
"native-macos",
|
||||
"observe_native_calls",
|
||||
"debugger-attach-denied: attach failed",
|
||||
);
|
||||
const failed = await observe(new FixtureTracer(err(denied)), {
|
||||
breakpoints: BREAKPOINTS,
|
||||
});
|
||||
expect(!failed.ok && failed.error).toBe(denied);
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await observe(
|
||||
new FixtureTracer(),
|
||||
{ breakpoints: BREAKPOINTS },
|
||||
undefined,
|
||||
controller.signal,
|
||||
);
|
||||
expect(!cancelled.ok && cancelled.error).toBeInstanceOf(
|
||||
AnalysisCancelledError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// Observed by verify:native-calls; `--wait` keeps the process running.
|
||||
@interface ReaCallGreeter : NSObject
|
||||
- (NSString *)greet:(NSString *)name times:(long)count;
|
||||
@end
|
||||
@implementation ReaCallGreeter
|
||||
- (NSString *)greet:(NSString *)name times:(long)count {
|
||||
return [NSString stringWithFormat:@"%@ x%ld", name, count];
|
||||
}
|
||||
@end
|
||||
|
||||
__attribute__((noinline)) int rea_call_add(int left, int right) {
|
||||
return left + right;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
@autoreleasepool {
|
||||
if (argc > 1 && strcmp(argv[1], "--wait") == 0)
|
||||
for (;;) sleep(1);
|
||||
ReaCallGreeter *greeter = [ReaCallGreeter new];
|
||||
for (long index = 0; index < 3; index++)
|
||||
printf("%s %d\n", [[greeter greet:@"world" times:index] UTF8String],
|
||||
rea_call_add((int)index, 40));
|
||||
const char *marker = getenv("REA_CALLS_MARKER");
|
||||
if (marker != NULL)
|
||||
printf("marker %s\n", marker);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user