refactor(mcp): make analysis states unrepresentable (#468)

* refactor(config): parse capability settings into exact states

* refactor(runtime): encode replay and process outcomes exactly

* refactor: make analysis states unrepresentable

* refactor(mcp): register canonical schemas with SDK

* fix: preserve capability and catalog invariants

* fix(build): remove stale compiled modules

* fix(replay): update real verifier policy dependency

* fix(package): verify the complete MCP catalog

* fix(test): supply complete replay reload policy

* refactor(contracts): centralize output schema lookup

* refactor(mcp): delegate protocol boundaries to SDK

* fix(browser): approve real source capture

* fix(mcp): preserve catalog guidance
This commit is contained in:
morluto
2026-08-10 02:28:11 +08:00
committed by GitHub
parent 6901edc05d
commit b8a9da0c0f
271 changed files with 5970 additions and 5699 deletions
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import type { EnabledJavaScriptReplayPolicy } from "../../../src/application/JavaScriptReplayPlanning.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { controlledReplayOutputSchema } from "../../../src/domain/javascriptReplay.js";
import { nodeCharacterizationPreparationOutputSchema } from "../../../src/domain/nodeRuntimeCharacterization.js";
@@ -13,9 +14,9 @@ import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js"
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
function createReplayPolicy(root: string) {
function createReplayPolicy(root: string): EnabledJavaScriptReplayPolicy {
return {
enabled: true,
status: "enabled",
roots: [root],
nodePath: process.execPath,
bubblewrapPath: process.execPath,
@@ -64,7 +65,7 @@ function createReplayScenario(root: string) {
}));
const server = createServer(session, session, {
permissionAuthority: createReplayAuthority(policy),
javascriptReplayPolicy: policy,
javascriptReplayPolicy: () => policy,
javascriptReplayHost: {
readSource: async (path) => ({
canonicalPath: await realpath(path),
@@ -134,7 +135,6 @@ function createReplayInput(root: string) {
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
approved: false,
};
}
@@ -210,7 +210,6 @@ async function createCharacterizationInput(root: string) {
entry_export: "selected",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
approved: false,
},
};
}
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
const mainPath = fileURLToPath(
new URL("../../../dist/main.js", import.meta.url),
@@ -31,9 +32,7 @@ const expectAvailableToolInventory = async (client: Client): Promise<void> => {
.parse(status.structuredContent).result.tool_availability;
expect(availability).toHaveLength(CATALOG_IDENTITY.counts.mcp_tools);
expect(new Set(listed.tools.map(({ name }) => name))).toEqual(
new Set(
availability.filter(({ available }) => available).map(({ name }) => name),
),
new Set(TOOL_CONTRACTS.map(({ name }) => name)),
);
};
@@ -53,6 +53,7 @@ describeBrowser("CdpBrowserProvider: document script 1", () => {
approved: true,
observation_ms: 0,
include_script_sources: true,
source_capture_approved: true,
}),
);
@@ -355,6 +356,7 @@ describeBrowser("CdpBrowserProvider: document script 3", () => {
approved: true,
observation_ms: 0,
include_script_sources: true,
source_capture_approved: true,
limits: {
max_frames: 1,
max_dom_nodes: 1,
@@ -31,8 +31,7 @@ describe("safe artifact output tree", () => {
),
).rejects.toThrow(/disagrees/u);
expect(await tree.rollback()).toMatchObject({
attempted: true,
verified: true,
status: "complete",
residualPaths: [],
});
await expect(access(output)).rejects.toThrow();
@@ -52,7 +51,7 @@ describe("safe artifact output tree", () => {
);
await tree.commit();
expect(await tree.rollback()).toMatchObject({ attempted: false });
expect(await tree.rollback()).toEqual({ status: "not-required" });
expect(await readFile(join(output, "file.txt"), "utf8")).toBe(
"visible before seal",
);
@@ -62,9 +61,13 @@ describe("safe artifact output tree", () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const tree = await SafeOutputTree.create(join(parent, "published"), LIMITS);
const cleanup = await tree.rollback();
(cleanup.residualPaths as string[]).push("/forged/path");
if (cleanup.status !== "complete") throw new Error("expected cleanup");
(cleanup.residualPaths as unknown as string[]).push("/forged/path");
expect(tree.cleanup.residualPaths).toEqual([]);
expect((await tree.rollback()).residualPaths).toEqual([]);
expect(tree.cleanup).toEqual({ status: "complete", residualPaths: [] });
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
});
});
+18 -1
View File
@@ -38,7 +38,7 @@ it(
const connected = await connectBrowser(browser);
const tools = await connected.client.listTools();
expect(tools.tools.length).toBeLessThan(TOOL_CONTRACTS.length);
expect(tools.tools).toHaveLength(TOOL_CONTRACTS.length);
expect(tools.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining([
"list_browser_targets",
@@ -80,6 +80,17 @@ it(
targets: { items: [{ target_id: "allowed-page" }] },
},
});
const unapprovedSourceCapture = await connected.client.callTool({
name: "inspect_web_page",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
include_script_sources: true,
},
});
expect(unapprovedSourceCapture.isError).toBe(true);
const inspected = await connected.client.callTool({
name: "inspect_web_page",
arguments: {
@@ -95,6 +106,7 @@ it(
include_websocket_shapes: true,
websocket_shape_approved: true,
include_script_sources: true,
source_capture_approved: true,
},
});
expect(inspected.isError).not.toBe(true);
@@ -205,6 +217,11 @@ const verifySessionAndComparisonTools = async (
expect(compared.structuredContent).toMatchObject({
result: { overall_status: "unknown" },
});
const incompleteComparison = await connected.client.callTool({
name: "compare_web_captures",
arguments: { before: { inspection: capture } },
});
expect(incompleteComparison.isError).toBe(true);
const screenshot = await connected.client.callTool({
name: "capture_web_screenshot",
arguments: {
+1 -1
View File
@@ -439,7 +439,7 @@ it("reports an unconfigured investigation ceiling before static analysis", async
(await client.listTools()).tools.some(
({ name }) => name === "analyze_javascript_application",
),
).toBe(false);
).toBe(true);
});
const evidenceFor = (session: BinarySession, value: unknown) => {
@@ -219,7 +219,7 @@ describe("enhanced MCP tools", () => {
expect(JSON.stringify(result)).toContain("operation budget");
});
it("returns correction-only structured validation issues", async () => {
it("lets the SDK reject misspelled and out-of-range inputs", async () => {
const client = await connect();
const valid = await client.callTool({
name: "trace_feature",
@@ -230,18 +230,8 @@ describe("enhanced MCP tools", () => {
name: "trace_feature",
arguments: { query: "needle", max_operatons: 1 },
});
expect(misspelled).toMatchObject({
isError: true,
structuredContent: {
error: {
code: "invalid_request",
retryable: true,
details: {
issues: [{ path: ["max_operatons"], reason: "unknown_argument" }],
},
},
},
});
expect(misspelled.isError).toBe(true);
expect(misspelled.structuredContent).toBeUndefined();
const nestedMisspelled = await client.callTool({
name: "analyze_function",
arguments: {
@@ -249,42 +239,14 @@ describe("enhanced MCP tools", () => {
collection_offset: { commentz: 1 },
},
});
expect(nestedMisspelled).toMatchObject({
isError: true,
structuredContent: {
error: {
details: {
issues: [
{
path: ["collection_offset", "commentz"],
reason: "unknown_argument",
},
],
},
},
},
});
expect(nestedMisspelled.isError).toBe(true);
expect(nestedMisspelled.structuredContent).toBeUndefined();
const bounded = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 101 },
});
expect(bounded.structuredContent).toMatchObject({
error: {
details: {
issues: [
{
path: ["max_operations"],
reason: "out_of_range",
maximum: 100,
},
],
},
},
});
expect(bounded.content[0]).toEqual({
type: "text",
text: JSON.stringify(bounded.structuredContent),
});
expect(bounded.isError).toBe(true);
expect(bounded.structuredContent).toBeUndefined();
});
it("returns a typed tool error for malformed Hopper boundary values", async () => {
+1 -1
View File
@@ -22,7 +22,7 @@ describe("Ghidra MCP capability routing", () => {
const availableNames = (await mcp.listTools()).tools.map(
({ name }) => name,
);
expect(availableNames).not.toContain("set_comment");
expect(availableNames).toContain("set_comment");
expect(calls).not.toContain("set_comment");
const status = await mcp.callTool({
+25
View File
@@ -14,12 +14,14 @@ const dependencies = ({
shutdown,
exitCodes,
shutdownUnregistrations = [],
loadOptionalProviders,
}: {
readonly serve: RuntimeDependencies["serve"];
readonly output: string[];
readonly shutdown: Array<() => void>;
readonly exitCodes: number[];
readonly shutdownUnregistrations?: string[];
readonly loadOptionalProviders?: RuntimeDependencies["loadOptionalProviders"];
}): RuntimeDependencies => ({
env: {},
serve,
@@ -29,6 +31,7 @@ const dependencies = ({
shutdown.push(handler);
return () => shutdownUnregistrations.push("shutdown");
},
...(loadOptionalProviders === undefined ? {} : { loadOptionalProviders }),
});
describe("MCP runtime errors", () => {
@@ -121,6 +124,28 @@ describe("MCP runtime errors", () => {
]);
});
it("starts the core transport when optional providers fail to load", async () => {
const output: string[] = [];
let serveCalls = 0;
expect(
await run(
dependencies({
serve: () => {
serveCalls += 1;
return { close: () => Promise.resolve() };
},
output,
shutdown: [],
exitCodes: [],
loadOptionalProviders: () =>
Promise.reject(new Error("synthetic optional import failure")),
}),
),
).toBe(0);
expect(serveCalls).toBe(1);
expect(output).toEqual([]);
});
it("reports shutdown failure and sets a failing exit code", async () => {
const output: string[] = [];
const shutdown: Array<() => void> = [];
+83 -26
View File
@@ -53,23 +53,29 @@ describe("runtime permission reload", () => {
runtime.reload();
await validReadStarted.promise;
expect(runtime.notifications()).toBe(0);
expect(runtime.options.processPolicy?.enabled).toBe(false);
expect(runtime.options.processPolicy?.().status).toBe("disabled");
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.oldRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
expectOptionalPolicies(runtime.options, { status: "disabled" });
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(true);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
releaseValidRead.resolve();
await runtime.notificationCount(1);
await expect
.poll(() => canRead(runtime.authority, fixture.newRoot))
.toBe(true);
expect(runtime.options.processPolicy?.enabled).toBe(true);
expect(runtime.options.processPolicy?.().status).toBe("enabled");
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.newRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
expectOptionalPolicies(runtime.options, {
status: "enabled",
root: fixture.newRoot,
});
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
});
@@ -102,13 +108,16 @@ describe("runtime permission reload", () => {
expect(secondStarted).toBe(false);
releaseFirstRead.resolve();
await secondReadStarted.promise;
await runtime.notificationCount(2);
await expect
.poll(() => canRead(runtime.authority, fixture.latestRoot))
.toBe(true);
expect(runtime.options.processPolicy?.enabled).toBe(false);
expect(runtime.options.processPolicy?.().status).toBe("disabled");
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.latestRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
expectOptionalPolicies(runtime.options, { status: "disabled" });
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
expect(await canRead(runtime.authority, fixture.latestRoot)).toBe(true);
});
@@ -125,19 +134,57 @@ describe("runtime permission reload", () => {
configure(fixture.env, fixture.newRoot, true);
runtime.reload();
runtime.reload();
await runtime.notificationCount(1);
await expect.poll(() => reads).toBe(2);
await expect
.poll(() => canRead(runtime.authority, fixture.newRoot))
.toBe(true);
expect(reads).toBe(2);
expect(runtime.options.processPolicy?.enabled).toBe(true);
expect(runtime.options.processPolicy?.().status).toBe("enabled");
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.newRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
expectOptionalPolicies(runtime.options, {
status: "enabled",
root: fixture.newRoot,
});
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
});
});
type ExpectedOptionalPolicies =
| { readonly status: "disabled" }
| { readonly status: "enabled"; readonly root: string };
const expectOptionalPolicies = (
options: CreateServerOptions,
expected: ExpectedOptionalPolicies,
): void => {
const enabled = expected.status === "enabled";
expect(options.managedRuntimePolicy?.()).toEqual(
enabled
? {
status: "enabled",
roots: [expected.root],
executablePath: process.execPath,
}
: { status: "disabled" },
);
expect(options.javascriptReplayPolicy?.()).toMatchObject(
enabled
? { status: "enabled", roots: [expected.root] }
: { status: "disabled" },
);
expect(options.availabilityPolicy?.()).toMatchObject({
browserObservationEnabled: enabled,
electronObservationEnabled: enabled,
v8InspectorObservationEnabled: enabled,
javascriptReplayEnabled: enabled,
});
};
const reloadFixture = async () => {
const directory = await createTestTempDirectory("rea-main-reload-");
directories.push(directory);
@@ -169,6 +216,33 @@ const configure = (
env.REA_PROCESS_EXECUTABLE_ROOTS_JSON = JSON.stringify([root]);
env.REA_PROCESS_WORKING_ROOTS_JSON = JSON.stringify([root]);
env.REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED = String(enabled);
env.REA_MANAGED_RUNTIME_ENABLED = String(enabled);
env.REA_MANAGED_RUNTIME_ROOTS_JSON = JSON.stringify([root]);
env.REA_MANAGED_RUNTIME_EXECUTABLE_PATH = process.execPath;
env.REA_JAVASCRIPT_REPLAY_ENABLED = String(enabled);
env.REA_JAVASCRIPT_REPLAY_ROOTS_JSON = JSON.stringify([root]);
env.REA_JAVASCRIPT_REPLAY_NODE_PATH = process.execPath;
env.REA_JAVASCRIPT_REPLAY_BWRAP_PATH = process.execPath;
env.REA_JAVASCRIPT_REPLAY_SYSTEMD_RUN_PATH = process.execPath;
env.REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH = process.execPath;
env.REA_JAVASCRIPT_REPLAY_SHELL_PATH = process.execPath;
env.REA_BROWSER_OBSERVE_ENABLED = String(enabled);
env.REA_BROWSER_CDP_ENDPOINTS_JSON = JSON.stringify([
"http://127.0.0.1:9222",
]);
env.REA_BROWSER_ALLOWED_ORIGINS_JSON = JSON.stringify([
"https://example.test",
]);
env.REA_ELECTRON_OBSERVE_ENABLED = String(enabled);
env.REA_ELECTRON_CDP_ENDPOINTS_JSON = JSON.stringify([
"http://127.0.0.1:9223",
]);
env.REA_ELECTRON_FILE_ROOTS_JSON = JSON.stringify([root]);
env.REA_V8_INSPECTOR_OBSERVE_ENABLED = String(enabled);
env.REA_V8_INSPECTOR_ENDPOINTS_JSON = JSON.stringify([
"http://127.0.0.1:9224",
]);
env.REA_V8_INSPECTOR_FILE_ROOTS_JSON = JSON.stringify([root]);
};
const startRuntime = async (
@@ -177,9 +251,6 @@ const startRuntime = async (
) => {
let reload: (() => void) | undefined;
let options: CreateServerOptions | undefined;
let notificationCount = 0;
let notification = deferred<void>();
const waiters = new Map<number, ReturnType<typeof deferred<void>>>();
const result = await run({
env,
serve: (factory) => {
@@ -196,14 +267,7 @@ const startRuntime = async (
readProjectPermissionStore: readStore,
createServer: (analysis, session, received) => {
options = received;
const server = createServer(analysis, session, received);
server.sendToolListChanged = () => {
notificationCount += 1;
notification.resolve(undefined);
notification = deferred<void>();
waiters.get(notificationCount)?.resolve(undefined);
};
return server;
return createServer(analysis, session, received);
},
});
expect(result).toBe(0);
@@ -215,13 +279,6 @@ const startRuntime = async (
reload,
options: capturedOptions,
authority,
notifications: () => notificationCount,
notificationCount: (count: number) => {
if (notificationCount >= count) return Promise.resolve();
const waiter = deferred<void>();
waiters.set(count, waiter);
return waiter.promise;
},
};
};
+3 -3
View File
@@ -55,11 +55,11 @@ it("opens a managed PE and executes the managed static provider through MCP", as
if (!authority.ok) throw authority.error;
const server = createServer(session, session, {
permissionAuthority: authority.value,
managedRuntimePolicy: {
enabled: true,
managedRuntimePolicy: () => ({
status: "enabled",
roots: [directory],
executablePath: runtimePath,
},
}),
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
+1 -1
View File
@@ -46,7 +46,7 @@ describe("production MCP doctor", () => {
expect(result.inventory?.tools.expected).toBe(
result.inventory?.tools.observed,
);
expect(result.inventory?.tools.expected).toBeLessThan(
expect(result.inventory?.tools.expected).toBe(
CATALOG_IDENTITY.counts.mcp_tools,
);
}, 30_000);
@@ -34,13 +34,13 @@ describe("process-capture MCP elicitation handshake", () => {
createServer(session, session, {
logger: silentLogger,
permissionAuthority: authority,
processPolicy: {
enabled: true,
processPolicy: () => ({
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
},
networkAccess: "external",
}),
});
const client = new Client(
{ name: "process-elicit", version: "1" },
@@ -70,6 +70,29 @@ describe("process-capture MCP elicitation handshake", () => {
});
try {
await client.connect(clientTransport);
const identity = await client.readResource({
uri: "rea://server/identity",
});
const identityContent = identity.contents[0];
if (identityContent === undefined || !("text" in identityContent))
throw new Error("missing modern server identity resource");
expect(JSON.parse(identityContent.text)).toMatchObject({
client: { name: "process-elicit", version: "1" },
});
const status = await client.callTool({
name: "binary_session",
arguments: { detail: "full" },
});
expect(status.structuredContent).toMatchObject({
result: {
client_features: {
elicitation_form: true,
elicitation_url: false,
roots: false,
sampling: false,
},
},
});
const captured = await client.callTool({
name: "capture_process_scenario",
arguments: {
@@ -56,13 +56,13 @@ describe("process-capture MCP elicitation handshake", () => {
createServer(session, session, {
logger: silentLogger,
permissionAuthority: authority,
processPolicy: {
enabled: true,
processPolicy: () => ({
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
},
networkAccess: "external",
}),
}),
{ transport: serverTransport, legacy: "reject" },
);
+2 -4
View File
@@ -59,10 +59,8 @@ describe("direct replay machine MCP parity", () => {
],
},
});
expect(invalid).toMatchObject({
isError: true,
structuredContent: { error: { code: "invalid_request" } },
});
expect(invalid.isError).toBe(true);
expect(invalid.structuredContent).toBeUndefined();
expect(JSON.stringify(invalid)).not.toContain("private-request-body");
} finally {
await client.close();
+46 -14
View File
@@ -59,6 +59,41 @@ const availabilityProvider = (): AnalysisProvider => {
};
};
const statusCapability = (
operation: string,
availability:
| { readonly available: true }
| {
readonly available: false;
readonly availability_code: "unsupported_host";
readonly reason: string;
} = { available: true },
) => ({
operation,
input_contract_version: 1,
output_contract_version: 1,
pagination: "none" as const,
exhaustive: true,
effects: {
mutates_artifact: false,
launches_process: false,
may_show_ui: false,
may_access_network: false,
may_write_filesystem: false,
changes_permissions: false,
requires_root: false,
},
limits: {
max_results: null,
max_payload_bytes: null,
timeout_ms: null,
},
limitations: [],
...(availability.available
? { available: true as const, reason: null, availability_code: null }
: availability),
});
describe("server and catalog identity", () => {
it("derives package and SDK versions from canonical package metadata", async () => {
const packageJson = JSON.parse(await readFile("package.json", "utf8"));
@@ -132,7 +167,7 @@ describe("server and catalog identity", () => {
"list_documents",
"list_procedures",
"list_strings",
].map((operation) => ({ operation, available: true, reason: null })),
].map((operation) => statusCapability(operation)),
},
policy,
);
@@ -144,9 +179,7 @@ describe("server and catalog identity", () => {
open: true,
kind: "artifact",
format: "javascript",
capabilities: [
{ operation: "current_address", available: true, reason: null },
],
capabilities: [statusCapability("current_address")],
},
policy,
);
@@ -163,12 +196,11 @@ describe("server and catalog identity", () => {
kind: "executable",
format: "elf",
capabilities: [
{
operation: "inspect_macho",
statusCapability("inspect_macho", {
available: false,
availability_code: "unsupported_host",
reason: "Native macOS utilities require macOS.",
},
}),
],
},
policy,
@@ -184,7 +216,7 @@ describe("server and catalog identity", () => {
});
describe("live server identity over MCP", () => {
it("exposes live identity, labeled inventories, availability, and list changes", async () => {
it("exposes live identity, a stable catalog, and changing availability", async () => {
const session = composeBinarySessionFromProvider(availabilityProvider());
const server = createServer(session, session);
const client = new Client(
@@ -209,12 +241,12 @@ describe("live server identity over MCP", () => {
await assertCapabilityViews(client);
expect(
(await client.listTools()).tools.map(({ name }) => name),
).not.toContain("current_address");
).toContain("current_address");
await client.callTool({
name: "open_binary",
arguments: { path: process.execPath },
});
await expect.poll(() => toolListChanges).toBeGreaterThan(0);
expect(toolListChanges).toBe(0);
expect(
(await client.listTools()).tools.map(({ name }) => name),
).toContain("current_address");
@@ -251,7 +283,7 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
server: SDK_IDENTITY.server,
client_test: PACKAGE_METADATA.clientSdkVersion,
},
client: { name: "identity-test", version: "9" },
client: null,
alignment: { state: "unknown" },
});
};
@@ -286,7 +318,7 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
required: [],
optional: ["elicitation_form"],
missing_required: [],
missing_optional: [],
missing_optional: ["elicitation_form"],
},
}),
expect.objectContaining({
@@ -304,7 +336,7 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
}),
]),
client_features: {
elicitation_form: true,
elicitation_form: false,
elicitation_url: false,
roots: false,
sampling: false,
@@ -354,7 +386,7 @@ const assertCapabilityViews = async (client: Client): Promise<void> => {
has_more: true,
},
client_features: {
elicitation_form: true,
elicitation_form: false,
elicitation_url: false,
roots: false,
sampling: false,
@@ -85,6 +85,31 @@ it("projects remote failures without provider or bridge details", async () => {
expect(text(result)).toBe(JSON.stringify(result.structuredContent));
});
it("lets the SDK validate a tool call before invoking its handler", async () => {
let invocations = 0;
const client = await connect({
execute: () => {
invocations += 1;
return Promise.resolve(ok([]));
},
});
const malformed = await client.callTool({
name: "procedure_info",
arguments: {},
});
expect(malformed.isError).toBe(true);
expect(invocations).toBe(0);
const valid = await client.callTool({
name: "list_documents",
arguments: {},
});
expect(valid.isError).not.toBe(true);
expect(invocations).toBe(1);
});
it("handles concurrent tool calls without corruption", async () => {
const invocations: string[] = [];
const client = await connect({
+8 -85
View File
@@ -43,86 +43,6 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return Object.fromEntries(Object.entries(result.structuredContent));
};
const objectEntries = (value: unknown): readonly [string, unknown][] =>
typeof value === "object" && value !== null && !Array.isArray(value)
? Object.entries(value)
: [];
const referencedSchema = (schema: unknown, root: unknown): unknown => {
const object = Object.fromEntries(objectEntries(schema));
const reference = object.$ref;
if (typeof reference !== "string" || !reference.startsWith("#/$defs/"))
return schema;
return Object.fromEntries(objectEntries(root)).$defs instanceof Object
? Object.fromEntries(
objectEntries(Object.fromEntries(objectEntries(root)).$defs),
)[reference.slice(8)]
: schema;
};
const assertDescribedStrictObjects = (
schema: unknown,
root = schema,
path = "$",
strictObject = true,
): void => {
for (const [key, value] of objectEntries(schema)) {
if (key === "examples") continue;
if (key === "properties") {
const properties = objectEntries(value);
for (const [property, propertySchema] of properties) {
const resolved = referencedSchema(propertySchema, root);
const propertyObject = Object.fromEntries(
objectEntries(propertySchema),
);
expect(
propertyObject.description ??
Object.fromEntries(objectEntries(resolved)).description,
`${path}.properties.${property}`,
).toEqual(expect.any(String));
assertDescribedStrictObjects(
propertySchema,
root,
`${path}.properties.${property}`,
);
}
if (strictObject)
expect(
Object.fromEntries(objectEntries(schema)).additionalProperties,
).toBe(false);
continue;
}
assertDescribedStrictObjects(
value,
root,
`${path}.${key}`,
strictObject &&
key !== "allOf" &&
key !== "contains" &&
key !== "if" &&
key !== "then",
);
}
if (Array.isArray(schema))
for (const [index, value] of schema.entries())
assertDescribedStrictObjects(
value,
root,
`${path}[${String(index)}]`,
strictObject,
);
};
const assertDescribedRootObject = (schema: unknown, path: string): void => {
const object = Object.fromEntries(objectEntries(schema));
expect(object.additionalProperties, path).toBe(false);
for (const [property, propertySchema] of objectEntries(object.properties))
expect(
Object.fromEntries(objectEntries(propertySchema)).description,
`${path}.properties.${property}`,
).toEqual(expect.any(String));
};
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
const client = await connect({
execute: (name, args) => {
@@ -213,8 +133,8 @@ it("advertises the complete currently available inventory with a session", async
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
expect(names).toContain("binary_session");
expect(names).not.toContain("binary_overview");
expect(names).not.toContain("batch_decompile");
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
const status = structured(
await client.callTool({
name: "binary_session",
@@ -234,7 +154,11 @@ it("advertises the complete currently available inventory with a session", async
.result.tool_availability.filter((item) => item.available)
.map(({ name }) => name),
);
expect(new Set(names)).toEqual(available);
expect(new Set(names)).toEqual(
new Set(TOOL_CONTRACTS.map(({ name }) => name)),
);
expect(available).not.toContain("binary_overview");
expect(available).not.toContain("batch_decompile");
const contracts = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
@@ -245,8 +169,7 @@ it("advertises the complete currently available inventory with a session", async
expect(tool.title, tool.name).toBe(contract?.title);
expect(tool.description, tool.name).toBe(contract?.description);
expect(tool.annotations, tool.name).toEqual(contract?.annotations);
expect(tool.inputSchema, tool.name).toBeDefined();
expect(tool.outputSchema, tool.name).toBeDefined();
assertDescribedStrictObjects(tool.inputSchema, tool.inputSchema, tool.name);
assertDescribedRootObject(tool.outputSchema, `${tool.name}.output`);
}
}, 10_000);
+6 -6
View File
@@ -130,8 +130,8 @@ describe("target-free MCP workflow", () => {
);
expect(beforeNames).toContain("open_binary");
expect(beforeNames).toContain("binary_session");
expect(beforeNames).not.toContain("current_document");
expect(beforeNames).not.toContain("capture_process_scenario");
expect(beforeNames).toContain("current_document");
expect(beforeNames).toContain("capture_process_scenario");
expect(
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
.isError,
@@ -235,13 +235,13 @@ describe("process residuals over MCP", () => {
);
const server = createServer(session, session, {
logger: silentLogger,
processPolicy: {
enabled: true,
processPolicy: () => ({
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [dirname(processFixture)],
allowedEnvironment: [],
allowExternalNetwork: true,
},
networkAccess: "external",
}),
});
const mcp = new Client({ name: "process-unknown", version: "1.0.0" });
const [clientTransport, serverTransport] =
@@ -1,68 +1,164 @@
import { describe, expect, it } from "vitest";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { z } from "zod";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
describe("tool registration options", () => {
it("reuses finalized advertised schemas", () => {
const contract = TOOL_CONTRACTS[0];
expect(contract).toBeDefined();
if (contract === undefined) return;
const first = toolRegistrationOptions(contract);
const second = toolRegistrationOptions(contract);
expect(first.inputSchema["~standard"].jsonSchema.input()).toBe(
second.inputSchema["~standard"].jsonSchema.output(),
);
expect(first.outputSchema["~standard"].jsonSchema.input()).toBe(
second.outputSchema["~standard"].jsonSchema.output(),
);
it("preserves canonical Zod parsers in the SDK schemas", () => {
for (const contract of TOOL_CONTRACTS) {
const options = toolRegistrationOptions(contract);
expect(options.inputSchema).not.toBe(contract.inputSchema);
expect(
options.inputSchema.safeParse(contract.examples[0]?.input ?? {}),
).toEqual(
contract.inputSchema.safeParse(contract.examples[0]?.input ?? {}),
);
expect(options.outputSchema).toBe(contract.outputSchema);
}
});
it("gives fallback parameter guidance operational meaning", () => {
it("retains the canonical parser as the SDK validation boundary", async () => {
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "analyze_function",
);
expect(contract).toBeDefined();
if (contract === undefined) return;
const advertisedSchema =
toolRegistrationOptions(contract).inputSchema[
"~standard"
].jsonSchema.input();
const properties = Object.fromEntries(
Object.entries(advertisedSchema.properties ?? {}),
);
expect(properties.include_assembly).toMatchObject({
description: "Whether to include assembly in the result.",
});
expect(properties.max_instructions).toMatchObject({
description: "Maximum permitted instructions for this operation.",
});
expect(properties.pseudocode_offset).toMatchObject({
description: "Zero-based index of the first pseudocode to return.",
});
const result = await contract.inputSchema["~standard"].validate({});
expect("issues" in result).toBe(true);
});
it("advertises validated contract examples on the MCP input schema", () => {
for (const name of [
"record_unknown",
"run_replay_machine",
"build_reconstruction_obligation_ledger",
]) {
const contract = TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
it("generates the checked-in catalog from the SDK wire projection", async () => {
const server = new McpServer({ name: "catalog-test", version: "0" });
for (const contract of TOOL_CONTRACTS)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => ({
content: [{ type: "text" as const, text: "catalog-only" }],
isError: true as const,
}),
);
expect(contract).toBeDefined();
if (contract === undefined) continue;
const client = new Client({ name: "catalog-test", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.map((tool) => ({
name: tool.name,
title: tool.title,
description: tool.description,
inputSchema: tool.inputSchema,
outputSchema: tool.outputSchema,
annotations: tool.annotations,
}));
for (const contract of TOOL_CONTRACTS) {
const tool = advertised.find(({ name }) => name === contract.name);
expect(tool?.inputSchema.examples, contract.name).toEqual(
contract.examples.map(({ input }) => input),
);
expect(
missingPropertyDescriptions(tool?.inputSchema),
contract.name,
).toEqual([]);
}
const analyzeFunction = advertised.find(
({ name }) => name === "analyze_function",
);
expect(analyzeFunction?.inputSchema.properties).toMatchObject({
include_assembly: {
description: "Whether to include assembly in the result.",
},
max_instructions: {
description: "Maximum permitted instructions for this operation.",
},
pseudocode_offset: {
description: "Zero-based index of the first pseudocode to return.",
},
});
expect(advertised).toEqual(
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
name: tool.name,
title: tool.title,
description: tool.description,
inputSchema: tool.inputSchema,
outputSchema: tool.outputSchema,
annotations: tool.annotations,
})),
);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
const schema =
toolRegistrationOptions(contract).inputSchema[
"~standard"
].jsonSchema.input();
expect(schema.examples).toEqual(
contract.examples.map(({ input }) => input),
it("delegates output validation to the SDK boundary", async () => {
const server = new McpServer({ name: "output-test", version: "0" });
server.registerTool(
"invalid_output",
{
inputSchema: z.object({}),
outputSchema: z.object({ value: z.string() }),
},
async () => ({
content: [{ type: "text", text: "invalid" }],
structuredContent: { value: 42 },
}),
);
const client = new Client({ name: "output-test", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({ name: "invalid_output" });
expect(result.isError).toBe(true);
expect(result.content).toContainEqual(
expect.objectContaining({
type: "text",
text: expect.stringContaining("Output validation error"),
}),
);
expect(result.structuredContent).toBeUndefined();
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
const missingPropertyDescriptions = (
value: unknown,
path = "inputSchema",
): string[] => {
if (Array.isArray(value))
return value.flatMap((child, index) =>
missingPropertyDescriptions(child, `${path}[${index}]`),
);
if (!isObject(value)) return [];
const missing: string[] = [];
if (isObject(value.properties))
for (const [property, schema] of Object.entries(value.properties)) {
const propertyPath = `${path}.properties.${property}`;
if (!isObject(schema) || typeof schema.description !== "string")
missing.push(propertyPath);
missing.push(...missingPropertyDescriptions(schema, propertyPath));
}
for (const [key, child] of Object.entries(value))
if (
key !== "properties" &&
key !== "examples" &&
key !== "default" &&
key !== "const" &&
key !== "enum"
)
missing.push(...missingPropertyDescriptions(child, `${path}.${key}`));
return missing;
};
const isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
-25
View File
@@ -87,31 +87,6 @@ describe("tool result projection", () => {
});
expect(JSON.stringify(result)).not.toContain("cookie");
});
it("classifies output contract failures without naming a provider", () => {
const result = toCallToolResult(ok({ value: 42 }), contract);
expect(result).toMatchObject({
structuredContent: {
error: {
code: "unreadable_output",
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
retryable: false,
remediation: {
action:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
restart_required: false,
},
},
},
isError: true,
});
expect(result.content[0]).toEqual({
type: "text",
text: JSON.stringify(result.structuredContent),
});
});
it("links successful evidence only when its session resource exists", () => {
const evidence = createEvidence(
undefined,
@@ -10,6 +10,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createElectronEvidence } from "../../../src/application/ElectronEvidence.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { reconcileJavaScriptRuntime } from "../../../src/domain/javascriptRuntimeReconciliation.js";
import { inspectElectronPageInputSchema } from "../../../src/domain/electronObservation.js";
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
@@ -233,7 +234,7 @@ const electronRuntimeEvidence = (
const includeWorker = options.includeWorker ?? true;
const targetId = options.targetId ?? "target-main";
const sourceCaptureApproved = options.sourceCaptureApproved ?? true;
const input = {
const input = inspectElectronPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9223",
allowed_file_roots: [root],
target_id: targetId,
@@ -250,7 +251,7 @@ const electronRuntimeEvidence = (
max_script_source_bytes: 1_048_576,
max_total_script_source_bytes: 4_194_304,
},
};
});
return createElectronEvidence(
"inspect_electron_page",
input,
@@ -35,11 +35,11 @@ it("does not follow or disclose symlink targets outside declared roots", async (
filesystem_roots: [root],
}),
{
enabled: true,
status: "enabled",
executableRoots: ["/usr/bin"],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
},
);
expect(result.ok).toBe(true);
@@ -65,11 +65,7 @@ it("does not launch when policy denies capture", async () => {
working_directory: "/tmp",
});
const result = await captureProcessScenario(scenario, {
enabled: false,
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
allowExternalNetwork: true,
status: "disabled",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected policy refusal");
@@ -80,11 +76,11 @@ it("distinguishes timeout from cancellation and cleans both runs", async () => {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const policy: ProcessExecutionPolicy = {
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [dirname(processFixture)],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
};
const timedOut = await captureProcessScenario(
parseProcessScenario({
@@ -143,11 +139,11 @@ it("captures source-owned interactive, resize, Unicode, and signal behavior", as
idle_timeout_ms: 2_000,
}),
{
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [dirname(processFixture)],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
},
);
if (!result.ok) throw result.error;
@@ -177,7 +173,7 @@ it("dispatches scheduled events before a silent PTY produces output", async () =
idle_timeout_ms: 2_000,
}),
{
enabled: true,
status: "enabled",
executableRoots: [
join(dirname(process.execPath), "missing"),
dirname(process.execPath),
@@ -187,7 +183,7 @@ it("dispatches scheduled events before a silent PTY produces output", async () =
dirname(processFixture),
],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
},
);
expect(result.ok).toBe(true);
@@ -214,11 +210,11 @@ it("samples and cleans a source-owned child and grandchild process tree", async
idle_timeout_ms: 2_000,
}),
{
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [dirname(processFixture)],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
},
);
expect(result.ok).toBe(true);
@@ -196,11 +196,11 @@ it("runs the committed multi-source reactive fixture deterministically", async (
);
const run = () =>
captureProcessScenario(createMultiSourceScenario(root, script), {
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
});
try {
const capability = await probeProcessCaptureCapability();
@@ -207,11 +207,11 @@ it("cleans the temporary root when capture home creation fails", async () => {
prepareProcessCapture(
parseProcessScenario(base),
{
enabled: true,
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
},
undefined,
host,
@@ -375,11 +375,11 @@ it("parses bounded scenarios and rejects unordered events", () => {
it("requires explicit operator approval for host network access", () => {
expect(
authorizeProcessScenario(parseProcessScenario(base), {
enabled: true,
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: false,
networkAccess: "none",
}),
).toEqual({
allowed: false,
@@ -394,11 +394,11 @@ it("refuses paths and environment outside operator policy", () => {
});
expect(
authorizeProcessScenario(scenario, {
enabled: true,
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
}),
).toEqual({
allowed: false,
@@ -287,11 +287,11 @@ it("drives a process from terminal observations and retains the reactive transit
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(scenario, {
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
});
if (!result.ok) throw result.error;
assertCompletedCapture(result.value);
@@ -351,11 +351,11 @@ it("records target loss before post-exit settlement can win the deadline race",
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(scenario, {
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
@@ -119,11 +119,11 @@ it("runs a login and reconnect replay machine inside process capture", async ()
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const capture = await captureProcessScenario(scenario, {
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
});
expect(capture.ok).toBe(true);
if (!capture.ok) throw capture.error;
@@ -172,11 +172,11 @@ it("captures PTY, filesystem, descendants, HTTP replay, and redacts environment"
].join("\n"),
);
const policy: ProcessExecutionPolicy = {
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: ["SECRET"],
allowExternalNetwork: true,
networkAccess: "external",
};
const scenario = parseProcessScenario({
approved: true,
@@ -132,11 +132,11 @@ it("renders terminal state, records shim invocations, and captures literal check
const result = await captureProcessScenario(
buildTerminalScenario(root, script),
{
enabled: true,
status: "enabled",
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
networkAccess: "external",
},
);
expect(result.ok).toBe(true);
@@ -85,7 +85,7 @@ describe("provider process runtime and wait primitives", () => {
const waiting = deadline.wait(1_000);
controller.abort();
await expect(waiting).resolves.toBe("aborted");
expect(deadline.cancelled).toBe(true);
expect(deadline.interruption).toBe("cancelled");
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
expect(vi.getTimerCount()).toBe(0);
deadline.dispose();
@@ -99,7 +99,7 @@ describe("provider process runtime and wait primitives", () => {
await vi.advanceTimersByTimeAsync(100);
await expect(waiting).resolves.toBe("aborted");
expect(deadline.timedOut).toBe(true);
expect(deadline.interruption).toBe("timeout");
expect(deadline.remainingMs()).toBe(0);
deadline.dispose();
expect(vi.getTimerCount()).toBe(0);
@@ -114,8 +114,7 @@ describe("provider process runtime and wait primitives", () => {
controller.abort();
expect(deadline.signal.reason).toMatchObject({ name: "TimeoutError" });
expect(deadline.timedOut).toBe(true);
expect(deadline.cancelled).toBe(false);
expect(deadline.interruption).toBe("timeout");
expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
expect(vi.getTimerCount()).toBe(0);
deadline.dispose();
@@ -120,7 +120,8 @@ describe("Ghidra provider", () => {
});
expect(
ghidra.inspectTargetSupport({
...executableTarget("elf", "x86_64"),
path: "/tmp/fixture.asar",
sha256: "a".repeat(64),
kind: "archive",
format: "asar",
}),
@@ -129,14 +130,15 @@ describe("Ghidra provider", () => {
code: "target_kind_unsupported",
});
expect(
ghidra.inspectTargetSupport(executableTarget("javascript", "x86_64")),
ghidra.inspectTargetSupport({
path: "/tmp/fixture.js",
sha256: "a".repeat(64),
kind: "artifact",
format: "javascript",
}),
).toMatchObject({
status: "unsupported",
code: "target_format_unsupported",
});
expect(ghidra.inspectTargetSupport(executableTarget("elf"))).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
code: "target_kind_unsupported",
});
});
});
@@ -144,11 +146,7 @@ describe("Ghidra provider", () => {
describe("Ghidra platform support", () => {
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
const ghidra = provider({ ...installationHost(), platform: "win32" });
const nativeApplication: BinaryTarget = {
...executableTarget("pe", "x86_64"),
executableRole: "application",
managed: false,
};
const nativeApplication = peTarget("x86_64");
expect(ghidra.inspectTargetSupport(nativeApplication)).toMatchObject({
status: "supported",
@@ -208,16 +206,13 @@ describe("Ghidra platform support", () => {
code: "managed_target_unsupported",
});
expect(
ghidra.inspectTargetSupport({ ...nativeApplication, format: "elf" }),
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
).toMatchObject({
status: "unsupported",
code: "target_format_unsupported",
});
expect(
ghidra.inspectTargetSupport({
...nativeApplication,
architecture: "arm64",
}),
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
@@ -470,14 +465,29 @@ const sessionInfo = () => ({
});
const executableTarget = (
format: BinaryTarget["format"],
architecture?: NonNullable<BinaryTarget["architecture"]>,
): BinaryTarget => ({
format: "mach-o" | "elf" | "pe",
architecture: NonNullable<BinaryTarget["architecture"]>,
): BinaryTarget =>
format === "pe"
? peTarget(architecture)
: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
};
const peTarget = (
architecture: NonNullable<BinaryTarget["architecture"]>,
): Extract<BinaryTarget, { format: "pe" }> => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
...(architecture === undefined
? {}
: { architecture, availableArchitectures: [architecture] }),
format: "pe",
architecture,
availableArchitectures: [architecture],
executableRole: "application",
managed: false,
});
@@ -27,8 +27,12 @@ describe("Hopper analysis profiles", () => {
[target("pe", "x86"), ["-l", "WinPE", "--intel-32"]],
[
{
...target("mach-o", "arm64"),
availableArchitectures: ["x86_64", "arm64"],
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["x86_64", "arm64"] as const,
} satisfies BinaryTarget,
["-l", "FAT", "--aarch64", "-l", "Mach-O"],
],
@@ -141,11 +145,23 @@ describe("Hopper analysis profiles", () => {
const target = (
format: "mach-o" | "elf" | "pe",
architecture: "x86" | "x86_64" | "arm" | "arm64",
): BinaryTarget => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
});
): BinaryTarget =>
format === "pe"
? {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
executableRole: "application",
managed: false,
}
: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
};
@@ -48,6 +48,7 @@ class FixtureLauncher implements BridgeLauncher {
ok({
process: child,
ownsProcessLifetime: true,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -78,9 +79,9 @@ class OwnedFixtureLauncher implements BridgeLauncher {
this.ownership = started.ownership;
return ok({
process: started.process,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
ownership: started.ownership,
shutdownByCleanup: true,
shutdownMode: "process-cleanup" as const,
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
});
}
@@ -102,6 +103,29 @@ class UnconfirmedFixtureLauncher implements BridgeLauncher {
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: false,
shutdownMode: "bridge-request" as const,
}),
);
}
}
class UnconfirmedOwnedFixtureLauncher implements BridgeLauncher {
launch(session: BridgeSession) {
return Promise.resolve(
ok({
process: spawn(
process.execPath,
[
fixturePath,
session.socketPath,
session.token,
session.runId,
"unconfirmed",
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -183,6 +207,26 @@ describe("HopperClient cleanup", () => {
});
});
it("does not treat an owned launcher exit as bridge document shutdown", async () => {
const client = new HopperClient({
launcher: new UnconfirmedOwnedFixtureLauncher(),
startupTimeoutMs: 1_000,
});
clients.push(client);
expect((await client.start()).ok).toBe(true);
const closed = await client.closeWithOutcome();
expect(closed).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cleanupResources: ["hopper-document"],
},
});
});
it("kills only its owned Hopper group and emits sanitized shutdown coordinates", async () => {
const unrelated = spawn(
process.execPath,
@@ -42,7 +42,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -45,7 +45,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -42,7 +42,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -46,7 +46,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -63,7 +64,8 @@ class SilentLauncher implements BridgeLauncher {
stdio: ["ignore", "ignore", "pipe"],
},
),
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -89,7 +91,8 @@ class ExitingLauncher implements BridgeLauncher {
process: spawn(process.execPath, ["-e", `process.exit(${this.code})`], {
stdio: ["ignore", "ignore", "pipe"],
}),
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -126,7 +129,8 @@ class DiagnosticExitingLauncher implements BridgeLauncher {
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -49,12 +49,11 @@ const processResult = (
value: HopperStartupDiagnostic,
overrides: Partial<LinuxPrivateDisplayProbeProcessResult> = {},
): LinuxPrivateDisplayProbeProcessResult => ({
outcome: "exited",
exitCode: value.status === "ready" ? 0 : failureExit(value.failure_code),
stderr: `${LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX}${JSON.stringify(value)}\n`,
stderrBytes: 0,
stderrTruncated: false,
timedOut: false,
cancelled: false,
cleanupIncomplete: false,
...overrides,
});
@@ -345,4 +345,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -135,4 +135,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -70,4 +70,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -146,8 +146,12 @@ describe("managed artifact failures", () => {
await client.close();
const nativeClient = new ManagedStaticProvider().createClient({
...parsed.value,
path: parsed.value.path,
sha256: parsed.value.sha256,
kind: "executable",
format: "elf",
architecture: "x86",
availableArchitectures: ["x86"],
});
await expect(
nativeClient.execute("inspect_managed_artifact", {}),
@@ -164,6 +168,8 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
const asManagedResult = (execution: AnalysisExecution) =>
@@ -168,4 +168,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -137,4 +137,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -151,4 +151,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -300,6 +300,9 @@ const inspect = (
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
};
const result = inspectManagedMembersBytes(bytes, target, limits);
return {
@@ -151,11 +151,11 @@ const inventory = async (targetValue: BinaryTarget) => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -126,13 +126,13 @@ const inventory = async (targetValue: BinaryTarget) => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
const limits = () => ({ maxDepth: 20, maxPathBytes: 4_096 });
@@ -79,11 +79,11 @@ describe("artifact directory inventory", () => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -130,11 +130,11 @@ const inventory = async (targetValue: BinaryTarget) => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -106,11 +106,11 @@ describe("artifact pagination and slices", () => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { projectNativeApiInspection } from "../../../../src/application/NativeApiInspection.js";
import { functionDossierSchema } from "../../../../src/domain/hopperValues.js";
import { nativeApiBoundarySchema } from "../../../../src/domain/nativeApiBoundary.js";
import { ghidraFunctionDossier } from "../../../fixtures/ghidraFunction.js";
describe("native API inspection", () => {
@@ -59,4 +60,30 @@ describe("native API inspection", () => {
],
});
});
it("rejects boundary types placed in the wrong ABI role", () => {
const boundary = functionDossierSchema.parse(
ghidraFunctionDossier(),
).native_api;
if (boundary === null || boundary.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
return_type: { ...boundary.return_type, role: "parameter" },
}).success,
).toBe(false);
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
parameters: [
{
...boundary.return_type,
role: "return",
},
],
}).success,
).toBe(false);
});
});
@@ -7,6 +7,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { runControlledReplay } from "../../../../src/application/JavaScriptReplayService.js";
import type {
EnabledJavaScriptReplayPolicy,
JavaScriptReplayHost,
JavaScriptReplayPolicy,
JavaScriptReplayRunner,
@@ -19,8 +20,8 @@ import {
} from "../../../../src/domain/javascriptReplay.js";
const root = resolve("tests/fixtures/replay");
const policy: JavaScriptReplayPolicy = {
enabled: true,
const policy: EnabledJavaScriptReplayPolicy = {
status: "enabled",
roots: [root],
nodePath: process.execPath,
bubblewrapPath: process.execPath,
@@ -127,7 +128,7 @@ const input = (
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
approved: mode === "execute",
...(mode === "execute" ? { approved: true as const } : {}),
});
const completedRunner = (): JavaScriptReplayRunner => ({
@@ -153,6 +154,45 @@ const completedRunner = (): JavaScriptReplayRunner => ({
});
describe("controlled JavaScript replay planning", () => {
it("parses planning and execution as disjoint legal states", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
approved: false,
plan_digest: "0".repeat(64),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
approved: true,
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
plan_digest: "0".repeat(64),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
approved: true,
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
approved: true,
plan_digest: "0".repeat(64),
reproducer_export: {
path: "/tmp/reproducer",
approved: false,
},
}).success,
).toBe(false);
});
it("rejects relative paths and more than 128 combined cases", () => {
expect(
controlledReplayInputSchema.safeParse({
@@ -180,7 +220,7 @@ describe("controlled JavaScript replay planning", () => {
const readSource = vi.fn(host.readSource);
const result = await runControlledReplay(
{
policy,
policy: () => policy,
host: { ...host, probe, readSource },
runner: completedRunner(),
authority: authority(),
@@ -199,11 +239,21 @@ describe("controlled JavaScript replay planning", () => {
it("returns a deterministic plan without admitting application code", async () => {
const execute = vi.fn(completedRunner().execute);
const first = await runControlledReplay(
{ policy, host, runner: { execute }, authority: authority() },
{
policy: () => policy,
host,
runner: { execute },
authority: authority(),
},
input("plan"),
);
const second = await runControlledReplay(
{ policy, host, runner: { execute }, authority: authority() },
{
policy: () => policy,
host,
runner: { execute },
authority: authority(),
},
input("plan"),
);
expect(first).toEqual(second);
@@ -213,12 +263,26 @@ describe("controlled JavaScript replay planning", () => {
plan: { network: "none", filesystem: { host_writes: false } },
evidence: null,
});
if (!first.ok) throw first.error;
const output = controlledReplayOutputSchema.parse(first.value);
expect(
controlledReplayOutputSchema.safeParse({ ...output, plan: null }).success,
).toBe(false);
expect(
controlledReplayOutputSchema.safeParse({ ...output, phase: "execute" })
.success,
).toBe(false);
});
it("rejects a stale digest before worker admission", async () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{ policy, host, runner: { execute }, authority: authority() },
{
policy: () => policy,
host,
runner: { execute },
authority: authority(),
},
{ ...input("execute"), plan_digest: "0".repeat(64) },
);
expect(result.ok).toBe(false);
@@ -227,10 +291,30 @@ describe("controlled JavaScript replay planning", () => {
});
});
describe("controlled JavaScript replay policy snapshots", () => {
it("uses one enabled policy snapshot for the complete planning operation", async () => {
let reads = 0;
const configuredPolicy = (): JavaScriptReplayPolicy => {
reads += 1;
return reads === 1 ? policy : { status: "disabled" };
};
const result = await runControlledReplay(
{
policy: configuredPolicy,
host,
runner: completedRunner(),
authority: authority(),
},
input("plan"),
);
expect([result.ok, reads]).toEqual([true, 1]);
});
});
describe("controlled JavaScript replay evidence and authorization", () => {
it("creates controlled-replay Evidence after an approved exact plan", async () => {
const dependencies = {
policy,
policy: () => policy,
host,
runner: completedRunner(),
authority: authority(),
@@ -272,6 +356,12 @@ describe("controlled JavaScript replay evidence and authorization", () => {
expect(output.evidence?.evidence_links).toEqual([
output.source_evidence[0]?.evidence_id,
]);
expect(
controlledReplayOutputSchema.safeParse({
...output,
source_evidence: [],
}).success,
).toBe(false);
});
it("cannot read or execute when replay is disabled", async () => {
@@ -279,7 +369,7 @@ describe("controlled JavaScript replay evidence and authorization", () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
policy: { ...policy, enabled: false },
policy: () => ({ status: "disabled" }),
host: { ...host, readSource },
runner: { execute },
authority: authority(),
@@ -293,7 +383,7 @@ describe("controlled JavaScript replay evidence and authorization", () => {
it("changes the commitment when selected module bytes change", async () => {
const dependencies = {
policy,
policy: () => policy,
host,
runner: completedRunner(),
authority: authority(),
@@ -333,7 +423,7 @@ describe("controlled JavaScript replay cancellation and export", () => {
}),
);
const dependencies = {
policy,
policy: () => policy,
host,
runner: { execute },
authority: authority(),
@@ -365,7 +455,7 @@ describe("controlled JavaScript replay cancellation and export", () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
policy,
policy: () => policy,
host: {
...host,
probe: async () => {
@@ -387,7 +477,7 @@ describe("controlled JavaScript replay cancellation and export", () => {
const directory = await createTestTempDirectory("rea-reproducer-test-");
const path = join(directory, "reproducer.json");
const dependencies = {
policy,
policy: () => policy,
host,
runner: completedRunner(),
authority: authority(directory),
@@ -66,6 +66,20 @@ const request = async (
});
describe("disposable JavaScript replay worker", () => {
it("rejects malformed runtime-hop requests before loading modules", async () => {
const result = await runWorker({
schemaVersion: 1,
left: { modules: "not-an-array", entryAlias: "entry", entryExport: "x" },
cases: [],
determinism: { clockIso: "2000-01-01T00:00:00.000Z", randomSeed: 7 },
limits: { resultDepth: 16, resultNodes: 10_000, exceptionBytes: 4096 },
});
expect(result.code).toBe(70);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("Invalid replay worker modules");
});
it("runs an ESM parser with projected plain data", async () => {
const result = await runWorker(
await request("parser.mjs", "esm", "default", ["# Title"]),
@@ -19,14 +19,14 @@ describe("replay worker protocol", () => {
parseReplayWorkerResponse(
{ schema_version: 1, left: [outcome] },
cases,
false,
"single",
),
).toMatchObject({ left: [outcome] });
expect(() =>
parseReplayWorkerResponse(
{ schema_version: 1, left: [{ ...outcome, case_id: "forged" }] },
cases,
false,
"single",
),
).toThrow("case identity changed");
expect(() =>
@@ -36,7 +36,7 @@ describe("replay worker protocol", () => {
left: [{ ...outcome, input_sha256: "2".repeat(64) }],
},
cases,
false,
"single",
),
).toThrow("case identity changed");
});
@@ -46,9 +46,9 @@ describe("replay worker protocol", () => {
parseReplayWorkerResponse(
{ schema_version: 1, left: [outcome] },
cases,
true,
"differential",
),
).toThrow("differential response is incomplete");
).toThrow();
expect(() =>
parseReplayWorkerResponse(
{
@@ -56,7 +56,7 @@ describe("replay worker protocol", () => {
left: [{ ...outcome, unexpected: true }],
},
cases,
false,
"single",
),
).toThrow();
expect(() =>
@@ -66,8 +66,8 @@ describe("replay worker protocol", () => {
left: [{ ...outcome, outcome: "exception", value: undefined }],
},
cases,
false,
"single",
),
).toThrow("Exception is missing");
).toThrow();
});
});
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import {
resolveArtifactIntegrityPolicy,
resolveNativeMountPolicy,
} from "../../../src/application/ArtifactInventory/policy.js";
describe("artifact inventory policy resolution", () => {
it("admits native mounting only when caller and operator both allow it", () => {
expect(resolveNativeMountPolicy(false, true)).toEqual({
status: "disabled",
});
expect(() => resolveNativeMountPolicy(true, false)).toThrow(
"disabled by operator policy",
);
expect(resolveNativeMountPolicy(true, true)).toEqual({
status: "approved",
});
});
it("projects strict integrity without dormant continuation state", () => {
expect(resolveArtifactIntegrityPolicy({ mode: "fail" }, true)).toEqual({
mode: "fail",
});
});
it("admits parsed continuation intent only under operator policy", () => {
expect(() =>
resolveArtifactIntegrityPolicy(
{ mode: "record-and-continue", maxMismatches: 10 },
false,
),
).toThrow("requires explicit approval and operator policy");
expect(
resolveArtifactIntegrityPolicy(
{ mode: "record-and-continue", maxMismatches: 10 },
true,
),
).toEqual({ mode: "record-and-continue", maxMismatches: 10 });
});
});
@@ -22,13 +22,37 @@ const status = (
readonly operation: string;
readonly available: boolean;
readonly reason: string | null;
readonly availability_code?: string;
readonly availability_code?: "unsupported_host";
}[];
} = {},
) => ({
open: options.open ?? false,
...(options.kind === undefined ? {} : { kind: options.kind }),
capabilities: [...(options.capabilities ?? [])],
capabilities: (options.capabilities ?? []).map((capability) => ({
...capability,
availability_code: capability.available
? null
: (capability.availability_code ?? null),
input_contract_version: 1,
output_contract_version: 1,
pagination: "none" as const,
exhaustive: true,
effects: {
mutates_artifact: false,
launches_process: false,
may_show_ui: false,
may_access_network: false,
may_write_filesystem: false,
changes_permissions: false,
requires_root: false,
},
limits: {
max_results: null,
max_payload_bytes: null,
timeout_ms: null,
},
limitations: [],
})),
});
const entry = (
@@ -47,6 +47,20 @@ const contractJsonSchema = (schema: z.ZodType) => {
return converted;
};
const describesObject = (schema: ReturnType<typeof contractJsonSchema>) =>
schema.type === "object" ||
[schema.oneOf, schema.anyOf].some(
(variants) =>
Array.isArray(variants) &&
variants.every(
(variant) =>
typeof variant === "object" &&
variant !== null &&
"type" in variant &&
variant.type === "object",
),
);
const emptySchemaPaths = (value: unknown, path = "$"): string[] => {
if (Array.isArray(value))
return value.flatMap((item, index) =>
@@ -66,8 +80,8 @@ describe("tool contract surface", () => {
for (const contract of contracts) {
const inputSchema = contractJsonSchema(contract.inputSchema);
const outputSchema = contractJsonSchema(contract.outputSchema);
expect(inputSchema.type).toBe("object");
expect(outputSchema.type).toBe("object");
expect(describesObject(inputSchema)).toBe(true);
expect(describesObject(outputSchema)).toBe(true);
expect(contract.title.length).toBeGreaterThan(2);
expect(contract.annotations).toEqual(
annotationsFromEffects(contract.effects),
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { traceJavaScriptSemanticsRequestSchema } from "../../../src/contracts/applicationWorkflowInputContracts.js";
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js";
import {
artifactInspectionInputSchema,
artifactInventoryInputSchema,
@@ -19,7 +20,10 @@ import {
annotationsFromEffects,
toolContractMetadata,
} from "../../../src/contracts/toolEffects.js";
import { requireOutputSchema } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import {
requireOutputSchema,
toolAvailability,
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE } from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
const EVIDENCE_ID = `ev_${"a".repeat(64)}`;
@@ -80,6 +84,17 @@ describe("contract validation boundaries", () => {
).toBe(false);
});
it("accepts each complete managed application Evidence source", () => {
for (const input of [
{ managed_artifact_evidence_id: EVIDENCE_ID },
{ managed_members_evidence_id: EVIDENCE_ID },
{ managed_native_boundaries_evidence_id: EVIDENCE_ID },
])
expect(
managedApplicationGraphReferenceInputSchema.safeParse(input).success,
).toBe(true);
});
it("requires explicit approval for record-and-continue artifact inspection", () => {
const input = {
integrity_policy: "record-and-continue" as const,
@@ -89,6 +104,30 @@ describe("contract validation boundaries", () => {
expect(artifactInspectionInputSchema.safeParse(input).success).toBe(false);
});
it("rejects contradictory tool availability states", () => {
const inventory = buildCapabilityInventory(
{ open: false, capabilities: [] },
{
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 0,
},
);
const unavailable = inventory.find(({ available }) => !available);
expect(unavailable).toBeDefined();
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
expect(
toolAvailability.safeParse({ ...unavailable, available: true }).success,
).toBe(false);
expect(
toolAvailability.safeParse({
...unavailable,
available: false,
reason: "available",
}).success,
).toBe(false);
});
it("covers deterministic contract rendering and defensive helper errors", () => {
const rendered = renderGuidedPrompt(PROMPT_CONTRACTS[0], {
zulu: "last",
@@ -22,9 +22,6 @@ const LIMITS = {
const INTEGRITY = {
mode: "fail",
approved: false,
enabled: false,
maxMismatches: 1,
} as const;
const deferred = <Value>() => {
@@ -43,12 +43,6 @@ describe("Hopper provider discovery", () => {
code: "target_kind_unsupported",
diagnostics: { target_kind: "archive", target_format: "asar" },
});
expect(
hopper.inspectTargetSupport(executableTargetWithoutArchitecture()),
).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
});
});
it("advertises the exact bounded byte-read limit", () => {
@@ -88,21 +82,26 @@ const databaseTarget = (): BinaryTarget => ({
const executableTarget = (
format: "mach-o" | "elf" | "pe",
architecture: "x86" | "x86_64" | "arm" | "arm64",
): BinaryTarget => ({
path: "/tmp/fixture",
sha256: "b".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
});
const executableTargetWithoutArchitecture = (): BinaryTarget => ({
path: "/tmp/fixture",
sha256: "b".repeat(64),
kind: "executable",
format: "elf",
});
): BinaryTarget =>
format === "pe"
? {
path: "/tmp/fixture",
sha256: "b".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
executableRole: "application",
managed: false,
}
: {
path: "/tmp/fixture",
sha256: "b".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
};
const artifactTarget = (): BinaryTarget => ({
path: "/tmp/app.asar",
@@ -48,7 +48,7 @@ describe("package identity", () => {
"node scripts/generate-package-metadata.mjs --check",
);
expect(packageJson.scripts.prebuild).toBe(
"npm run deps:check && npm run metadata:check",
"npm run deps:check && npm run metadata:check && node scripts/clean-build-output.mjs",
);
expect(packageJson.scripts["precheck:fast"]).toBe("npm run deps:check");
expect(packageJson.scripts["check:fast"]).toBe("turbo run typecheck lint");
@@ -1,103 +0,0 @@
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { applyToolInputJsonSchemaOverride } from "../../../src/contracts/toolSchemaJsonOverrides.js";
import { z } from "zod";
const publicInputSchema = (name: string) => {
const contract = TOOL_CONTRACTS.find((item) => item.name === name);
if (contract === undefined) throw new Error(`Missing contract: ${name}`);
return applyToolInputJsonSchemaOverride(
name,
z.toJSONSchema(contract.inputSchema, {
target: "draft-07",
unrepresentable: "any",
}),
);
};
describe("public tool schema refinements", () => {
it("requires complete web capture pairs and Evidence sources", () => {
expect(publicInputSchema("compare_web_captures")).toMatchObject({
oneOf: [
{
required: ["before", "after"],
not: {
anyOf: [
{ required: ["before_scenario"] },
{ required: ["after_scenario"] },
],
},
},
{
required: ["before_scenario", "after_scenario"],
not: {
anyOf: [{ required: ["before"] }, { required: ["after"] }],
},
},
],
});
expect(publicInputSchema("trace_application_feature")).toMatchObject({
oneOf: [
{ required: ["application"] },
{ required: ["application_evidence_id"] },
],
});
});
it("publishes sensitive approval dependencies and exact readiness stages", () => {
expect(
JSON.stringify(publicInputSchema("inspect_electron_page")),
).toContain('"source_capture_approved"');
const readiness = publicInputSchema("evaluate_reconstruction_readiness");
expect(readiness).toMatchObject({
allOf: [
{
properties: {
stages: {
allOf: expect.arrayContaining([
expect.objectContaining({ minContains: 1, maxContains: 1 }),
]),
},
},
},
],
});
expect(JSON.stringify(readiness)).toContain('"minContains":1');
const bundleSchema = JSON.stringify(
publicInputSchema("analyze_web_bundle"),
);
expect(bundleSchema).toContain('"include_console_text"');
expect(bundleSchema).toContain('"console_text_approved"');
expect(bundleSchema).toContain('"include_json_body_shapes"');
expect(bundleSchema).toContain('"json_body_schema_approved"');
expect(bundleSchema).toContain('"include_websocket_shapes"');
expect(bundleSchema).toContain('"websocket_shape_approved"');
});
it("requires exactly two export-shape Evidence links", () => {
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "compare_javascript_export_shapes",
);
if (contract === undefined)
throw new Error("Missing export comparison contract");
expect(
JSON.stringify(
z.toJSONSchema(contract.outputSchema, {
target: "draft-07",
unrepresentable: "any",
}),
),
).toContain('"minItems":2');
});
it("requires exactly one source for source-to-bundle comparison", () => {
expect(publicInputSchema("compare_source_to_bundle")).toMatchObject({
oneOf: [
{ required: ["application"] },
{ required: ["application_evidence_id"] },
],
});
});
});
@@ -173,7 +173,13 @@ describe("persistent cross-version investigation workspace", () => {
).resolves.toMatchObject({ ok: true, value: { reused: true } });
await expect(
runCrossVersionInvestigation(
{ ...input, integrity_continue_approved: true },
{
...input,
options: {
...input.options,
change_limit: input.options.change_limit + 1,
},
},
policy(directory),
{ inputRoots: [directory] },
),
@@ -151,8 +151,8 @@ const input = (overrides: Record<string, unknown> = {}) =>
target_id: "page-1",
approved: true,
include_script_sources: true,
source_capture_approved: true,
}),
source_capture_approved: true,
...overrides,
});
@@ -5,7 +5,10 @@ import {
type ProcessCapturePort,
} from "../../../src/application/ProcessPairedExperiment.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
import { parseProcessCapture } from "../../../src/domain/processCapture.js";
import {
parseProcessCapture,
type EnabledProcessExecutionPolicy,
} from "../../../src/domain/processCapture.js";
import {
analyzeProcessRepeatability,
bindProcessScenario,
@@ -47,12 +50,12 @@ const experiment = () =>
],
});
const policy = {
enabled: true,
const policy: EnabledProcessExecutionPolicy = {
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: ["SHARED", "SIDE"],
allowExternalNetwork: false,
networkAccess: "none",
};
describe("paired process experiments", () => {
@@ -11,6 +11,7 @@ import { analyzeJavaScriptApplication } from "../../../src/application/JavaScrip
import { reconcileJavaScriptRuntime } from "../../../src/domain/javascriptRuntimeReconciliation.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascriptRuntimeReconciliationSchemas.js";
import { electronActiveObservationInputSchema } from "../../../src/domain/electronActiveObservation.js";
import { inspectElectronPageInputSchema } from "../../../src/domain/electronObservation.js";
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
import { createElectronActiveObservationFixtureResult } from "../../fixtures/electronActiveObservationResult.js";
@@ -337,7 +338,7 @@ const electronRuntimeEvidence = (
const includeWorker = options.includeWorker ?? true;
const targetId = options.targetId ?? "target-main";
const sourceCaptureApproved = options.sourceCaptureApproved ?? true;
const input = {
const input = inspectElectronPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9223",
allowed_file_roots: [root],
target_id: targetId,
@@ -354,7 +355,7 @@ const electronRuntimeEvidence = (
max_script_source_bytes: 1_048_576,
max_total_script_source_bytes: 4_194_304,
},
};
});
return createElectronEvidence(
"inspect_electron_page",
input,
@@ -7,6 +7,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
MANAGED_RUNTIME_DISABLED,
planManagedRuntimeCorrelationEvidence,
type ManagedRuntimePolicy,
} from "../../../src/application/ManagedRuntimeCorrelationService.js";
@@ -43,7 +44,7 @@ describe("managed runtime correlation planning", () => {
const fixture = inspect(buildManagedPeFixture(), "/tmp/disabled.dll");
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: disabledPolicy,
policy: () => MANAGED_RUNTIME_DISABLED,
authority: undefined,
},
inputFor(fixture.evidence, fixture.method),
@@ -64,7 +65,7 @@ describe("managed runtime correlation planning", () => {
const authority = await authorityFor(directory, executablePath, false);
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: { enabled: true, roots: [directory], executablePath },
policy: () => enabledPolicy(directory, executablePath),
authority,
},
inputFor(fixture.evidence, fixture.method),
@@ -82,10 +83,10 @@ describe("managed runtime correlation planning", () => {
await writeFile(artifactPath, buildManagedPeFixture());
await writeFile(executablePath, "#!/bin/sh\n");
const fixture = inspect(buildManagedPeFixture(), artifactPath);
const policy = { enabled: true, roots: [directory], executablePath };
const policy = enabledPolicy(directory, executablePath);
const authority = await authorityFor(directory, executablePath, true);
const result = await planManagedRuntimeCorrelationEvidence(
{ policy, authority },
{ policy: () => policy, authority },
inputFor(fixture.evidence, fixture.method),
);
@@ -131,7 +132,7 @@ describe("managed runtime correlation planning", () => {
const authority = await authorityFor(directory, executablePath, true);
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: { enabled: true, roots: [directory], executablePath },
policy: () => enabledPolicy(directory, executablePath),
authority,
},
{
@@ -162,7 +163,7 @@ describe("managed runtime correlation planning", () => {
const authority = await authorityFor(directory, executablePath, true);
const result = await planManagedRuntimeCorrelationEvidence(
{
policy: { enabled: true, roots: [directory], executablePath },
policy: () => enabledPolicy(directory, executablePath),
authority,
},
inputFor(fixture.evidence, fixture.method),
@@ -178,11 +179,14 @@ describe("managed runtime correlation planning", () => {
});
});
const disabledPolicy: ManagedRuntimePolicy = {
enabled: false,
roots: [],
executablePath: "/usr/bin/dotnet",
};
const enabledPolicy = (
root: string,
executablePath: string,
): ManagedRuntimePolicy => ({
status: "enabled",
roots: [root],
executablePath,
});
const authorityFor = async (
root: string,
@@ -251,6 +255,9 @@ const inspect = (
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
};
const result = inspectManagedMembersBytes(bytes, target, limits);
const method = result.methods.items[0];
@@ -11,8 +11,8 @@ import {
prepareNodeCharacterization,
} from "../../../src/application/NodeRuntimeCharacterizationService.js";
import type {
EnabledJavaScriptReplayPolicy,
JavaScriptReplayHost,
JavaScriptReplayPolicy,
JavaScriptReplayRunner,
} from "../../../src/application/JavaScriptReplayPlanning.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
@@ -68,6 +68,12 @@ describe("Node runtime characterization", () => {
},
replay: { phase: "plan" },
});
expect(() =>
nodeCharacterizationPreparationOutputSchema.parse({
...output,
plan: { ...output.plan, expected_effect: "bounded-effects" },
}),
).toThrow();
const stale = await executeNodeCharacterization(dependencies, {
execution_approved: true,
@@ -192,13 +198,12 @@ const preparationInput = (
entry_export: "selected",
},
cases: [{ case_id: "trim", arguments: [" value "] }],
approved: false,
},
});
const dependenciesFor = (root: string, onExecute: () => void) => {
const policy: JavaScriptReplayPolicy = {
enabled: true,
const policy: EnabledJavaScriptReplayPolicy = {
status: "enabled",
roots: [root],
nodePath: process.execPath,
bubblewrapPath: process.execPath,
@@ -287,5 +292,5 @@ const dependenciesFor = (root: string, onExecute: () => void) => {
],
),
);
return { policy, host, runner, authority };
return { policy: () => policy, host, runner, authority };
};
@@ -59,9 +59,12 @@ describe("browser runtime configuration", () => {
const result = parseConfig(environment);
if (!result.ok) throw result.error;
expect(result.value.browserScenarioPolicy).toEqual({
enabled: true,
executableRoots: ["/opt/chromium"],
cdpEndpoints: ["http://127.0.0.1:9222"],
status: "enabled",
target: {
access: "launch-or-attach",
executableRoots: ["/opt/chromium"],
cdpEndpoints: ["http://127.0.0.1:9222"],
},
allowedOrigins: ["https://app.example.test"],
allowedEnvironment: ["REA_TEST_PASSWORD"],
});
@@ -89,7 +92,74 @@ describe("browser runtime configuration", () => {
}),
);
});
});
describe("browser scenario policy states", () => {
it("parses each legal browser-scenario access state", () => {
const launch = parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/opt/chromium"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
});
expect(launch).toMatchObject({
ok: true,
value: {
browserScenarioPolicy: {
status: "enabled",
target: { access: "launch" },
},
},
});
const attach = parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
});
expect(attach).toMatchObject({
ok: true,
value: {
browserScenarioPolicy: {
status: "enabled",
target: { access: "attach" },
},
},
});
});
it("rejects enabled browser scenarios without an origin or access path", () => {
expect(
parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/opt/chromium"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON:
'["https://app.example.test"]',
}).ok,
).toBe(false);
});
it("drops inactive browser-scenario settings from the parsed policy", () => {
expect(
parseConfig({
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/ignored/chromium"]',
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON:
'["https://ignored.example.test"]',
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: '["IGNORED_SECRET"]',
}),
).toMatchObject({
ok: true,
value: { browserScenarioPolicy: { status: "disabled" } },
});
});
});
describe("browser runtime input scopes", () => {
it.each([
'["http://localhost:9222"]',
'["http://192.168.1.5:9222"]',
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("capability flags", () => {
it("rejects values outside the exact true/false boundary", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "typo",
REA_BROWSER_OBSERVE_ENABLED: "typo",
REA_BROWSER_SCENARIO_ENABLED: "typo",
REA_ELECTRON_OBSERVE_ENABLED: "typo",
REA_ELECTRON_AUTOMATE_ENABLED: "typo",
REA_V8_INSPECTOR_OBSERVE_ENABLED: "typo",
REA_JAVASCRIPT_REPLAY_ENABLED: "typo",
REA_MANAGED_RUNTIME_ENABLED: "typo",
});
expect(result.ok).toBe(false);
});
});
@@ -29,36 +29,26 @@ describe("runtime configuration", () => {
maxDepth: 32,
maxPathBytes: 4_096,
});
expect(result.value.browserObservationEnabled).toBe(false);
expect(result.value.browserCdpEndpoints).toEqual([]);
expect(result.value.browserAllowedOrigins).toEqual([]);
expect(result.value.browserObservationPolicy).toEqual({
status: "disabled",
});
expect(result.value.browserScenarioPolicy).toEqual({
enabled: false,
executableRoots: [],
cdpEndpoints: [],
allowedOrigins: [],
allowedEnvironment: [],
status: "disabled",
});
expect(result.value.electronObservationPolicy).toEqual({
status: "disabled",
});
expect(result.value.electronObservationEnabled).toBe(false);
expect(result.value.electronCdpEndpoints).toEqual([]);
expect(result.value.electronFileRoots).toEqual([]);
expect(result.value.electronAutomationPolicy).toEqual({
enabled: false,
executableRoots: [],
applicationRoots: [],
status: "disabled",
});
expect(result.value.v8InspectorObservationEnabled).toBe(false);
expect(result.value.v8InspectorEndpoints).toEqual([]);
expect(result.value.v8InspectorFileRoots).toEqual([]);
expect(result.value.v8InspectorAllowedOrigins).toEqual([]);
expect(result.value.javascriptReplayPolicy).toMatchObject({
enabled: false,
roots: [],
expect(result.value.v8InspectorObservationPolicy).toEqual({
status: "disabled",
});
expect(result.value.managedRuntimePolicy).toMatchObject({
enabled: false,
roots: [],
executablePath: "/usr/bin/dotnet",
expect(result.value.javascriptReplayPolicy).toEqual({
status: "disabled",
});
expect(result.value.managedRuntimePolicy).toEqual({
status: "disabled",
});
}
});
@@ -161,7 +151,7 @@ describe("active Electron permission configuration", () => {
});
if (!result.ok) throw result.error;
expect(result.value.electronAutomationPolicy).toEqual({
enabled: true,
status: "enabled",
executableRoots: ["/opt/electron"],
applicationRoots: ["/tmp/apps"],
});
@@ -204,6 +194,30 @@ describe("active Electron permission configuration", () => {
}).ok,
).toBe(false);
});
it("requires both root sets only for enabled Electron automation", () => {
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/tmp/apps"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/opt/electron"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/ignored/bin"]',
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/ignored/app"]',
}),
).toMatchObject({
ok: true,
value: { electronAutomationPolicy: { status: "disabled" } },
});
});
});
describe("runtime permission configuration", () => {
@@ -245,6 +259,11 @@ describe("runtime permission configuration", () => {
REA_JAVASCRIPT_REPLAY_NODE_PATH: "/opt/node/bin/node",
});
if (!result.ok) throw result.error;
expect(result.value.javascriptReplayPolicy).toMatchObject({
status: "enabled",
roots: ["/tmp/extracted-modules"],
nodePath: "/opt/node/bin/node",
});
expect(result.value.permissionCeilings).toContainEqual({
capability: "javascript_replay",
roots: ["/tmp/extracted-modules"],
@@ -267,6 +286,24 @@ describe("runtime permission configuration", () => {
);
});
it("requires a source root when JavaScript replay is enabled", () => {
expect(
parseConfig({ REA_JAVASCRIPT_REPLAY_ENABLED: "true" }),
).toMatchObject({ ok: false });
});
it("does not retain dormant JavaScript replay authority", () => {
const result = parseConfig({
REA_JAVASCRIPT_REPLAY_ENABLED: "false",
REA_JAVASCRIPT_REPLAY_ROOTS_JSON: '["/tmp/extracted-modules"]',
REA_JAVASCRIPT_REPLAY_NODE_PATH: "/opt/node/bin/node",
});
if (!result.ok) throw result.error;
expect(result.value.javascriptReplayPolicy).toEqual({
status: "disabled",
});
});
it("rejects relative JavaScript replay roots and executables", () => {
expect(
parseConfig({ REA_JAVASCRIPT_REPLAY_ROOTS_JSON: '["relative/module"]' })
@@ -287,7 +324,7 @@ describe("runtime target configuration", () => {
});
if (!result.ok) throw result.error;
expect(result.value.managedRuntimePolicy).toEqual({
enabled: true,
status: "enabled",
roots: ["/tmp/managed-targets"],
executablePath: "/opt/dotnet/dotnet",
});
@@ -318,6 +355,23 @@ describe("runtime target configuration", () => {
).toBe(false);
});
it("requires a non-empty root set only for enabled managed runtime correlation", () => {
const enabled = parseConfig({ REA_MANAGED_RUNTIME_ENABLED: "true" });
expect(enabled.ok).toBe(false);
if (!enabled.ok)
expect(enabled.error.message).toContain("at least one absolute root");
expect(
parseConfig({
REA_MANAGED_RUNTIME_ROOTS_JSON: '["/ignored/while-disabled"]',
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "/ignored/dotnet",
}),
).toMatchObject({
ok: true,
value: { managedRuntimePolicy: { status: "disabled" } },
});
});
it("rejects relative Electron file roots", () => {
expect(
parseConfig({ REA_ELECTRON_FILE_ROOTS_JSON: '["relative/app"]' }).ok,
@@ -344,11 +398,7 @@ describe("runtime target configuration", () => {
logLevel: "info",
artifactNativeMountEnabled: false,
processExecutionPolicy: {
enabled: false,
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
allowExternalNetwork: false,
status: "disabled",
},
evidenceFilePolicy: {
roots: [],
@@ -0,0 +1,153 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("passive browser observation policy", () => {
it("requires both endpoint and origin scopes when enabled", () => {
expect(
parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
}).ok,
).toBe(false);
});
it("parses one enabled policy and drops inactive settings", () => {
expect(
parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
}),
).toMatchObject({
ok: true,
value: {
browserObservationPolicy: {
status: "enabled",
cdpEndpoints: ["http://127.0.0.1:9222"],
allowedOrigins: ["https://app.example.test"],
},
},
});
expect(
parseConfig({
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_ALLOWED_ORIGINS_JSON: '["https://ignored.example.test"]',
}),
).toMatchObject({
ok: true,
value: { browserObservationPolicy: { status: "disabled" } },
});
});
});
describe("passive Electron observation policy", () => {
it("requires both endpoint and file-root scopes when enabled", () => {
expect(
parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_FILE_ROOTS_JSON: '["/tmp/electron-app"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
}).ok,
).toBe(false);
});
it("parses one enabled policy and drops inactive settings", () => {
expect(
parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
REA_ELECTRON_FILE_ROOTS_JSON: '["/tmp/electron-app"]',
}),
).toMatchObject({
ok: true,
value: {
electronObservationPolicy: {
status: "enabled",
cdpEndpoints: ["http://127.0.0.1:9223"],
fileRoots: ["/tmp/electron-app"],
},
},
});
expect(
parseConfig({
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
REA_ELECTRON_FILE_ROOTS_JSON: '["/ignored/electron-app"]',
}),
).toMatchObject({
ok: true,
value: { electronObservationPolicy: { status: "disabled" } },
});
});
});
describe("passive V8 Inspector observation policy", () => {
const endpoint = {
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: '["http://127.0.0.1:9229"]',
} as const;
it("requires an endpoint and at least one target-location scope", () => {
expect(
parseConfig({
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]',
}).ok,
).toBe(false);
expect(parseConfig(endpoint).ok).toBe(false);
});
it.each([
["files", { REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]' }],
[
"origins",
{
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON:
'["https://renderer.example.test"]',
},
],
[
"files-and-origins",
{
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]',
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON:
'["https://renderer.example.test"]',
},
],
] as const)("parses the %s location variant", (scope, environment) => {
expect(parseConfig({ ...endpoint, ...environment })).toMatchObject({
ok: true,
value: {
v8InspectorObservationPolicy: {
status: "enabled",
locations: { scope },
},
},
});
});
it("drops inactive endpoint and location settings", () => {
expect(
parseConfig({
REA_V8_INSPECTOR_ENDPOINTS_JSON: '["http://127.0.0.1:9229"]',
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/ignored/node-app"]',
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON:
'["https://ignored.example.test"]',
}),
).toMatchObject({
ok: true,
value: { v8InspectorObservationPolicy: { status: "disabled" } },
});
});
});
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("process capture configuration", () => {
it("parses all authority required by enabled capture", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "true",
REA_PROCESS_EXECUTABLE_ROOTS_JSON: '["/opt/tools"]',
REA_PROCESS_WORKING_ROOTS_JSON: '["/tmp/work"]',
REA_PROCESS_ALLOWED_ENV_JSON: '["TOKEN"]',
REA_PROCESS_ALLOW_EXTERNAL_NETWORK: "true",
});
if (!result.ok) throw result.error;
expect(result.value.processExecutionPolicy).toEqual({
status: "enabled",
executableRoots: ["/opt/tools"],
workingRoots: ["/tmp/work"],
allowedEnvironment: ["TOKEN"],
networkAccess: "external",
});
});
it("requires both authority roots when capture is enabled", () => {
expect(parseConfig({ REA_PROCESS_CAPTURE_ENABLED: "true" })).toMatchObject({
ok: false,
});
});
it("does not retain dormant process-capture authority", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "false",
REA_PROCESS_EXECUTABLE_ROOTS_JSON: '["/opt/tools"]',
REA_PROCESS_WORKING_ROOTS_JSON: '["/tmp/work"]',
REA_PROCESS_ALLOWED_ENV_JSON: '["TOKEN"]',
REA_PROCESS_ALLOW_EXTERNAL_NETWORK: "true",
});
if (!result.ok) throw result.error;
expect(result.value.processExecutionPolicy).toEqual({
status: "disabled",
});
});
});
@@ -189,6 +189,8 @@ const fixtureTarget: BinaryTarget = {
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
};
const fixtureMembers = inspectManagedMembersBytes(
fixtureBytes,