test: overhaul deterministic suite architecture
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { listBrowserTargets } from "../../../src/application/BrowserObservationService.js";
|
||||
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
|
||||
import { CdpCaptureEvents } from "../../../src/browser/CdpCaptureEvents.js";
|
||||
import { ingestElectronScriptEvent } from "../../../src/browser/CdpElectronScriptEvents.js";
|
||||
import {
|
||||
browserEndpointSchema,
|
||||
browserOriginSchema,
|
||||
inspectWebPageInputSchema,
|
||||
isLiteralLoopbackHostname,
|
||||
listBrowserTargetsInputSchema,
|
||||
sanitizeBrowserUrl,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
|
||||
describe("browser observation contracts", () => {
|
||||
it("normalizes exact HTTP origins without accepting broader URL scopes", () => {
|
||||
expect(browserOriginSchema.parse("https://Example.COM:443")).toBe(
|
||||
"https://example.com",
|
||||
);
|
||||
expect(browserOriginSchema.parse("http://example.com:80")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
for (const value of [
|
||||
"https://*.example.com",
|
||||
"https://example.com/path",
|
||||
"https://example.com/?token=secret",
|
||||
"https://user:pass@example.com",
|
||||
"file:///tmp/page.html",
|
||||
])
|
||||
expect(browserOriginSchema.safeParse(value).success, value).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts only literal loopback HTTP CDP endpoints", () => {
|
||||
expect(browserEndpointSchema.parse("http://127.0.0.1:9222")).toBe(
|
||||
"http://127.0.0.1:9222",
|
||||
);
|
||||
expect(browserEndpointSchema.parse("http://[::1]:9222")).toBe(
|
||||
"http://[::1]:9222",
|
||||
);
|
||||
for (const value of [
|
||||
"http://localhost:9222",
|
||||
"http://192.168.1.2:9222",
|
||||
"https://127.0.0.1:9222",
|
||||
"http://127.0.0.1:9222/json/list",
|
||||
"http://user:pass@127.0.0.1:9222",
|
||||
])
|
||||
expect(browserEndpointSchema.safeParse(value).success, value).toBe(false);
|
||||
});
|
||||
|
||||
it("recognizes bracketed and normalized IPv6 loopback hostnames", () => {
|
||||
for (const hostname of ["127.0.0.1", "[::1]", "::1"])
|
||||
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(true);
|
||||
for (const hostname of ["localhost", "127.0.0.2", "::2"])
|
||||
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(false);
|
||||
});
|
||||
|
||||
it("requests loopback authority for an IPv6-only browser origin", async () => {
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "http://[::1]:3000";
|
||||
const ceiling = {
|
||||
capability: "browser_observe" as const,
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [endpoint, origin],
|
||||
network: "loopback" as const,
|
||||
mount: false,
|
||||
};
|
||||
const authority = await createPermissionAuthority(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:browser_observe",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const result = await listBrowserTargets(
|
||||
undefined,
|
||||
authority.value,
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCapabilityUnavailableError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("applies conservative bounded defaults to public tool input", () => {
|
||||
expect(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
approved: true,
|
||||
}),
|
||||
).toEqual({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
expect(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
observation_ms: 500,
|
||||
include_accessibility_text: false,
|
||||
include_console_text: false,
|
||||
console_text_approved: false,
|
||||
include_json_body_shapes: false,
|
||||
json_body_schema_approved: false,
|
||||
include_websocket_shapes: false,
|
||||
websocket_shape_approved: false,
|
||||
include_script_sources: false,
|
||||
include_storage_keys: false,
|
||||
limits: {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_ax_nodes: 2_000,
|
||||
max_ax_text_field_bytes: 1_024,
|
||||
max_total_ax_text_bytes: 65_536,
|
||||
max_scripts: 200,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_storage_keys: 1_000,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
max_network_events: 1_000,
|
||||
max_console_events: 200,
|
||||
max_console_text_field_bytes: 1_024,
|
||||
max_total_console_text_bytes: 65_536,
|
||||
max_json_body_bytes: 1_048_576,
|
||||
max_total_json_body_bytes: 4_194_304,
|
||||
max_json_shape_nodes: 5_000,
|
||||
max_json_shape_depth: 20,
|
||||
max_websocket_events: 500,
|
||||
max_websocket_shape_bytes: 65_536,
|
||||
max_total_websocket_shape_bytes: 1_048_576,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser observation sensitive surfaces and retention", () => {
|
||||
it("requires independent approval for each sensitive capture surface", () => {
|
||||
const base = {
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
};
|
||||
for (const input of [
|
||||
{ include_console_text: true },
|
||||
{ include_json_body_shapes: true },
|
||||
{ include_websocket_shapes: true },
|
||||
{ include_storage_fingerprints: true },
|
||||
])
|
||||
expect(
|
||||
inspectWebPageInputSchema.safeParse({ ...base, ...input }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("requires an independent literal approval for screenshot pixels", () => {
|
||||
const input = {
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
};
|
||||
expect(captureWebScreenshotInputSchema.safeParse(input).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
captureWebScreenshotInputSchema.safeParse({
|
||||
...input,
|
||||
screenshot_approved: true,
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("removes stale frame attribution when CDP destroys execution contexts", () => {
|
||||
const request = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const browser = new CdpCaptureEvents(
|
||||
request,
|
||||
new Set(["https://app.example.test"]),
|
||||
);
|
||||
browser.beginAuthorizedFrame("frame-old");
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextDestroyed",
|
||||
params: { executionContextId: 7 },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Debugger.scriptParsed",
|
||||
params: {
|
||||
scriptId: "script-1",
|
||||
url: "https://app.example.test/app.js",
|
||||
executionContextId: 7,
|
||||
},
|
||||
});
|
||||
const script = browser.scripts.get("script-1");
|
||||
if (script === undefined) throw new TypeError("Expected captured script");
|
||||
expect(browser.frameForScript(script, new Set(["frame-old"]))).toBeNull();
|
||||
|
||||
const electronFrames = new Map<string, string>();
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
ingestElectronScriptEvent({
|
||||
event: {
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
},
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
ingestElectronScriptEvent({
|
||||
event: { method: "Runtime.executionContextsCleared", params: {} },
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
expect(electronFrames.size).toBe(0);
|
||||
});
|
||||
|
||||
it("removes credentials, query values, and fragments from observed URLs", () => {
|
||||
expect(
|
||||
sanitizeBrowserUrl(
|
||||
"https://user:pass@app.example.test/path?token=secret&mode=full#part",
|
||||
),
|
||||
).toEqual({
|
||||
url: "https://app.example.test/path?mode=%5BREDACTED%5D&token=%5BREDACTED%5D",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: ["mode", "token"],
|
||||
redacted: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds retained URL and query-name metadata", () => {
|
||||
const longName = `a${"x".repeat(400)}`;
|
||||
const parameters = [
|
||||
`${longName}=secret`,
|
||||
...Array.from(
|
||||
{ length: 300 },
|
||||
(_value, index) => `k${String(index).padStart(3, "0")}=secret`,
|
||||
),
|
||||
].join("&");
|
||||
const sanitized = sanitizeBrowserUrl(
|
||||
`https://app.example.test/path?${parameters}`,
|
||||
);
|
||||
expect(sanitized.query_parameter_names).toHaveLength(256);
|
||||
expect(
|
||||
sanitized.query_parameter_names.every((name) => name.length <= 256),
|
||||
).toBe(true);
|
||||
expect(sanitized.url).not.toContain("secret");
|
||||
|
||||
const oversized = sanitizeBrowserUrl(
|
||||
`https://app.example.test/${"p".repeat(70_000)}`,
|
||||
);
|
||||
expect(oversized.origin).toBe("https://app.example.test");
|
||||
expect(oversized.url.length).toBeLessThanOrEqual(131_072);
|
||||
expect(oversized.redacted).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BrowserScenarioSecrets } from "../../../src/browser/BrowserScenarioSecrets.js";
|
||||
import { browserScenarioSchema } from "../../../src/domain/browserScenario.js";
|
||||
|
||||
const secret = (secret_id: string) => ({ source: "secret", secret_id });
|
||||
const literal = (value: string) => ({
|
||||
source: "literal",
|
||||
value,
|
||||
classification: "public",
|
||||
});
|
||||
|
||||
const baseScenario = () => ({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium/chrome",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: {
|
||||
url: "https://app.example.test/",
|
||||
query: [{ name: "token", value: secret("session") }],
|
||||
},
|
||||
allowed_origins: ["https://api.example.test", "https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "dark",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "login",
|
||||
action: "fill",
|
||||
locator: { kind: "test_id", value: "password" },
|
||||
value: secret("login_input"),
|
||||
},
|
||||
{
|
||||
step_id: "submit",
|
||||
action: "click",
|
||||
locator: {
|
||||
kind: "role",
|
||||
role: "button",
|
||||
name: "Sign in",
|
||||
exact: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
step_id: "dashboard",
|
||||
action: "goto",
|
||||
destination: { url: "https://app.example.test/dashboard" },
|
||||
wait_until: "load",
|
||||
},
|
||||
],
|
||||
storage: {
|
||||
cookies: [
|
||||
{
|
||||
name: "sid",
|
||||
value: secret("cookie"),
|
||||
destination: { url: "https://app.example.test/" },
|
||||
http_only: true,
|
||||
secure: true,
|
||||
same_site: "Lax",
|
||||
},
|
||||
],
|
||||
local_storage: [
|
||||
{
|
||||
origin: "https://app.example.test",
|
||||
entries: [{ name: "theme", value: literal("dark") }],
|
||||
},
|
||||
],
|
||||
},
|
||||
request_replay: {
|
||||
mode: "exact",
|
||||
unmatched: "abort",
|
||||
routes: [
|
||||
{
|
||||
route_id: "profile",
|
||||
method: "GET",
|
||||
request: { url: "https://api.example.test/profile" },
|
||||
response: {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [
|
||||
{
|
||||
name: "content-type",
|
||||
value: literal("application/json"),
|
||||
},
|
||||
],
|
||||
body: literal('{"name":"Ada"}'),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
secrets: [
|
||||
{
|
||||
secret_id: "session",
|
||||
environment_variable: "REA_TEST_SESSION",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
{
|
||||
secret_id: "login_input",
|
||||
environment_variable: "REA_TEST_PASSWORD",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
{
|
||||
secret_id: "cookie",
|
||||
environment_variable: "REA_TEST_COOKIE",
|
||||
purpose: "storage",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: ["token"],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: ["screenshot", "url", "accessibility"],
|
||||
at_end: ["dom", "storage"],
|
||||
events: ["console", "page-errors", "network", "websockets"],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 60_000,
|
||||
action_timeout_ms: 5_000,
|
||||
navigation_timeout_ms: 10_000,
|
||||
max_events: 2_000,
|
||||
max_frames: 100,
|
||||
max_workers: 20,
|
||||
max_popups: 10,
|
||||
max_websockets: 100,
|
||||
max_dom_nodes: 10_000,
|
||||
max_accessibility_nodes: 10_000,
|
||||
max_screenshots: 16,
|
||||
max_screenshot_bytes: 4 * 1_024 * 1_024,
|
||||
max_storage_entries: 256,
|
||||
max_total_metadata_bytes: 4 * 1_024 * 1_024,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema", () => {
|
||||
it("accepts and normalizes a bounded declared scenario", () => {
|
||||
const parsed = browserScenarioSchema.parse(baseScenario());
|
||||
expect(parsed.allowed_origins).toEqual([
|
||||
"https://api.example.test",
|
||||
"https://app.example.test",
|
||||
]);
|
||||
expect(parsed.environment.viewport.device_scale_factor).toBe(1);
|
||||
expect(parsed.redaction.header_names).toEqual([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"proxy-authorization",
|
||||
"set-cookie",
|
||||
]);
|
||||
});
|
||||
|
||||
it("redacts overlapping secrets longest-first", () => {
|
||||
const scenario = browserScenarioSchema.parse(baseScenario());
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {
|
||||
REA_TEST_SESSION: "prefix",
|
||||
REA_TEST_PASSWORD: "prefix-suffix",
|
||||
REA_TEST_COOKIE: "cookie",
|
||||
});
|
||||
expect(secrets?.redact("prefix-suffix")).toBe("[REDACTED:login_input]");
|
||||
});
|
||||
|
||||
it("rejects unsupported actions", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions = [
|
||||
{
|
||||
step_id: "script",
|
||||
action: "evaluate",
|
||||
expression: "document.cookie",
|
||||
} as never,
|
||||
];
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects every undeclared navigation, storage, and replay origin", () => {
|
||||
for (const mutate of [
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.start_url.url = "https://other.example.test/";
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.actions[2] = {
|
||||
...scenario.actions[2],
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.storage.local_storage[0]!.origin =
|
||||
"https://other.example.test";
|
||||
},
|
||||
(scenario: ReturnType<typeof baseScenario>) => {
|
||||
scenario.request_replay.routes[0]!.request.url =
|
||||
"https://other.example.test/data";
|
||||
},
|
||||
]) {
|
||||
const scenario = baseScenario();
|
||||
mutate(scenario);
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects redirects outside declared origins", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "redirect",
|
||||
status: 302,
|
||||
destination: { url: "https://other.example.test/" },
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects missing, duplicate, and unused secret declarations", () => {
|
||||
const missing = baseScenario();
|
||||
missing.secrets = missing.secrets.filter(
|
||||
({ secret_id }) => secret_id !== "login_input",
|
||||
);
|
||||
expect(browserScenarioSchema.safeParse(missing).success).toBe(false);
|
||||
|
||||
const duplicate = baseScenario();
|
||||
duplicate.secrets.push({ ...duplicate.secrets[0]! });
|
||||
expect(browserScenarioSchema.safeParse(duplicate).success).toBe(false);
|
||||
|
||||
const unused = baseScenario();
|
||||
unused.secrets.push({
|
||||
secret_id: "unused",
|
||||
environment_variable: "REA_TEST_UNUSED",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
});
|
||||
expect(browserScenarioSchema.safeParse(unused).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects secret query values without named redaction", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.redaction.query_parameter_names = [];
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects literal credential headers and provider-owned headers", () => {
|
||||
for (const name of ["authorization", "content-length"]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.request_replay.routes[0]!.response = {
|
||||
kind: "response",
|
||||
status: 200,
|
||||
headers: [{ name, value: literal("raw") }],
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects duplicate replay response headers case-insensitively", () => {
|
||||
const scenario = baseScenario();
|
||||
const response = scenario.request_replay.routes[0]!.response;
|
||||
if (response.kind !== "response")
|
||||
throw new Error("Expected replay response fixture");
|
||||
response.headers.push({
|
||||
name: "Content-Type",
|
||||
value: literal("text/plain"),
|
||||
});
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects raw secret-shaped action values", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.actions[0] = {
|
||||
...scenario.actions[0],
|
||||
value: "literal-input",
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects embedded URL credentials and query values", () => {
|
||||
const credentialedUrl = new URL("https://app.example.test/");
|
||||
credentialedUrl.username = String.fromCodePoint(120);
|
||||
for (const url of [
|
||||
credentialedUrl.href,
|
||||
"https://app.example.test/?token=raw",
|
||||
]) {
|
||||
const scenario = baseScenario();
|
||||
scenario.start_url.url = url;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("requires explicit external ownership for CDP connections", () => {
|
||||
const scenario = baseScenario();
|
||||
scenario.browser = {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
} as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(true);
|
||||
|
||||
scenario.browser.cleanup = "close-browser" as never;
|
||||
expect(browserScenarioSchema.safeParse(scenario).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareBrowserScenarios,
|
||||
compareBrowserScenariosInputSchema,
|
||||
} from "../../../src/domain/browserScenarioDiff.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
type BrowserScenarioCapture,
|
||||
} from "../../../src/domain/browserScenarioCapture.js";
|
||||
|
||||
describe("browser scenario comparison", () => {
|
||||
it("records canonical literal normalization and ignores declared volatile fields", () => {
|
||||
const before = scenarioCapture({
|
||||
domText: "<main data-build='build-123'>Settings</main>",
|
||||
elapsedMs: 11,
|
||||
eventSequence: 3,
|
||||
});
|
||||
const after = scenarioCapture({
|
||||
domText: "<main data-build='build-456'>Settings</main>",
|
||||
elapsedMs: 900,
|
||||
eventSequence: 88,
|
||||
});
|
||||
const rules = [
|
||||
{
|
||||
rule_id: "new-build",
|
||||
artifacts: ["dom"] as const,
|
||||
match: "build-456",
|
||||
replacement: "[BUILD]",
|
||||
},
|
||||
{
|
||||
rule_id: "old-build",
|
||||
artifacts: ["dom"] as const,
|
||||
match: "build-123",
|
||||
replacement: "[BUILD]",
|
||||
},
|
||||
];
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: { rules },
|
||||
}),
|
||||
);
|
||||
const reordered = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: {
|
||||
rules: [...rules].reverse().map((rule) => ({
|
||||
...rule,
|
||||
artifacts: [...rule.artifacts].reverse(),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("unchanged");
|
||||
expect(compared.alignment.status).toBe("aligned");
|
||||
expect(compared.artifact_diffs.total).toBe(0);
|
||||
expect(compared.normalization).toMatchObject({
|
||||
rules: [
|
||||
{ rule_id: "new-build", artifacts: ["dom"] },
|
||||
{ rule_id: "old-build", artifacts: ["dom"] },
|
||||
],
|
||||
});
|
||||
expect(reordered.normalization.sha256).toBe(compared.normalization.sha256);
|
||||
});
|
||||
|
||||
it("exposes action mismatches and normalized artifact-level changes", () => {
|
||||
const before = scenarioCapture({
|
||||
domText: "<main>Settings</main>",
|
||||
});
|
||||
const after = scenarioCapture({
|
||||
action: "dblclick",
|
||||
domText: "<main>Advanced settings</main>",
|
||||
});
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
}),
|
||||
);
|
||||
const step = compared.steps.find(
|
||||
({ step_id: stepId }) => stepId === "open-settings",
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("changed");
|
||||
expect(compared.alignment).toMatchObject({
|
||||
status: "partial",
|
||||
failures: [
|
||||
expect.objectContaining({
|
||||
code: "action_mismatch",
|
||||
step_id: "open-settings",
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(step).toMatchObject({
|
||||
status: "changed",
|
||||
artifact_diffs: [
|
||||
expect.objectContaining({
|
||||
artifact: "action_state",
|
||||
status: "changed",
|
||||
}),
|
||||
expect.objectContaining({ artifact: "dom", status: "changed" }),
|
||||
],
|
||||
});
|
||||
expect(compared.artifact_diffs).toEqual({
|
||||
total: 2,
|
||||
retained: 2,
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser scenario comparison validation", () => {
|
||||
it("reports missing aligned steps without claiming equality", () => {
|
||||
const before = scenarioCapture({});
|
||||
const after = scenarioCapture({ stepId: "open-profile" });
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("unknown");
|
||||
expect(compared.alignment).toMatchObject({
|
||||
status: "partial",
|
||||
aligned_steps: 1,
|
||||
before_only: ["open-settings"],
|
||||
after_only: ["open-profile"],
|
||||
failures: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
code: "missing_before_step",
|
||||
step_id: "open-profile",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "missing_after_step",
|
||||
step_id: "open-settings",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects ambiguous input pairs and duplicate normalization rule IDs", () => {
|
||||
const capture = scenarioCapture({});
|
||||
expect(
|
||||
compareBrowserScenariosInputSchema.safeParse({
|
||||
before_scenario: capture,
|
||||
after_scenario: capture,
|
||||
normalization: {
|
||||
rules: [
|
||||
{
|
||||
rule_id: "volatile",
|
||||
artifacts: ["dom"],
|
||||
match: "one",
|
||||
replacement: "[VALUE]",
|
||||
},
|
||||
{
|
||||
rule_id: "volatile",
|
||||
artifacts: ["url"],
|
||||
match: "two",
|
||||
replacement: "[VALUE]",
|
||||
},
|
||||
],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
interface ScenarioCaptureOptions {
|
||||
readonly stepId?: string;
|
||||
readonly action?: string;
|
||||
readonly domText?: string;
|
||||
readonly elapsedMs?: number;
|
||||
readonly eventSequence?: number;
|
||||
}
|
||||
|
||||
const scenarioCapture = (
|
||||
options: ScenarioCaptureOptions,
|
||||
): BrowserScenarioCapture => {
|
||||
const url = {
|
||||
url: "https://app.example.test/settings",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: [],
|
||||
redacted: false,
|
||||
};
|
||||
const completeness = {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
const artifacts = (text: string) => ({
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "captured", value: textArtifact(text) },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "captured", value: url },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
});
|
||||
const eventSequence = options.eventSequence ?? 1;
|
||||
return browserScenarioCaptureSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
product: "Chromium",
|
||||
version: "149.0",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: "https://app.example.test",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
action_count: 1,
|
||||
secret_references: [],
|
||||
},
|
||||
duration_ms: options.elapsedMs ?? 10,
|
||||
steps: [
|
||||
{
|
||||
step_index: 0,
|
||||
step_id: "scenario_start",
|
||||
action: "scenario_start",
|
||||
status: "completed",
|
||||
elapsed_ms: 0,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts: artifacts("<main>Ready</main>"),
|
||||
completeness,
|
||||
},
|
||||
{
|
||||
step_index: 1,
|
||||
step_id: options.stepId ?? "open-settings",
|
||||
action: options.action ?? "click",
|
||||
status: "completed",
|
||||
elapsed_ms: options.elapsedMs ?? 10,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: eventSequence,
|
||||
event_sequence_end: eventSequence,
|
||||
artifacts: artifacts(options.domText ?? "<main>Settings</main>"),
|
||||
completeness,
|
||||
},
|
||||
],
|
||||
events: {
|
||||
retained: 1,
|
||||
dropped: 0,
|
||||
items: [
|
||||
{
|
||||
sequence: eventSequence,
|
||||
step_index: 1,
|
||||
kind: "console",
|
||||
level: "info",
|
||||
text: "settings-ready",
|
||||
url: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
completeness,
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
const textArtifact = (text: string) => {
|
||||
const bytes = Buffer.from(text);
|
||||
return {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.byteLength,
|
||||
text,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
authorizedElectronFile,
|
||||
canonicalElectronRoots,
|
||||
} from "../../../src/browser/ElectronFileScope.js";
|
||||
|
||||
describe("Electron file scope", () => {
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts canonical files within a root and rejects escape forms", async () => {
|
||||
const base = await createTestTempDirectory("rea-electron-scope-");
|
||||
temporary.push(base);
|
||||
const root = join(base, "root");
|
||||
const outside = join(base, "outside");
|
||||
await mkdir(root);
|
||||
await mkdir(outside);
|
||||
const allowed = join(root, "index.html");
|
||||
const denied = join(outside, "secret.html");
|
||||
await writeFile(allowed, "allowed");
|
||||
await writeFile(denied, "denied");
|
||||
await symlink(denied, join(root, "escape.html"));
|
||||
const roots = await canonicalElectronRoots([root]);
|
||||
|
||||
expect(
|
||||
await authorizedElectronFile(pathToFileURL(allowed).href, roots),
|
||||
).toBe(allowed);
|
||||
expect(
|
||||
await authorizedElectronFile(pathToFileURL(denied).href, roots),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
await authorizedElectronFile(
|
||||
pathToFileURL(join(root, "escape.html")).href,
|
||||
roots,
|
||||
),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
await authorizedElectronFile("file://server/share/index.html", roots),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
await authorizedElectronFile("file:///tmp/root%2Findex.html", roots),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,374 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
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 { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches renderer, frame, script bytes, and worker without claiming execution", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeEvidence = electronRuntimeEvidence(fixture, SOURCE);
|
||||
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
javascriptRuntimeReconciliationResultSchema.parse(result),
|
||||
).not.toThrow();
|
||||
expect(result.summary).toMatchObject({
|
||||
runtime_targets: 1,
|
||||
runtime_frames: 1,
|
||||
runtime_scripts: 1,
|
||||
runtime_workers: 1,
|
||||
matched: 2,
|
||||
ambiguous: 2,
|
||||
unmatched: 0,
|
||||
});
|
||||
expect(result.reconciliations).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entity_kind: "script",
|
||||
status: "matched",
|
||||
basis: "content-and-location",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entity_kind: "worker",
|
||||
status: "matched",
|
||||
basis: "artifact-path",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entity_kind: "target",
|
||||
status: "ambiguous",
|
||||
reason: "ambiguous-static-candidates",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.static_load_states).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "javascript-asset",
|
||||
status: "loaded",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.limitations.join(" ")).toMatch(
|
||||
/not reported as executed|not code reachability/u,
|
||||
);
|
||||
expect(
|
||||
result.graph.edges
|
||||
.filter(({ relation }) => relation === "observed_as")
|
||||
.every(
|
||||
({ evidence }) =>
|
||||
evidence.authority === "cross-layer-reconciliation" &&
|
||||
evidence.state === "inferred",
|
||||
),
|
||||
).toBe(true);
|
||||
const worker = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "worker",
|
||||
);
|
||||
const frame = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "frame",
|
||||
);
|
||||
expect(result.graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: frame?.runtime_node_id,
|
||||
target_node_id: worker?.runtime_node_id,
|
||||
relation: "contains",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a captured digest disagreement instead of accepting a path match", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeEvidence = electronRuntimeEvidence(
|
||||
fixture,
|
||||
"export const observed = 'different';\n",
|
||||
);
|
||||
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
const script = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "script",
|
||||
);
|
||||
|
||||
expect(script).toMatchObject({
|
||||
status: "unmatched",
|
||||
reason: "captured-content-disagrees-with-static-location",
|
||||
});
|
||||
expect(script?.candidate_static_nodes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps source-map declarations outside primary matching authority", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeEvidence = electronRuntimeEvidence(fixture, SOURCE);
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
|
||||
expect(result.source_map_authority).toMatchObject({
|
||||
used_for_primary_matching: false,
|
||||
static_layers_with_read_approval: 0,
|
||||
runtime_script_declarations: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("imports an operator-provided cache layer through an explicit file mapping", async () => {
|
||||
const application = await applicationFixture();
|
||||
const cache = await createTestTempDirectory("rea-runtime-cache-static-");
|
||||
const runtimeCache = await createTestTempDirectory("rea-runtime-cache-live-");
|
||||
temporary.push(application, cache, runtimeCache);
|
||||
const cacheSource = "export const cachedFeature = 'fixture';\n";
|
||||
await mkdir(join(cache, "mapped"));
|
||||
await Promise.all([
|
||||
writeFile(join(cache, "mapped", "chunk.js"), cacheSource),
|
||||
writeFile(join(cache, "outside.js"), "export const outside = true;\n"),
|
||||
writeFile(join(runtimeCache, "chunk.js"), cacheSource),
|
||||
writeFile(join(runtimeCache, "index.html"), "<script></script>"),
|
||||
]);
|
||||
const applicationEvidence = await analyzeFixture(application);
|
||||
const cacheEvidence = await analyzeFixture(cache);
|
||||
const runtimeEvidence = electronRuntimeEvidence(runtimeCache, cacheSource, {
|
||||
scriptFile: "chunk.js",
|
||||
includeWorker: false,
|
||||
});
|
||||
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [
|
||||
{ role: "application", analysis: applicationEvidence },
|
||||
{
|
||||
role: "cache",
|
||||
analysis: cacheEvidence,
|
||||
runtime_mappings: [
|
||||
{
|
||||
kind: "file-root",
|
||||
root: runtimeCache,
|
||||
artifact_prefix: "mapped",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
const script = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "script",
|
||||
);
|
||||
const cacheLayer = result.static_layers.find(({ role }) => role === "cache");
|
||||
|
||||
expect(script).toMatchObject({
|
||||
status: "matched",
|
||||
basis: "content-and-location",
|
||||
static_layer_id: cacheLayer?.layer_id,
|
||||
});
|
||||
const outside = result.graph.nodes.find(
|
||||
(node) =>
|
||||
node.kind === "javascript-asset" &&
|
||||
node.observations.some(
|
||||
({ properties }) => properties.path === "outside.js",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
result.static_load_states.find(
|
||||
({ static_node_id: nodeId }) => nodeId === outside?.node_id,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
reason: "layer-outside-runtime-scope",
|
||||
});
|
||||
});
|
||||
|
||||
const applicationFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-runtime-reconciliation-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-runtime-reconciliation-fixture",
|
||||
version: "1.0.0",
|
||||
renderer: "index.html",
|
||||
}),
|
||||
),
|
||||
writeFile(join(root, "index.html"), "<script src='./app.js'></script>"),
|
||||
writeFile(join(root, "app.js"), SOURCE),
|
||||
writeFile(join(root, "worker.js"), "self.onmessage = () => undefined;\n"),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
|
||||
const analyzeFixture = async (root: string) => {
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
|
||||
const electronRuntimeEvidence = (
|
||||
root: string,
|
||||
source: string,
|
||||
options: {
|
||||
readonly scriptFile?: string;
|
||||
readonly includeWorker?: boolean;
|
||||
readonly targetId?: string;
|
||||
readonly sourceCaptureApproved?: boolean;
|
||||
readonly workersUnavailable?: boolean;
|
||||
} = {},
|
||||
) => {
|
||||
const scriptFile = options.scriptFile ?? "app.js";
|
||||
const includeWorker = options.includeWorker ?? true;
|
||||
const targetId = options.targetId ?? "target-main";
|
||||
const sourceCaptureApproved = options.sourceCaptureApproved ?? true;
|
||||
const input = {
|
||||
cdp_endpoint: "http://127.0.0.1:9223",
|
||||
allowed_file_roots: [root],
|
||||
target_id: targetId,
|
||||
approved: true as const,
|
||||
observation_ms: 100,
|
||||
include_script_sources: sourceCaptureApproved,
|
||||
source_capture_approved: sourceCaptureApproved,
|
||||
limits: {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_scripts: 500,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
},
|
||||
};
|
||||
return createElectronEvidence(
|
||||
"inspect_electron_page",
|
||||
input,
|
||||
{
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
product: "Electron/fixture",
|
||||
protocol_version: "1.3",
|
||||
revision: "fixture",
|
||||
user_agent: "Electron fixture",
|
||||
js_version: "13",
|
||||
},
|
||||
target: {
|
||||
target_id: targetId,
|
||||
type: "page",
|
||||
title: "Fixture",
|
||||
file_path: join(root, "index.html"),
|
||||
attached: false,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: "2026-07-15T00:00:00.000Z",
|
||||
ended_at: "2026-07-15T00:00:00.100Z",
|
||||
observation_ms: 100,
|
||||
},
|
||||
completeness: options.workersUnavailable
|
||||
? {
|
||||
...completeCapture(),
|
||||
status: "attach_limited" as const,
|
||||
conditions: ["attach_limited" as const],
|
||||
attach_limited_sections: ["workers" as const],
|
||||
unavailable_sections: ["workers" as const],
|
||||
}
|
||||
: completeCapture(),
|
||||
frames: [
|
||||
{
|
||||
frame_id: "frame-main",
|
||||
parent_frame_id: null,
|
||||
file_path: join(root, "index.html"),
|
||||
},
|
||||
],
|
||||
dom: { total_nodes: 0, nodes: [] },
|
||||
scripts: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
script_key: `electron_script_${"1".repeat(64)}`,
|
||||
frame_id: "frame-main",
|
||||
file_path: join(root, scriptFile),
|
||||
cdp_hash: "fixture",
|
||||
length: Buffer.byteLength(source),
|
||||
is_module: true,
|
||||
language: "JavaScript",
|
||||
source: {
|
||||
included: true as const,
|
||||
artifact: createWebTextArtifact(source, "text/javascript"),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
resources: [],
|
||||
workers: includeWorker
|
||||
? [
|
||||
{
|
||||
target_id: "worker-main",
|
||||
type: "worker",
|
||||
file_path: join(root, "worker.js"),
|
||||
attached: false,
|
||||
opener_target_id: targetId,
|
||||
parent_frame_id: "frame-main",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
limitations: ["Synthetic passive capture fixture."],
|
||||
},
|
||||
{
|
||||
id: "rea-cdp-electron",
|
||||
name: "REA Electron file-page CDP observation provider",
|
||||
version: "1",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const completeCapture = () => ({
|
||||
status: "complete_within_window" as const,
|
||||
conditions: ["complete_within_window" as const],
|
||||
policy_filtered_sections: [],
|
||||
attach_limited_sections: [],
|
||||
truncated_sections: [],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: {
|
||||
scripts: 0,
|
||||
network_requests: 0,
|
||||
console_events: 0,
|
||||
websocket_connections: 0,
|
||||
websocket_frames: 0,
|
||||
webmcp_tools: 0,
|
||||
timeline_events: 0,
|
||||
total: 0,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
planManagedRuntimeCorrelationEvidence,
|
||||
type ManagedRuntimePolicy,
|
||||
} from "../../../src/application/ManagedRuntimeCorrelationService.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationProviders.js";
|
||||
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { managedRuntimeCorrelationResultSchema } from "../../../src/domain/managedRuntimeCorrelation.js";
|
||||
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import type { PermissionCeiling } from "../../../src/domain/permissionPolicy.js";
|
||||
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
describe("managed runtime correlation planning", () => {
|
||||
it("fails closed while the managed runtime authority is disabled", async () => {
|
||||
const fixture = inspect(buildManagedPeFixture(), "/tmp/disabled.dll");
|
||||
const result = await planManagedRuntimeCorrelationEvidence(
|
||||
{
|
||||
policy: disabledPolicy,
|
||||
authority: undefined,
|
||||
},
|
||||
inputFor(fixture.evidence, fixture.method),
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError");
|
||||
});
|
||||
|
||||
it("requires an explicit managed_runtime grant under an enabled ceiling", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-runtime-");
|
||||
const artifactPath = join(directory, "fixture.dll");
|
||||
const executablePath = join(directory, "dotnet");
|
||||
await writeFile(artifactPath, buildManagedPeFixture());
|
||||
await writeFile(executablePath, "#!/bin/sh\n");
|
||||
const fixture = inspect(buildManagedPeFixture(), artifactPath);
|
||||
const authority = await authorityFor(directory, executablePath, false);
|
||||
const result = await planManagedRuntimeCorrelationEvidence(
|
||||
{
|
||||
policy: { enabled: true, roots: [directory], executablePath },
|
||||
authority,
|
||||
},
|
||||
inputFor(fixture.evidence, fixture.method),
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("PermissionRequiredError");
|
||||
});
|
||||
|
||||
it("records an exact-build non-executing admission plan when authorized", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-runtime-");
|
||||
const artifactPath = join(directory, "fixture.dll");
|
||||
const executablePath = join(directory, "dotnet");
|
||||
await writeFile(artifactPath, buildManagedPeFixture());
|
||||
await writeFile(executablePath, "#!/bin/sh\n");
|
||||
const fixture = inspect(buildManagedPeFixture(), artifactPath);
|
||||
const policy = { enabled: true, roots: [directory], executablePath };
|
||||
const authority = await authorityFor(directory, executablePath, true);
|
||||
const result = await planManagedRuntimeCorrelationEvidence(
|
||||
{ policy, authority },
|
||||
inputFor(fixture.evidence, fixture.method),
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.operation).toBe("plan_managed_runtime_correlation");
|
||||
expect(result.value.confidence).toBe("derived");
|
||||
expect(result.value.authority).toBe("analyst-inference");
|
||||
const plan = managedRuntimeCorrelationResultSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
expect(plan).toMatchObject({
|
||||
executed: false,
|
||||
authority_model: {
|
||||
capability: "managed_runtime",
|
||||
default_enabled: false,
|
||||
per_call_approval_required: true,
|
||||
},
|
||||
method_lock: {
|
||||
token: "0x06000001",
|
||||
exact_build_required: true,
|
||||
},
|
||||
requested_runtime: {
|
||||
effect: "instrumentation",
|
||||
executable_path: executablePath,
|
||||
network: "none",
|
||||
},
|
||||
effect_taxonomy: {
|
||||
instruments_code: true,
|
||||
invokes_target_code: false,
|
||||
},
|
||||
unsupported_until_executor_exists: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a method lock that no longer matches static Evidence", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-runtime-");
|
||||
const artifactPath = join(directory, "fixture.dll");
|
||||
const executablePath = join(directory, "dotnet");
|
||||
await writeFile(artifactPath, buildManagedPeFixture());
|
||||
await writeFile(executablePath, "#!/bin/sh\n");
|
||||
const fixture = inspect(buildManagedPeFixture(), artifactPath);
|
||||
const authority = await authorityFor(directory, executablePath, true);
|
||||
const result = await planManagedRuntimeCorrelationEvidence(
|
||||
{
|
||||
policy: { enabled: true, roots: [directory], executablePath },
|
||||
authority,
|
||||
},
|
||||
{
|
||||
...inputFor(fixture.evidence, fixture.method),
|
||||
method: {
|
||||
...inputFor(fixture.evidence, fixture.method).method,
|
||||
normalized_il_sha256: "0".repeat(64),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
|
||||
it("rejects a runtime lock for instruction-limited CIL", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-runtime-");
|
||||
const artifactPath = join(directory, "fixture.dll");
|
||||
const executablePath = join(directory, "dotnet");
|
||||
const bytes = buildManagedPeFixture();
|
||||
await writeFile(artifactPath, bytes);
|
||||
await writeFile(executablePath, "#!/bin/sh\n");
|
||||
const fixture = inspect(bytes, artifactPath, {
|
||||
...memberLimits,
|
||||
maxMethodInstructions: 1,
|
||||
});
|
||||
const authority = await authorityFor(directory, executablePath, true);
|
||||
const result = await planManagedRuntimeCorrelationEvidence(
|
||||
{
|
||||
policy: { enabled: true, roots: [directory], executablePath },
|
||||
authority,
|
||||
},
|
||||
inputFor(fixture.evidence, fixture.method),
|
||||
);
|
||||
|
||||
expect(fixture.method.body).toMatchObject({
|
||||
status: "partial",
|
||||
normalized_il_sha256: null,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
});
|
||||
|
||||
const disabledPolicy: ManagedRuntimePolicy = {
|
||||
enabled: false,
|
||||
roots: [],
|
||||
executablePath: "/usr/bin/dotnet",
|
||||
};
|
||||
|
||||
const authorityFor = async (
|
||||
root: string,
|
||||
executablePath: string,
|
||||
granted: boolean,
|
||||
) => {
|
||||
const ceiling: PermissionCeiling = {
|
||||
capability: "managed_runtime",
|
||||
roots: [root],
|
||||
executables: [executablePath],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
};
|
||||
const authority = await createPermissionAuthority(
|
||||
[ceiling],
|
||||
granted
|
||||
? [
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:managed_runtime",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
if (!authority.ok) throw authority.error;
|
||||
return authority.value;
|
||||
};
|
||||
|
||||
const inputFor = (
|
||||
staticMembers: ReturnType<typeof createEvidence>,
|
||||
method: ReturnType<typeof inspect>["method"],
|
||||
) => ({
|
||||
static_members: staticMembers,
|
||||
method: {
|
||||
token: method.token,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
},
|
||||
requested_effect: "instrumentation" as const,
|
||||
host: {
|
||||
os: "linux" as const,
|
||||
clr_family: "dotnet" as const,
|
||||
architecture: "x86_64" as const,
|
||||
},
|
||||
bounds: {
|
||||
timeout_ms: 5_000,
|
||||
max_threads: 32,
|
||||
max_output_bytes: 65_536,
|
||||
allow_network: false as const,
|
||||
allow_ui: false as const,
|
||||
},
|
||||
});
|
||||
|
||||
const inspect = (
|
||||
bytes: Buffer,
|
||||
path: string,
|
||||
limits: typeof memberLimits = memberLimits,
|
||||
) => {
|
||||
const target: BinaryTarget = {
|
||||
path,
|
||||
sha256: hash(bytes),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
};
|
||||
const result = inspectManagedMembersBytes(bytes, target, limits);
|
||||
const method = result.methods.items[0];
|
||||
if (method === undefined) throw new Error("fixture has no method");
|
||||
return {
|
||||
result,
|
||||
method,
|
||||
evidence: createEvidence(target, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result,
|
||||
rawResult: null,
|
||||
limitations: result.limitations,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const hash = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
@@ -0,0 +1,291 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
executeNodeCharacterization,
|
||||
prepareNodeCharacterization,
|
||||
} from "../../../src/application/NodeRuntimeCharacterizationService.js";
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
} from "../../../src/application/JavaScriptReplayPlanning.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import {
|
||||
nodeCharacterizationPreparationInputSchema,
|
||||
nodeCharacterizationPreparationOutputSchema,
|
||||
} from "../../../src/domain/nodeRuntimeCharacterization.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const sha256 = (value: Uint8Array): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Node runtime characterization", () => {
|
||||
it("prepares without execution, then executes only the approved exact plan", async () => {
|
||||
const fixture = await createFixture();
|
||||
let executions = 0;
|
||||
const dependencies = dependenciesFor(fixture.root, () => {
|
||||
executions += 1;
|
||||
});
|
||||
const input = preparationInput(fixture);
|
||||
|
||||
const prepared = await prepareNodeCharacterization(dependencies, input);
|
||||
expect(prepared.ok).toBe(true);
|
||||
expect(executions).toBe(0);
|
||||
if (!prepared.ok) throw prepared.error;
|
||||
const output = nodeCharacterizationPreparationOutputSchema.parse(
|
||||
prepared.value,
|
||||
);
|
||||
expect(output).toMatchObject({
|
||||
phase: "preparation",
|
||||
plan: {
|
||||
preparation_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
runtime: { family: "ecmascript", provider_id: "node-javascript" },
|
||||
authority: {
|
||||
preparation_approved: true,
|
||||
execution_approved: false,
|
||||
},
|
||||
},
|
||||
transformation: {
|
||||
original_sha256: fixture.sha256,
|
||||
output_format: "commonjs-factory",
|
||||
},
|
||||
transformation_evidence: {
|
||||
predicate_type: "rea.javascript-export-transformation/v1",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
replay: { phase: "plan" },
|
||||
});
|
||||
|
||||
const stale = await executeNodeCharacterization(dependencies, {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: "0".repeat(64),
|
||||
preparation: input,
|
||||
});
|
||||
expect(stale.ok).toBe(false);
|
||||
expect(!stale.ok && stale.error._tag).toBe("ReplayPlanStaleError");
|
||||
expect(executions).toBe(0);
|
||||
|
||||
const executed = await executeNodeCharacterization(dependencies, {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: output.plan.plan_sha256,
|
||||
preparation: input,
|
||||
});
|
||||
expect(executed.ok && executed.value).toMatchObject({
|
||||
phase: "execution",
|
||||
replay: {
|
||||
phase: "execute",
|
||||
evidence: { authority: "controlled-replay" },
|
||||
},
|
||||
evidence: {
|
||||
predicate_type: "rea.runtime-characterization/v1",
|
||||
authority: "controlled-replay",
|
||||
},
|
||||
});
|
||||
expect(executions).toBe(1);
|
||||
expect(await readFile(fixture.path)).toEqual(Buffer.from(fixture.bytes));
|
||||
});
|
||||
|
||||
it("rejects aliases that cannot fit the provider-neutral plan identity", async () => {
|
||||
const input = preparationInput(await createFixture());
|
||||
expect(() =>
|
||||
nodeCharacterizationPreparationInputSchema.parse({
|
||||
...input,
|
||||
selected_alias: "a".repeat(201),
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("maps replay-only alias syntax to a provider-neutral module identity", async () => {
|
||||
const fixture = await createFixture();
|
||||
const input = preparationInput(fixture);
|
||||
const alias = "@scope/pkg";
|
||||
const prepared = await prepareNodeCharacterization(
|
||||
dependenciesFor(fixture.root, () => undefined),
|
||||
{
|
||||
...input,
|
||||
selected_alias: alias,
|
||||
replay: {
|
||||
...input.replay,
|
||||
left: {
|
||||
...input.replay.left,
|
||||
entry_alias: alias,
|
||||
modules: input.replay.left.modules.map((module) => ({
|
||||
...module,
|
||||
alias,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(prepared.ok && prepared.value).toMatchObject({
|
||||
plan: {
|
||||
callable: {
|
||||
module_id: expect.stringMatching(/^module\/[a-f0-9]{64}$/u),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const createFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-characterization-");
|
||||
roots.push(root);
|
||||
const path = join(root, "bundle.js");
|
||||
const source = "const hidden = (value) => value.trim();";
|
||||
const selected = "(value) => value.trim()";
|
||||
const bytes = new TextEncoder().encode(source);
|
||||
await writeFile(path, bytes);
|
||||
const byteStart = source.indexOf(selected);
|
||||
return {
|
||||
root,
|
||||
path,
|
||||
bytes,
|
||||
sha256: sha256(bytes),
|
||||
byteStart,
|
||||
selectedBytes: new TextEncoder().encode(selected),
|
||||
};
|
||||
};
|
||||
|
||||
const preparationInput = (
|
||||
fixture: Awaited<ReturnType<typeof createFixture>>,
|
||||
) => ({
|
||||
preparation_approved: true,
|
||||
selected_alias: "bundle",
|
||||
expected_effect: "pure" as const,
|
||||
instrumentation: {
|
||||
artifact_path: fixture.path,
|
||||
artifact_sha256: fixture.sha256,
|
||||
selection: {
|
||||
byte_start: fixture.byteStart,
|
||||
byte_end: fixture.byteStart + fixture.selectedBytes.byteLength,
|
||||
selected_sha256: sha256(fixture.selectedBytes),
|
||||
export_name: "selected",
|
||||
},
|
||||
},
|
||||
replay: {
|
||||
mode: "plan" as const,
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "bundle",
|
||||
path: fixture.path,
|
||||
format: "commonjs-factory" as const,
|
||||
role: "module" as const,
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "bundle",
|
||||
entry_export: "selected",
|
||||
},
|
||||
cases: [{ case_id: "trim", arguments: [" value "] }],
|
||||
approved: false,
|
||||
},
|
||||
});
|
||||
|
||||
const dependenciesFor = (root: string, onExecute: () => void) => {
|
||||
const policy: JavaScriptReplayPolicy = {
|
||||
enabled: true,
|
||||
roots: [root],
|
||||
nodePath: process.execPath,
|
||||
bubblewrapPath: process.execPath,
|
||||
systemdRunPath: process.execPath,
|
||||
systemctlPath: process.execPath,
|
||||
shellPath: process.execPath,
|
||||
};
|
||||
const host: JavaScriptReplayHost = {
|
||||
readSource: async (path, maximumBytes) => {
|
||||
const canonicalPath = await realpath(path);
|
||||
const bytes = await readFile(canonicalPath);
|
||||
if (bytes.byteLength > maximumBytes)
|
||||
throw new RangeError("fixture limit");
|
||||
return { canonicalPath, bytes };
|
||||
},
|
||||
identifyExecutable: async (path) => ({
|
||||
path,
|
||||
version: "fixture-node-24",
|
||||
sha256: "1".repeat(64),
|
||||
}),
|
||||
identifyWorker: async () => ({
|
||||
path: "/fixture/worker.js",
|
||||
version: "fixture-worker",
|
||||
sha256: "2".repeat(64),
|
||||
}),
|
||||
identifyRuntimeClosure: async (path) => [
|
||||
{
|
||||
sourcePath: path,
|
||||
destinationPath: "/runtime/node",
|
||||
sha256: "1".repeat(64),
|
||||
},
|
||||
],
|
||||
seccompDigest: () => "3".repeat(64),
|
||||
probe: async () => undefined,
|
||||
};
|
||||
const runner: JavaScriptReplayRunner = {
|
||||
execute: async (prepared) => {
|
||||
onExecute();
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
case_id: "trim",
|
||||
outcome: "return",
|
||||
value: "value",
|
||||
input_sha256:
|
||||
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
|
||||
output_sha256: "4".repeat(64),
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
stderr: "",
|
||||
termination: "completed",
|
||||
cleanup: { state: "complete", residual_resources: [] },
|
||||
limitations: ["fixture runner"],
|
||||
reproducer: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
const ceiling = {
|
||||
capability: "javascript_replay" as const,
|
||||
roots: [root],
|
||||
executables: [
|
||||
policy.nodePath,
|
||||
policy.bubblewrapPath,
|
||||
policy.systemdRunPath,
|
||||
policy.systemctlPath,
|
||||
policy.shellPath,
|
||||
],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
};
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:javascript_replay",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
return { policy, host, runner, authority };
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
import { deflateSync } from "node:zlib";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { comparePngScreenshots } from "../../../src/browser/PngVisualDiff.js";
|
||||
import {
|
||||
compareWebScreenshotsInputSchema,
|
||||
createWebScreenshotArtifact,
|
||||
} from "../../../src/domain/webScreenshot.js";
|
||||
|
||||
describe("PNG visual diff", () => {
|
||||
it("reports exact changed-pixel and channel metrics", () => {
|
||||
const before = artifact(1, 1, [0, 0, 0, 255]);
|
||||
const after = artifact(1, 1, [10, 0, 0, 255]);
|
||||
const result = comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({ before, after }),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "different",
|
||||
compared_pixels: 1,
|
||||
changed_pixels: 1,
|
||||
changed_ratio: 1,
|
||||
maximum_channel_delta: 10,
|
||||
mean_absolute_channel_delta: 2.5,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies a channel threshold and reports dimension mismatch", () => {
|
||||
const one = artifact(1, 1, [0, 0, 0, 255]);
|
||||
const near = artifact(1, 1, [2, 0, 0, 255]);
|
||||
expect(
|
||||
comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({
|
||||
before: one,
|
||||
after: near,
|
||||
channel_threshold: 2,
|
||||
}),
|
||||
).status,
|
||||
).toBe("identical");
|
||||
expect(
|
||||
comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({
|
||||
before: one,
|
||||
after: artifact(2, 1, [0, 0, 0, 255, 0, 0, 0, 255]),
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ status: "dimension_mismatch", compared_pixels: 0 });
|
||||
});
|
||||
|
||||
it("rejects images above the caller's decoded pixel limit", () => {
|
||||
const image = artifact(2, 1, [0, 0, 0, 255, 0, 0, 0, 255]);
|
||||
expect(() =>
|
||||
comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({
|
||||
before: image,
|
||||
after: image,
|
||||
maximum_pixels: 1,
|
||||
}),
|
||||
),
|
||||
).toThrow("oversized PNG");
|
||||
});
|
||||
});
|
||||
|
||||
const artifact = (width: number, height: number, pixels: readonly number[]) =>
|
||||
createWebScreenshotArtifact(png(width, height, pixels));
|
||||
|
||||
const png = (
|
||||
width: number,
|
||||
height: number,
|
||||
pixels: readonly number[],
|
||||
): Buffer => {
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(width, 0);
|
||||
header.writeUInt32BE(height, 4);
|
||||
header[8] = 8;
|
||||
header[9] = 6;
|
||||
const rows: number[] = [];
|
||||
for (let row = 0; row < height; row += 1)
|
||||
rows.push(0, ...pixels.slice(row * width * 4, (row + 1) * width * 4));
|
||||
return Buffer.concat([
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
|
||||
chunk("IHDR", header),
|
||||
chunk("IDAT", deflateSync(Buffer.from(rows))),
|
||||
chunk("IEND", Buffer.alloc(0)),
|
||||
]);
|
||||
};
|
||||
|
||||
const chunk = (type: string, data: Buffer): Buffer => {
|
||||
const result = Buffer.alloc(12 + data.byteLength);
|
||||
result.writeUInt32BE(data.byteLength, 0);
|
||||
result.write(type, 4, 4, "ascii");
|
||||
data.copy(result, 8);
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "../../../src/domain/replayMachine.js";
|
||||
|
||||
const loginMachine = () => ({
|
||||
initial_state: "waiting_for_login",
|
||||
states: [
|
||||
{ name: "waiting_for_login" },
|
||||
{ name: "waiting_for_api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "login",
|
||||
from: "waiting_for_login",
|
||||
to: "waiting_for_api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "api",
|
||||
from: "waiting_for_api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
describe("replay machine", () => {
|
||||
it("accepts a bounded, reachable, data-only login machine", () => {
|
||||
expect(replayMachineSchema.parse(loginMachine())).toMatchObject({
|
||||
initial_state: "waiting_for_login",
|
||||
max_transitions: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"unreachable state",
|
||||
(machine: ReturnType<typeof loginMachine>) =>
|
||||
machine.states.push({ name: "orphan", terminal: false }),
|
||||
"unreachable",
|
||||
],
|
||||
[
|
||||
"ambiguous transition",
|
||||
(machine: ReturnType<typeof loginMachine>) => {
|
||||
const transition = machine.transitions[0];
|
||||
if (transition === undefined) throw new TypeError("missing transition");
|
||||
machine.transitions.push({ ...transition, id: "login_2" });
|
||||
},
|
||||
"ambiguous",
|
||||
],
|
||||
[
|
||||
"outgoing terminal transition",
|
||||
(machine: ReturnType<typeof loginMachine>) => {
|
||||
const transition = machine.transitions[0];
|
||||
if (transition === undefined) throw new TypeError("missing transition");
|
||||
machine.transitions.push({
|
||||
...transition,
|
||||
id: "restart",
|
||||
from: "complete",
|
||||
to: "waiting_for_login",
|
||||
trigger: { protocol: "http", method: "POST", path: "/restart" },
|
||||
});
|
||||
},
|
||||
"terminal",
|
||||
],
|
||||
[
|
||||
"unknown guard variable",
|
||||
(machine: ReturnType<typeof loginMachine>) => {
|
||||
const guard = machine.transitions[1]?.guards?.[0];
|
||||
if (guard === undefined) throw new TypeError("missing guard");
|
||||
guard.variable = "missing";
|
||||
},
|
||||
"executable path before use",
|
||||
],
|
||||
[
|
||||
"missing terminal state",
|
||||
(machine: ReturnType<typeof loginMachine>) => {
|
||||
const state = machine.states[2];
|
||||
if (state === undefined) throw new TypeError("missing state");
|
||||
state.terminal = false;
|
||||
},
|
||||
"terminal state",
|
||||
],
|
||||
])("rejects %s", (_name, mutate, message) => {
|
||||
const machine = loginMachine();
|
||||
mutate(machine);
|
||||
expect(() => replayMachineSchema.parse(machine)).toThrow(message);
|
||||
});
|
||||
|
||||
it("canonicalizes methods and headers while refusing persisted credential matchers", () => {
|
||||
const canonical = {
|
||||
...loginMachine(),
|
||||
transitions: loginMachine().transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...transition,
|
||||
trigger: {
|
||||
protocol: "http",
|
||||
method: "post",
|
||||
path: "/login",
|
||||
headers: { "X-Request-ID": "fixture" },
|
||||
},
|
||||
}
|
||||
: transition,
|
||||
),
|
||||
};
|
||||
expect(
|
||||
replayMachineSchema.parse(canonical).transitions[0]?.trigger,
|
||||
).toMatchObject({
|
||||
method: "POST",
|
||||
headers: { "x-request-id": "fixture" },
|
||||
});
|
||||
const credentialMatcher = {
|
||||
...loginMachine(),
|
||||
transitions: loginMachine().transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...transition,
|
||||
trigger: {
|
||||
protocol: "http",
|
||||
method: "POST",
|
||||
path: "/login",
|
||||
headers: { Authorization: "test-auth-token" },
|
||||
},
|
||||
}
|
||||
: transition,
|
||||
),
|
||||
};
|
||||
expect(() => replayMachineSchema.parse(credentialMatcher)).toThrow(
|
||||
/secret alias/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("replay machine validation", () => {
|
||||
it("rejects sensitive captures sourced from persisted action JSON", () => {
|
||||
const candidate = loginMachine();
|
||||
const capture = candidate.transitions[0]?.captures?.[0];
|
||||
if (capture === undefined) throw new TypeError("missing capture");
|
||||
capture.value = { source: "action_json", path: ["token"] };
|
||||
|
||||
expect(() => replayMachineSchema.parse(candidate)).toThrow(
|
||||
/literal action JSON/u,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid header name", { "bad header": "value" }],
|
||||
["invalid header value", { "x-test": "value\nsmuggled" }],
|
||||
])("rejects %s in HTTP responses", (_name, headers) => {
|
||||
const candidate = loginMachine();
|
||||
const action = candidate.transitions[0]?.actions[0];
|
||||
if (action === undefined || action.type !== "http_response")
|
||||
throw new TypeError("missing HTTP response");
|
||||
action.headers = headers;
|
||||
|
||||
expect(() => replayMachineSchema.parse(candidate)).toThrow();
|
||||
});
|
||||
|
||||
it("rejects unknown fields at nested machine boundaries", () => {
|
||||
const candidate = loginMachine();
|
||||
const action = candidate.transitions[0]?.actions[0];
|
||||
if (action === undefined) throw new TypeError("missing action");
|
||||
|
||||
expect(() =>
|
||||
replayMachineSchema.parse({
|
||||
...candidate,
|
||||
transitions: [
|
||||
{
|
||||
...candidate.transitions[0],
|
||||
actions: [{ ...action, unexpected: true }],
|
||||
},
|
||||
candidate.transitions[1],
|
||||
],
|
||||
}),
|
||||
).toThrow(/Unrecognized key/u);
|
||||
});
|
||||
|
||||
it("reports duplicate transition IDs as structured validation", () => {
|
||||
const candidate = loginMachine();
|
||||
const first = candidate.transitions[0];
|
||||
const second = candidate.transitions[1];
|
||||
if (first === undefined || second === undefined)
|
||||
throw new TypeError("missing transition");
|
||||
|
||||
expect(
|
||||
replayMachineSchema.safeParse({
|
||||
...candidate,
|
||||
transitions: [first, { ...second, id: first.id }],
|
||||
}),
|
||||
).toMatchObject({ success: false });
|
||||
});
|
||||
|
||||
it("rejects guards whose capture is not available before the transition", () => {
|
||||
const candidate = loginMachine();
|
||||
const first = candidate.transitions[0];
|
||||
if (first === undefined) throw new TypeError("missing transition");
|
||||
first.guards = [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
];
|
||||
|
||||
expect(() => replayMachineSchema.parse(candidate)).toThrow(
|
||||
/executable path before use/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects ambiguous header triggers regardless of key order", () => {
|
||||
const candidate = loginMachine();
|
||||
const first = candidate.transitions[0];
|
||||
if (first === undefined) throw new TypeError("missing transition");
|
||||
const withHeaders = {
|
||||
...first,
|
||||
trigger: {
|
||||
protocol: "http" as const,
|
||||
method: "POST",
|
||||
path: "/login",
|
||||
headers: { accept: "json", "x-mode": "test" },
|
||||
},
|
||||
};
|
||||
|
||||
expect(() =>
|
||||
replayMachineSchema.parse({
|
||||
...candidate,
|
||||
transitions: [
|
||||
withHeaders,
|
||||
{
|
||||
...withHeaders,
|
||||
id: "login_duplicate",
|
||||
trigger: {
|
||||
...withHeaders.trigger,
|
||||
headers: { "x-mode": "test", accept: "json" },
|
||||
},
|
||||
},
|
||||
candidate.transitions[1],
|
||||
],
|
||||
}),
|
||||
).toThrow(/ambiguous/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createRuntimeCharacterizationPlan,
|
||||
parseRuntimeCharacterizationPlan,
|
||||
} from "../../../src/domain/runtimeCharacterization.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
|
||||
describe("provider-neutral runtime characterization plan", () => {
|
||||
it("commits preparation separately from execution approval", () => {
|
||||
const plan = createRuntimeCharacterizationPlan({
|
||||
schema_version: 1,
|
||||
preparation_sha256: digest("5"),
|
||||
artifact: {
|
||||
path: "/approved/app.js",
|
||||
sha256: digest("1"),
|
||||
byte_length: 100,
|
||||
},
|
||||
runtime: {
|
||||
family: "ecmascript",
|
||||
provider_id: "node-javascript",
|
||||
executable_path: "/usr/bin/node",
|
||||
executable_sha256: digest("2"),
|
||||
version: "v24.18.0",
|
||||
profile_sha256: digest("3"),
|
||||
},
|
||||
callable: {
|
||||
callable_id: "bundle.module7.hidden",
|
||||
module_id: "bundle.module7",
|
||||
export_name: "selected",
|
||||
semantic_evidence_id: null,
|
||||
selector_sha256: digest("4"),
|
||||
},
|
||||
working_directory: "/owned/work",
|
||||
isolated_home: "/owned/home",
|
||||
expected_effect: "pure",
|
||||
allowed_boundaries: [],
|
||||
limits: {
|
||||
max_calls: 2,
|
||||
max_processes: 0,
|
||||
max_files: 0,
|
||||
max_bytes: 65_536,
|
||||
max_handles: 32,
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 1_000,
|
||||
},
|
||||
determinism: {
|
||||
clock: "fixed",
|
||||
randomness: "seeded",
|
||||
identifiers: "deterministic",
|
||||
seed: 7,
|
||||
},
|
||||
authority: {
|
||||
preparation_approved: true,
|
||||
execution_approved: false,
|
||||
network: "none",
|
||||
provider_owned_process_only: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parseRuntimeCharacterizationPlan(plan)).toEqual(plan);
|
||||
expect(plan.authority.execution_approved).toBe(false);
|
||||
expect(() =>
|
||||
parseRuntimeCharacterizationPlan({
|
||||
...plan,
|
||||
expected_effect: "bounded-effects",
|
||||
}),
|
||||
).toThrow(/digest is invalid/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
TextReader,
|
||||
Uint8ArrayReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipWriter,
|
||||
} from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { runProviderAnalysis } from "../../../src/application/DirectAnalysis.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
identifyRuntimes,
|
||||
runtimeIdentificationResultSchema,
|
||||
} from "../../../src/domain/runtimeIdentification.js";
|
||||
|
||||
describe("runtime identification", () => {
|
||||
it("identifies APK runtime families and exposes missing semantic providers", async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-");
|
||||
const path = join(root, "Fixture.apk");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(
|
||||
"AndroidManifest.xml",
|
||||
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0, 8, 0, 0, 0])),
|
||||
);
|
||||
await writer.add(
|
||||
"classes.dex",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
|
||||
),
|
||||
);
|
||||
await writer.add(
|
||||
"assets/Fixture.class",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]),
|
||||
),
|
||||
);
|
||||
await writer.add(
|
||||
"assets/module.wasm",
|
||||
new Uint8ArrayReader(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])),
|
||||
);
|
||||
await writer.add("assets/main.js", new TextReader("bridge.call();"));
|
||||
await writer.add(
|
||||
"lib/arm64-v8a/libfixture.so",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]),
|
||||
),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {
|
||||
node_limit: 100,
|
||||
occurrence_limit: 100,
|
||||
edge_limit: 100,
|
||||
}),
|
||||
);
|
||||
const first = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
const second = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
expect(first).toEqual(second);
|
||||
expect(runtimeIdentificationResultSchema.parse(first)).toMatchObject({
|
||||
root_format: "apk",
|
||||
coverage: {
|
||||
status: "complete-within-inventory",
|
||||
inventory_complete: true,
|
||||
omitted_observations: 0,
|
||||
},
|
||||
});
|
||||
expect(first.runtimes.map(({ family }) => family)).toEqual([
|
||||
"android",
|
||||
"javascript",
|
||||
"jvm",
|
||||
"native",
|
||||
"webassembly",
|
||||
]);
|
||||
expect(first.runtimes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
family: "android",
|
||||
inspection: "available",
|
||||
provider_id: "rea-android-application",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "jvm",
|
||||
inspection: "provider-missing",
|
||||
provider_id: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "webassembly",
|
||||
inspection: "provider-missing",
|
||||
provider_id: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "javascript",
|
||||
inspection: "available",
|
||||
provider_id: "rea-javascript-application",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
family: "native",
|
||||
inspection: "provider-selection-required",
|
||||
provider_id: null,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports bounded runtime-observation truncation", async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-limit-");
|
||||
const path = join(root, "Fixture.apk");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("one.js", new TextReader("one"));
|
||||
await writer.add("two.js", new TextReader("two"));
|
||||
await writeFile(path, await writer.close());
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const result = identifyRuntimes({
|
||||
inventory_evidence: [inventory],
|
||||
limits: { max_observations: 1 },
|
||||
});
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
omitted_observations: expect.any(Number),
|
||||
});
|
||||
expect(result.coverage.omitted_observations).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("does not route nested DEX content to the APK-only provider", async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-dex-");
|
||||
const path = join(root, "Fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(
|
||||
"classes.dex",
|
||||
new Uint8ArrayReader(
|
||||
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
|
||||
),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const result = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
|
||||
expect(result.runtimes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
family: "android",
|
||||
inspection: "provider-selection-required",
|
||||
provider_id: null,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
|
||||
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import {
|
||||
correlateStaticAndRuntime,
|
||||
staticRuntimeCorrelationResultSchema,
|
||||
} from "../../../src/domain/staticRuntimeCorrelation.js";
|
||||
|
||||
const staticComparison =
|
||||
INVESTIGATION_EXAMPLES.find_changed_behavior.comparisons[0];
|
||||
if (staticComparison === undefined)
|
||||
throw new Error("Missing static comparison fixture");
|
||||
|
||||
const capture = (digit: string): Evidence =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.process-capture/v4",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: { digit },
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: `fixture-${digit}`,
|
||||
platform: "test",
|
||||
architecture: "test",
|
||||
isolation: "process",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const leftCapture = capture("1");
|
||||
const rightCapture = capture("2");
|
||||
|
||||
const processComparison = (
|
||||
terminal: "unchanged" | "changed" | "unknown" | "truncated",
|
||||
): Evidence => {
|
||||
const result = {
|
||||
status: terminal,
|
||||
terminal,
|
||||
interaction: terminal === "truncated" ? "truncated" : "unchanged",
|
||||
exit: terminal === "truncated" ? "truncated" : "unchanged",
|
||||
filesystem: terminal === "truncated" ? "truncated" : "unchanged",
|
||||
protocol: terminal === "truncated" ? "truncated" : "unchanged",
|
||||
process: terminal === "truncated" ? "truncated" : "unchanged",
|
||||
shim: terminal === "truncated" ? "truncated" : "unchanged",
|
||||
first_divergence:
|
||||
terminal === "changed"
|
||||
? {
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
index: 0,
|
||||
left_at_ms: 0,
|
||||
right_at_ms: 0,
|
||||
left: "left",
|
||||
right: "right",
|
||||
}
|
||||
: terminal === "truncated" || terminal === "unknown"
|
||||
? { status: "unknown", reason: "Incomplete fixture." }
|
||||
: { status: "none" },
|
||||
limitations: terminal === "unknown" ? ["Terminal unavailable."] : [],
|
||||
} satisfies JsonValue;
|
||||
return createEvidence(
|
||||
undefined,
|
||||
{
|
||||
id: "rea-process",
|
||||
name: "REA deterministic process harness",
|
||||
version: "3",
|
||||
},
|
||||
{
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: leftCapture.evidence_id,
|
||||
right_evidence_id: rightCapture.evidence_id,
|
||||
},
|
||||
result,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: [leftCapture.evidence_id, rightCapture.evidence_id],
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const mapping = (
|
||||
runtime: Evidence,
|
||||
expected: "cochanged" | "static_only" | "runtime_only" | "both_unchanged",
|
||||
dimension: "terminal" | "interaction" | "exit" | "shim" = "terminal",
|
||||
) => ({
|
||||
static_comparisons: [staticComparison],
|
||||
runtime_comparisons: [runtime],
|
||||
mappings: [
|
||||
{
|
||||
static: {
|
||||
comparison_evidence_id: staticComparison.evidence_id,
|
||||
selector: {
|
||||
kind: "function" as const,
|
||||
dimension: "pseudocode" as const,
|
||||
},
|
||||
},
|
||||
runtime: {
|
||||
comparison_evidence_id: runtime.evidence_id,
|
||||
dimension,
|
||||
},
|
||||
side_alignment: "left_to_left" as const,
|
||||
hypothesis: {
|
||||
statement: "The static edit is associated with terminal behavior.",
|
||||
expected_pattern: expected,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
describe("static/runtime correlation", () => {
|
||||
it("accepts interaction and shim runtime dimensions", () => {
|
||||
const runtime = processComparison("unchanged");
|
||||
expect(
|
||||
correlateStaticAndRuntime(mapping(runtime, "static_only", "interaction")),
|
||||
).toMatchObject({ status: "correlated" });
|
||||
expect(
|
||||
correlateStaticAndRuntime(mapping(runtime, "static_only", "shim")),
|
||||
).toMatchObject({ status: "correlated" });
|
||||
});
|
||||
|
||||
it("keeps consistent cochange as a hypothesis with complete citations", () => {
|
||||
const runtime = processComparison("changed");
|
||||
const result = correlateStaticAndRuntime(mapping(runtime, "cochanged"));
|
||||
expect(staticRuntimeCorrelationResultSchema.parse(result)).toMatchObject({
|
||||
status: "correlated",
|
||||
summary: { hypotheses: 1, contradictions: 0, unresolved: 0 },
|
||||
correlations: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
observed_pattern: "cochanged",
|
||||
classification: "hypothesis",
|
||||
side_alignment: "left_to_left",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.correlations.items[0]?.evidence_links).toEqual(
|
||||
expect.arrayContaining([
|
||||
staticComparison.evidence_id,
|
||||
runtime.evidence_id,
|
||||
leftCapture.evidence_id,
|
||||
rightCapture.evidence_id,
|
||||
]),
|
||||
);
|
||||
expect(result.limitations.join(" ")).toMatch(
|
||||
/does not establish causality/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies an explicit expectation mismatch as contradiction", () => {
|
||||
const result = correlateStaticAndRuntime(
|
||||
mapping(processComparison("unchanged"), "cochanged"),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
status: "contradicted",
|
||||
summary: { hypotheses: 0, contradictions: 1, unresolved: 0 },
|
||||
correlations: {
|
||||
items: [
|
||||
{ observed_pattern: "static_only", classification: "contradiction" },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("lets unknown and truncation dominate rather than imply equivalence", () => {
|
||||
const unknown = correlateStaticAndRuntime(
|
||||
mapping(processComparison("unknown"), "cochanged"),
|
||||
);
|
||||
const truncated = correlateStaticAndRuntime(
|
||||
mapping(processComparison("truncated"), "cochanged"),
|
||||
);
|
||||
expect(unknown).toMatchObject({
|
||||
status: "unknown",
|
||||
correlations: { items: [{ classification: "unresolved_branch" }] },
|
||||
});
|
||||
expect(truncated).toMatchObject({
|
||||
status: "truncated",
|
||||
correlations: { items: [{ observed_pattern: "truncated" }] },
|
||||
});
|
||||
});
|
||||
|
||||
it("is order-stable, paginated, and rejects duplicates and absent selectors", () => {
|
||||
const runtime = processComparison("changed");
|
||||
const base = mapping(runtime, "cochanged");
|
||||
const second = {
|
||||
...base.mappings[0],
|
||||
runtime: { ...base.mappings[0]!.runtime, dimension: "exit" as const },
|
||||
hypothesis: {
|
||||
statement: "The edit is associated with exit behavior.",
|
||||
expected_pattern: "static_only" as const,
|
||||
},
|
||||
};
|
||||
const forward = correlateStaticAndRuntime({
|
||||
...base,
|
||||
mappings: [base.mappings[0], second],
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
});
|
||||
const reversed = correlateStaticAndRuntime({
|
||||
...base,
|
||||
mappings: [second, base.mappings[0]],
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
});
|
||||
expect(reversed).toEqual(forward);
|
||||
expect(forward.correlations).toMatchObject({ total: 2, next_offset: 1 });
|
||||
expect(() =>
|
||||
correlateStaticAndRuntime({
|
||||
...base,
|
||||
mappings: [base.mappings[0], base.mappings[0]],
|
||||
}),
|
||||
).toThrow(/duplicate mappings/u);
|
||||
expect(() =>
|
||||
correlateStaticAndRuntime({
|
||||
...base,
|
||||
mappings: [
|
||||
{
|
||||
...base.mappings[0],
|
||||
static: {
|
||||
...base.mappings[0]!.static,
|
||||
selector: { kind: "function", dimension: "assembly" },
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
correlateStaticAndRuntime({
|
||||
...base,
|
||||
mappings: [
|
||||
{
|
||||
...base.mappings[0],
|
||||
static: {
|
||||
comparison_evidence_id: runtime.evidence_id,
|
||||
selector: { kind: "function", dimension: "pseudocode" },
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/absent static comparison/u);
|
||||
});
|
||||
|
||||
it("rejects comparison citations that disagree with source parameters", () => {
|
||||
const runtime = processComparison("changed");
|
||||
const forged = createEvidence(undefined, runtime.provider, {
|
||||
predicateType: runtime.predicate_type,
|
||||
operation: runtime.operation,
|
||||
parameters: {
|
||||
left_evidence_id: leftCapture.evidence_id,
|
||||
right_evidence_id: staticComparison.evidence_id,
|
||||
},
|
||||
result: runtime.normalized_result,
|
||||
confidence: runtime.confidence,
|
||||
authority: runtime.authority,
|
||||
evidenceLinks: runtime.evidence_links,
|
||||
});
|
||||
const input = mapping(forged, "cochanged");
|
||||
expect(() => correlateStaticAndRuntime(input)).toThrow(
|
||||
/closure disagrees with its source parameters/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import {
|
||||
compareWebCaptures,
|
||||
compareWebCapturesInputSchema,
|
||||
webCaptureDiffSchema,
|
||||
} from "../../../src/domain/webCaptureDiff.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
describe("web capture diff", () => {
|
||||
it("reports stable observed changes while preserving unknown dimensions", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const after = structuredClone(captured.value);
|
||||
after.scripts.items = [];
|
||||
const request = after.network.requests[0];
|
||||
if (request !== undefined) request.status = 204;
|
||||
|
||||
const result = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: after },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.overall_status).toBe("changed");
|
||||
expect(result.dimensions.scripts).toMatchObject({
|
||||
status: "changed",
|
||||
total_changes: 1,
|
||||
changes: [expect.objectContaining({ change: "removed" })],
|
||||
});
|
||||
expect(result.dimensions.network).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
expect(result.dimensions.webmcp).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
const {
|
||||
accessibility: _accessibility,
|
||||
storage: _storage,
|
||||
...legacy
|
||||
} = result.dimensions;
|
||||
const parsedLegacy = webCaptureDiffSchema.parse({
|
||||
...result,
|
||||
dimensions: legacy,
|
||||
});
|
||||
expect(parsedLegacy.dimensions.accessibility.status).toBe("unknown");
|
||||
expect(parsedLegacy.dimensions.storage.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("does not claim unchanged when a relevant section is incomplete", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const incomplete = structuredClone(captured.value);
|
||||
incomplete.completeness.truncated_sections.push("dom");
|
||||
|
||||
const result = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: incomplete },
|
||||
after: { inspection: captured.value },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.dimensions.dom_structure.status).toBe("unknown");
|
||||
expect(result.dimensions.dom_structure.reason).toContain("incomplete");
|
||||
});
|
||||
|
||||
it("ignores transient request IDs and capture-approval state", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const after = structuredClone(captured.value);
|
||||
const request = after.network.requests[0];
|
||||
if (request !== undefined) request.request_id = "different-cdp-request-id";
|
||||
const response = after.metadata.responses[0];
|
||||
if (response !== undefined)
|
||||
response.request_id = "different-cdp-request-id";
|
||||
const script = after.scripts.items[0];
|
||||
if (script !== undefined && !script.source.included)
|
||||
script.source.reason = "different approval explanation";
|
||||
markSectionsComplete(captured.value, ["scripts", "metadata"]);
|
||||
markSectionsComplete(after, ["scripts", "metadata"]);
|
||||
|
||||
const result = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: after },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.dimensions.scripts.status).toBe("unchanged");
|
||||
expect(result.dimensions.metadata.status).toBe("unchanged");
|
||||
expect(result.dimensions.network.status).toBe("unknown");
|
||||
expect(result.dimensions.network.total_changes).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture diff semantics and fingerprints", () => {
|
||||
it("detects accessibility semantics and storage inventory changes", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_accessibility_text: true,
|
||||
include_storage_keys: true,
|
||||
include_storage_fingerprints: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const compareAfter = (after: typeof captured.value) =>
|
||||
compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: after },
|
||||
}),
|
||||
);
|
||||
const roleChanged = structuredClone(captured.value);
|
||||
const namedNode = roleChanged.accessibility.nodes[0];
|
||||
if (namedNode === undefined)
|
||||
throw new Error("Expected accessibility nodes");
|
||||
namedNode.role = "menuitem";
|
||||
|
||||
const nameChanged = structuredClone(captured.value);
|
||||
const renamedNode = nameChanged.accessibility.nodes[0];
|
||||
if (renamedNode === undefined)
|
||||
throw new Error("Expected accessibility nodes");
|
||||
renamedNode.name = "Send report";
|
||||
|
||||
const stateChanged = structuredClone(captured.value);
|
||||
const stateNode = stateChanged.accessibility.nodes[0];
|
||||
const disabledState = stateNode?.states.find(
|
||||
({ name }) => name === "disabled",
|
||||
);
|
||||
if (disabledState === undefined)
|
||||
throw new Error("Expected an accessibility state");
|
||||
disabledState.value = true;
|
||||
|
||||
const hierarchyChanged = structuredClone(captured.value);
|
||||
const childNode = hierarchyChanged.accessibility.nodes[1];
|
||||
if (childNode === undefined)
|
||||
throw new Error("Expected an accessibility child");
|
||||
childNode.parent_id = null;
|
||||
|
||||
const storageChanged = structuredClone(captured.value);
|
||||
storageChanged.storage.local_storage_keys.push("new-key");
|
||||
|
||||
for (const after of [
|
||||
roleChanged,
|
||||
nameChanged,
|
||||
stateChanged,
|
||||
hierarchyChanged,
|
||||
])
|
||||
expect(compareAfter(after).dimensions.accessibility).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [
|
||||
{
|
||||
identity: "accessibility_tree",
|
||||
change: "modified",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(compareAfter(storageChanged).dimensions.storage).toMatchObject({
|
||||
status: "changed",
|
||||
changes: [expect.objectContaining({ change: "added" })],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web capture diff completeness", () => {
|
||||
it("uses complete redacted fingerprints but keeps incomplete evidence unknown", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
browsers.push(browser);
|
||||
const captured = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_accessibility_text: true,
|
||||
include_storage_keys: true,
|
||||
include_storage_fingerprints: true,
|
||||
}),
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const identical = structuredClone(captured.value);
|
||||
const identity = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: identical },
|
||||
}),
|
||||
);
|
||||
expect(identity.dimensions.accessibility.status).toBe("unchanged");
|
||||
expect(identity.dimensions.storage).toMatchObject({
|
||||
status: "unchanged",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const changedFingerprint = structuredClone(captured.value);
|
||||
const fingerprint = changedFingerprint.storage.content_fingerprints.find(
|
||||
({ complete, value_sha256: valueSha256 }) =>
|
||||
complete && valueSha256 !== null,
|
||||
);
|
||||
if (fingerprint === undefined || fingerprint.value_sha256 === null)
|
||||
throw new Error("Expected a complete content fingerprint");
|
||||
fingerprint.value_sha256 = "f".repeat(64);
|
||||
const storageChanged = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: changedFingerprint },
|
||||
}),
|
||||
);
|
||||
expect(storageChanged.dimensions.storage).toMatchObject({
|
||||
status: "changed",
|
||||
total_changes: 1,
|
||||
changes: [expect.objectContaining({ change: "modified" })],
|
||||
});
|
||||
|
||||
const incompleteStorage = structuredClone(captured.value);
|
||||
incompleteStorage.storage.fingerprints_complete = false;
|
||||
const storageUnknown = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: incompleteStorage },
|
||||
}),
|
||||
);
|
||||
expect(storageUnknown.dimensions.storage).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const evidenceQualityChanged = structuredClone(captured.value);
|
||||
evidenceQualityChanged.storage.fingerprints_complete = false;
|
||||
const incompleteFingerprint =
|
||||
evidenceQualityChanged.storage.content_fingerprints[0];
|
||||
if (incompleteFingerprint === undefined)
|
||||
throw new Error("Expected a content fingerprint");
|
||||
incompleteFingerprint.complete = false;
|
||||
const evidenceOnly = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: evidenceQualityChanged },
|
||||
}),
|
||||
);
|
||||
expect(evidenceOnly.dimensions.storage).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const withoutText = structuredClone(captured.value);
|
||||
withoutText.accessibility.text_capture.status = "not_approved";
|
||||
withoutText.accessibility.text_capture.excluded_fields = 1;
|
||||
for (const node of withoutText.accessibility.nodes) {
|
||||
node.name = null;
|
||||
node.description = null;
|
||||
}
|
||||
const missingText = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: captured.value },
|
||||
after: { inspection: withoutText },
|
||||
}),
|
||||
);
|
||||
expect(missingText.dimensions.accessibility).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
|
||||
const truncated = structuredClone(captured.value);
|
||||
truncated.accessibility.total_nodes += 1;
|
||||
truncated.completeness.truncated_sections.push("accessibility");
|
||||
const incompleteTree = compareWebCaptures(
|
||||
compareWebCapturesInputSchema.parse({
|
||||
before: { inspection: truncated },
|
||||
after: { inspection: structuredClone(truncated) },
|
||||
}),
|
||||
);
|
||||
expect(incompleteTree.dimensions.accessibility).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const markSectionsComplete = (
|
||||
inspection: {
|
||||
completeness: {
|
||||
policy_filtered_sections: string[];
|
||||
attach_limited_sections: string[];
|
||||
truncated_sections: string[];
|
||||
unavailable_sections: string[];
|
||||
};
|
||||
},
|
||||
sections: readonly string[],
|
||||
): void => {
|
||||
const completed = new Set(sections);
|
||||
for (const key of [
|
||||
"policy_filtered_sections",
|
||||
"attach_limited_sections",
|
||||
"truncated_sections",
|
||||
"unavailable_sections",
|
||||
] as const)
|
||||
inspection.completeness[key] = inspection.completeness[key].filter(
|
||||
(section) => !completed.has(section),
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user