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
@@ -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",
});
});
});