feat(application): add isolated JavaScript replay
Expose one plan/execute replay contract through both CLI and MCP with exact source, input, runtime, sandbox, limit, and export commitments. Run selected ESM and extracted CommonJS/Rspack factories in a disposable Linux x64 Bubblewrap namespace with a content-addressed Node ELF closure, architecture-checked seccomp, delegated systemd cgroup limits, bounded protocol capture, cancellation, and observable cleanup. Preserve left and right observations as Evidence, derive differential comparisons without erasing unknowns, add optional separately authorized reproducers, and fail closed on stale plans or unavailable host boundaries. Add source-owned parser, sanitizer, clipboard, denial, timeout, OOM, protocol-forgery, and cancellation coverage; a real Linux verifier and workflow; regenerated catalogs and TypeDoc; and updated the packaged REA analysis skill for the 83-tool inventory.
This commit is contained in:
@@ -56,6 +56,7 @@ export const buildCapabilityInventory = (
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
readonly javascriptReplayEnabled?: boolean;
|
||||
},
|
||||
) => {
|
||||
const status = statusSchema.parse(sessionStatus);
|
||||
@@ -101,6 +102,7 @@ const availabilityFor = (
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
readonly javascriptReplayEnabled?: boolean;
|
||||
},
|
||||
): {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
@@ -112,6 +114,15 @@ const availabilityFor = (
|
||||
remediation:
|
||||
"Enable or grant process_capture within the administrator ceiling.",
|
||||
};
|
||||
if (name === "run_controlled_replay" && !policy.javascriptReplayEnabled)
|
||||
return {
|
||||
reason: "policy_disabled",
|
||||
remediation:
|
||||
"Enable javascript_replay with exact source roots and sandbox executables.",
|
||||
};
|
||||
if (name === "run_controlled_replay")
|
||||
return { reason: "available", remediation: null };
|
||||
if (kind === "application") return { reason: "available", remediation: null };
|
||||
if (name === "import_evidence_bundle" && policy.evidenceFileRoots === 0)
|
||||
return {
|
||||
reason: "policy_disabled",
|
||||
|
||||
@@ -78,6 +78,7 @@ export interface DoctorHost {
|
||||
installationPaths?(): Promise<readonly string[]>;
|
||||
installedSkillVersion?(): Promise<string | undefined>;
|
||||
clientRegistrations?(): Promise<readonly ClientRegistrationStatus[]>;
|
||||
javascriptReplayCheck?(): Promise<DoctorCheck>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -192,6 +193,8 @@ export const runDoctor = async (
|
||||
),
|
||||
);
|
||||
const providerInspections = await inspectDoctorProviders(host, checks);
|
||||
const javascriptReplayCheck = await host.javascriptReplayCheck?.();
|
||||
if (javascriptReplayCheck !== undefined) checks.push(javascriptReplayCheck);
|
||||
if (host.platform === "linux" && hopperPath !== undefined)
|
||||
checks.push(
|
||||
check(
|
||||
@@ -287,6 +290,7 @@ export interface SystemDoctorHostOptions {
|
||||
readonly providerInspections?: () => Promise<
|
||||
readonly DoctorProviderInspection[]
|
||||
>;
|
||||
readonly javascriptReplayCheck?: () => Promise<DoctorCheck>;
|
||||
}
|
||||
|
||||
/** Create diagnostics backed by the current process and host commands. */
|
||||
@@ -375,6 +379,9 @@ export const systemDoctorHost = (
|
||||
...(options.providerInspections === undefined
|
||||
? {}
|
||||
: { providerInspections: options.providerInspections }),
|
||||
...(options.javascriptReplayCheck === undefined
|
||||
? {}
|
||||
: { javascriptReplayCheck: options.javascriptReplayCheck }),
|
||||
async installationPaths() {
|
||||
try {
|
||||
const command = process.platform === "win32" ? "where" : "which";
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
import canonicalize from "canonicalize";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type {
|
||||
ControlledReplayInput,
|
||||
ReplayExecutionResult,
|
||||
ReplayPlan,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
|
||||
const REPLAY_POLICY_VERSION = "linux-bwrap-systemd-v1" as const;
|
||||
const REPLAY_POLICY_DOCUMENT = Object.freeze({
|
||||
version: REPLAY_POLICY_VERSION,
|
||||
namespaces: ["user", "pid", "network", "ipc", "uts", "cgroup"],
|
||||
capabilities: "drop-all",
|
||||
network: "none",
|
||||
filesystem: "minimal-read-only-runtime-plus-private-tmpfs",
|
||||
seccomp: "rea-linux-x86_64-v1",
|
||||
resource_manager: "systemd-user-cgroup-v2",
|
||||
nested_user_namespaces: false,
|
||||
});
|
||||
|
||||
export interface ReplaySourceBytes {
|
||||
readonly canonicalPath: string;
|
||||
readonly bytes: Uint8Array;
|
||||
}
|
||||
|
||||
export interface ReplayExecutableIdentity {
|
||||
readonly path: string;
|
||||
readonly version: string;
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
export interface ReplayRuntimeFileIdentity {
|
||||
readonly sourcePath: string;
|
||||
readonly destinationPath: string;
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
export interface JavaScriptReplayPolicy {
|
||||
readonly enabled: boolean;
|
||||
readonly roots: readonly string[];
|
||||
readonly nodePath: string;
|
||||
readonly bubblewrapPath: string;
|
||||
readonly systemdRunPath: string;
|
||||
readonly systemctlPath: string;
|
||||
readonly shellPath: string;
|
||||
}
|
||||
|
||||
export interface JavaScriptReplayHost {
|
||||
readonly readSource: (
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
) => Promise<ReplaySourceBytes>;
|
||||
readonly identifyExecutable: (
|
||||
path: string,
|
||||
versionArguments: readonly string[],
|
||||
) => Promise<ReplayExecutableIdentity>;
|
||||
readonly identifyWorker: () => Promise<ReplayExecutableIdentity>;
|
||||
readonly identifyRuntimeClosure: (
|
||||
nodePath: string,
|
||||
) => Promise<readonly ReplayRuntimeFileIdentity[]>;
|
||||
readonly seccompDigest: () => string;
|
||||
readonly probe: (policy: JavaScriptReplayPolicy) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface PreparedReplayPlan {
|
||||
readonly publicPlan: ReplayPlan;
|
||||
readonly leftSources: Readonly<Record<string, string>>;
|
||||
readonly rightSources?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface JavaScriptReplayRunner {
|
||||
readonly execute: (
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<ReplayExecutionResult>;
|
||||
}
|
||||
|
||||
/** Read, normalize, and content-address every input to one replay experiment. */
|
||||
export const prepareReplayPlan = async (
|
||||
input: ControlledReplayInput,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
host: JavaScriptReplayHost,
|
||||
): Promise<PreparedReplayPlan> => {
|
||||
const cases = replayCases(input).map((item) => ({
|
||||
...item,
|
||||
sha256: digestJson(item.arguments),
|
||||
}));
|
||||
if (
|
||||
new TextEncoder().encode(
|
||||
JSON.stringify(cases.map(({ arguments: args }) => args)),
|
||||
).byteLength > input.limits.input_bytes
|
||||
)
|
||||
throw new RangeError("Replay case inputs exceed the aggregate byte limit");
|
||||
await host.probe(policy);
|
||||
const [
|
||||
runtime,
|
||||
bubblewrap,
|
||||
systemdRun,
|
||||
systemctl,
|
||||
shell,
|
||||
worker,
|
||||
runtimeFiles,
|
||||
left,
|
||||
right,
|
||||
] = await Promise.all([
|
||||
host.identifyExecutable(policy.nodePath, ["--version"]),
|
||||
host.identifyExecutable(policy.bubblewrapPath, ["--version"]),
|
||||
host.identifyExecutable(policy.systemdRunPath, ["--version"]),
|
||||
host.identifyExecutable(policy.systemctlPath, ["--version"]),
|
||||
host.identifyExecutable(policy.shellPath, ["--version"]),
|
||||
host.identifyWorker(),
|
||||
host.identifyRuntimeClosure(policy.nodePath),
|
||||
prepareSide(input.left, input.limits.module_bytes, host),
|
||||
input.right === undefined
|
||||
? Promise.resolve(undefined)
|
||||
: prepareSide(input.right, input.limits.module_bytes, host),
|
||||
]);
|
||||
const withoutDigest = {
|
||||
schema_version: 1 as const,
|
||||
policy_version: REPLAY_POLICY_VERSION,
|
||||
policy_sha256: digestJson(REPLAY_POLICY_DOCUMENT),
|
||||
network: "none" as const,
|
||||
filesystem: {
|
||||
host_writes: false as const,
|
||||
private_tmpfs_bytes: input.limits.tmpfs_bytes,
|
||||
},
|
||||
runtime: {
|
||||
executable: runtime,
|
||||
worker,
|
||||
read_only_files: runtimeFiles.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
})),
|
||||
},
|
||||
sandbox: {
|
||||
bubblewrap,
|
||||
systemd_run: systemdRun,
|
||||
systemctl,
|
||||
shell,
|
||||
seccomp_sha256: host.seccompDigest(),
|
||||
},
|
||||
left: left.commitment,
|
||||
...(right === undefined ? {} : { right: right.commitment }),
|
||||
cases,
|
||||
determinism: input.determinism,
|
||||
limits: input.limits,
|
||||
effects: [
|
||||
"Execute selected extracted modules in a disposable Linux OS sandbox",
|
||||
"Create and remove one private cgroup and mount namespace",
|
||||
"Retain bounded return, exception, termination, and diagnostic evidence",
|
||||
"Perform no host filesystem writes and expose no host or external network",
|
||||
...(input.reproducer_export === undefined
|
||||
? []
|
||||
: ["Write one separately approved reproducer after sandbox cleanup"]),
|
||||
],
|
||||
reproducer_export:
|
||||
input.reproducer_export === undefined
|
||||
? null
|
||||
: {
|
||||
path: input.reproducer_export.path,
|
||||
include_sources: input.reproducer_export.include_sources,
|
||||
authority: "evidence_write" as const,
|
||||
},
|
||||
};
|
||||
const publicPlan: ReplayPlan = {
|
||||
...withoutDigest,
|
||||
plan_digest: digestJson(withoutDigest),
|
||||
};
|
||||
return {
|
||||
publicPlan,
|
||||
leftSources: left.sources,
|
||||
...(right === undefined ? {} : { rightSources: right.sources }),
|
||||
};
|
||||
};
|
||||
|
||||
const prepareSide = async (
|
||||
side: ControlledReplayInput["left"],
|
||||
maximumBytes: number,
|
||||
host: JavaScriptReplayHost,
|
||||
) => {
|
||||
const aliases = new Set(side.modules.map(({ alias }) => alias));
|
||||
if (aliases.size !== side.modules.length || !aliases.has(side.entry_alias))
|
||||
throw new TypeError("Replay manifest aliases or entry alias are invalid");
|
||||
for (const module of side.modules)
|
||||
for (const dependency of Object.values(module.dependencies))
|
||||
if (!aliases.has(dependency))
|
||||
throw new TypeError(
|
||||
`Undeclared replay dependency alias: ${dependency}`,
|
||||
);
|
||||
const loaded: {
|
||||
readonly module: (typeof side.modules)[number];
|
||||
readonly source: ReplaySourceBytes;
|
||||
}[] = [];
|
||||
let totalBytes = 0;
|
||||
for (const module of side.modules) {
|
||||
const remaining = maximumBytes - totalBytes;
|
||||
if (remaining <= 0)
|
||||
throw new RangeError("Replay module bytes exceed the aggregate limit");
|
||||
const source = await host.readSource(module.path, remaining);
|
||||
totalBytes += source.bytes.byteLength;
|
||||
loaded.push({ module, source });
|
||||
}
|
||||
return {
|
||||
commitment: {
|
||||
modules: loaded.map(({ module, source }) => ({
|
||||
alias: module.alias,
|
||||
canonical_path: source.canonicalPath,
|
||||
format: module.format,
|
||||
role: module.role,
|
||||
byte_count: source.bytes.byteLength,
|
||||
sha256: digestBytes(source.bytes),
|
||||
dependencies: module.dependencies,
|
||||
})),
|
||||
entry_alias: side.entry_alias,
|
||||
entry_export: side.entry_export,
|
||||
},
|
||||
sources: Object.fromEntries(
|
||||
loaded.map(({ module, source }) => [
|
||||
module.alias,
|
||||
new TextDecoder("utf-8", { fatal: true }).decode(source.bytes),
|
||||
]),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const replayCases = (
|
||||
input: ControlledReplayInput,
|
||||
): readonly { readonly case_id: string; readonly arguments: JsonValue[] }[] => {
|
||||
const explicit = input.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
arguments: item.arguments,
|
||||
}));
|
||||
if (input.generator === undefined) return uniqueCases(explicit);
|
||||
let state = input.generator.seed || 0x9e37_79b9;
|
||||
const next = (): number => {
|
||||
state ^= state << 13;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5;
|
||||
return state >>> 0;
|
||||
};
|
||||
const corpus = boundaryCorpus(input.generator.preset);
|
||||
const generated = Array.from(
|
||||
{ length: input.generator.count },
|
||||
(_, index) => ({
|
||||
case_id: `generated-${input.generator?.preset ?? "boundary"}-${String(index)}`,
|
||||
arguments: [corpus[next() % corpus.length] ?? ""] as JsonValue[],
|
||||
}),
|
||||
);
|
||||
return uniqueCases([...explicit, ...generated]);
|
||||
};
|
||||
|
||||
const uniqueCases = <Case extends { readonly case_id: string }>(
|
||||
cases: readonly Case[],
|
||||
): readonly Case[] => {
|
||||
const ids = new Set<string>();
|
||||
for (const item of cases) {
|
||||
if (ids.has(item.case_id))
|
||||
throw new TypeError(`Duplicate replay case ID: ${item.case_id}`);
|
||||
ids.add(item.case_id);
|
||||
}
|
||||
return cases;
|
||||
};
|
||||
|
||||
const boundaryCorpus = (
|
||||
preset: NonNullable<ControlledReplayInput["generator"]>["preset"],
|
||||
): readonly JsonValue[] => {
|
||||
if (preset === "sanitizer-boundaries")
|
||||
return [
|
||||
"",
|
||||
"<script>alert(1)</script>",
|
||||
"<img src=x onerror=alert(1)>",
|
||||
"javascript:alert(1)",
|
||||
"<b>ok</b>",
|
||||
"\u0000",
|
||||
];
|
||||
if (preset === "clipboard-boundaries")
|
||||
return [
|
||||
"",
|
||||
"plain",
|
||||
"a\r\nb",
|
||||
"a\nb",
|
||||
"\t",
|
||||
"😀",
|
||||
"text/html",
|
||||
"text/plain",
|
||||
];
|
||||
return [
|
||||
"",
|
||||
" ",
|
||||
"\n",
|
||||
"# heading",
|
||||
"**bold**",
|
||||
"[x](javascript:y)",
|
||||
"`code`",
|
||||
"😀",
|
||||
"\u0000",
|
||||
"a".repeat(1024),
|
||||
];
|
||||
};
|
||||
|
||||
export const digestBytes = (value: Uint8Array): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
export const digestJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Replay commitment is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,402 @@
|
||||
import { z } from "zod";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import {
|
||||
controlledReplayInputSchema,
|
||||
replayExecutionResultSchema,
|
||||
controlledReplayOutputSchema,
|
||||
replayEvidenceSchema,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
ReplayPlanStaleError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import {
|
||||
digestBytes,
|
||||
prepareReplayPlan,
|
||||
type JavaScriptReplayHost,
|
||||
type JavaScriptReplayPolicy,
|
||||
type JavaScriptReplayRunner,
|
||||
} from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
const OPERATION = "run_controlled_replay" as const;
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
export interface JavaScriptReplayDependencies {
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly host: JavaScriptReplayHost;
|
||||
readonly runner: JavaScriptReplayRunner;
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
}
|
||||
|
||||
/** Plan or execute one content-bound extracted-module replay experiment. */
|
||||
export const runControlledReplay = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = controlledReplayInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
|
||||
if (!dependencies.policy.enabled)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-javascript-replay",
|
||||
OPERATION,
|
||||
"controlled replay is disabled; configure exact roots and executables before enabling it",
|
||||
),
|
||||
);
|
||||
if (dependencies.authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-javascript-replay",
|
||||
OPERATION,
|
||||
"JavaScript replay permission policy is not configured",
|
||||
),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const request = permissionRequest(parsed.data, dependencies.policy);
|
||||
const authorized =
|
||||
parsed.data.mode === "plan"
|
||||
? await dependencies.authority.explain(request, "read")
|
||||
: await dependencies.authority.authorize(request, "read");
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
let prepared;
|
||||
try {
|
||||
prepared = await prepareReplayPlan(
|
||||
parsed.data,
|
||||
dependencies.policy,
|
||||
dependencies.host,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-javascript-replay",
|
||||
OPERATION,
|
||||
cause instanceof Error ? cause.message : "replay planning failed",
|
||||
),
|
||||
);
|
||||
}
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
if (parsed.data.mode === "plan")
|
||||
return ok(
|
||||
asJson({
|
||||
phase: "plan",
|
||||
plan: prepared.publicPlan,
|
||||
source_evidence: [],
|
||||
evidence: null,
|
||||
}),
|
||||
);
|
||||
if (parsed.data.plan_digest !== prepared.publicPlan.plan_digest)
|
||||
return err(
|
||||
new ReplayPlanStaleError(
|
||||
parsed.data.plan_digest ?? "",
|
||||
prepared.publicPlan.plan_digest,
|
||||
),
|
||||
);
|
||||
let canonicalExportPath: string | undefined;
|
||||
if (parsed.data.reproducer_export !== undefined) {
|
||||
if (parsed.data.reproducer_export.approved !== true)
|
||||
return err(new AnalysisInputError(`${OPERATION}:reproducer_export`));
|
||||
const exportAuthorized = await dependencies.authority.authorize(
|
||||
{
|
||||
capability: "evidence_write",
|
||||
roots: [parsed.data.reproducer_export.path],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `${OPERATION}:reproducer:${prepared.publicPlan.plan_digest}`,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!exportAuthorized.ok)
|
||||
return err(
|
||||
exportAuthorized.error instanceof PermissionRequiredError
|
||||
? exportAuthorized.error
|
||||
: new AnalysisProtocolError(exportAuthorized.error.message, {
|
||||
cause: exportAuthorized.error,
|
||||
}),
|
||||
);
|
||||
canonicalExportPath = exportAuthorized.value.request.roots[0];
|
||||
if (canonicalExportPath !== parsed.data.reproducer_export.path)
|
||||
return err(
|
||||
new AnalysisInputError(`${OPERATION}:reproducer_export:path`, {
|
||||
cause: new TypeError(
|
||||
`Use the canonical reproducer path: ${canonicalExportPath ?? "unavailable"}`,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
await options.progress?.report({
|
||||
phase: OPERATION,
|
||||
completed: 0,
|
||||
total: 1,
|
||||
message: "Admitting approved modules into the isolated replay worker",
|
||||
});
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
try {
|
||||
let executed = replayExecutionResultSchema.parse(
|
||||
await dependencies.runner.execute(
|
||||
prepared,
|
||||
dependencies.policy,
|
||||
options.signal,
|
||||
),
|
||||
);
|
||||
await options.progress?.report({
|
||||
phase: OPERATION,
|
||||
completed: 1,
|
||||
total: 1,
|
||||
message: "Controlled replay stopped and sandbox cleanup was observed",
|
||||
terminal: true,
|
||||
});
|
||||
if (executed.termination === "cancelled")
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
if (
|
||||
parsed.data.reproducer_export !== undefined &&
|
||||
canonicalExportPath !== undefined &&
|
||||
executed.cleanup.state === "complete"
|
||||
) {
|
||||
const manifest = {
|
||||
schema_version: 1,
|
||||
plan: prepared.publicPlan,
|
||||
result: executed,
|
||||
sources: parsed.data.reproducer_export.include_sources
|
||||
? {
|
||||
left: prepared.leftSources,
|
||||
...(prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: prepared.rightSources }),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
const encoded = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
|
||||
try {
|
||||
await writeFileAtomic(canonicalExportPath, encoded, {
|
||||
mode: 0o600,
|
||||
});
|
||||
executed = replayExecutionResultSchema.parse({
|
||||
...executed,
|
||||
reproducer: {
|
||||
state: "written",
|
||||
path: canonicalExportPath,
|
||||
sha256: digestBytes(encoded),
|
||||
},
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
executed = replayExecutionResultSchema.parse({
|
||||
...executed,
|
||||
limitations: [
|
||||
...executed.limitations,
|
||||
"Replay completed, but the separately approved reproducer export failed.",
|
||||
],
|
||||
reproducer: {
|
||||
state: "failed",
|
||||
path: canonicalExportPath,
|
||||
error:
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "unknown reproducer export failure",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
const leftCount = prepared.publicPlan.cases.length;
|
||||
const sourceEvidence = [
|
||||
createReplayEvidence(
|
||||
prepared,
|
||||
executed,
|
||||
"left",
|
||||
executed.outcomes.slice(0, leftCount),
|
||||
),
|
||||
...(prepared.publicPlan.right === undefined
|
||||
? []
|
||||
: [
|
||||
createReplayEvidence(
|
||||
prepared,
|
||||
executed,
|
||||
"right",
|
||||
executed.outcomes.slice(leftCount),
|
||||
),
|
||||
]),
|
||||
];
|
||||
const subject = prepared.publicPlan.left.modules[0];
|
||||
const evidence = createEvidence(
|
||||
subject === undefined
|
||||
? undefined
|
||||
: {
|
||||
path: subject.canonical_path,
|
||||
sha256: subject.sha256,
|
||||
format: "javascript",
|
||||
},
|
||||
{
|
||||
id: "rea-javascript-replay",
|
||||
name: "REA isolated JavaScript replay",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
predicateType: "javascript-controlled-replay",
|
||||
operation: OPERATION,
|
||||
parameters: {
|
||||
replay_plan: jsonValueSchema.parse(
|
||||
JSON.parse(JSON.stringify(prepared.publicPlan)),
|
||||
),
|
||||
},
|
||||
result: jsonValueSchema.parse(JSON.parse(JSON.stringify(executed))),
|
||||
rawResult: jsonValueSchema.parse(
|
||||
JSON.parse(
|
||||
JSON.stringify({
|
||||
cases: prepared.publicPlan.cases,
|
||||
outcomes: executed.outcomes,
|
||||
stderr: executed.stderr,
|
||||
}),
|
||||
),
|
||||
),
|
||||
confidence: executed.comparison === undefined ? "observed" : "derived",
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: prepared.publicPlan.plan_digest,
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
isolation: "container",
|
||||
},
|
||||
limitations: executed.limitations,
|
||||
locations: prepared.publicPlan.left.modules.map((module) => ({
|
||||
kind: "artifact-path" as const,
|
||||
path: module.canonical_path,
|
||||
})),
|
||||
evidenceLinks: sourceEvidence.map(({ evidence_id: id }) => id),
|
||||
},
|
||||
);
|
||||
return ok(
|
||||
asJson({
|
||||
phase: "execute",
|
||||
plan: null,
|
||||
source_evidence: sourceEvidence.map((item) =>
|
||||
replayEvidenceSchema.parse(item),
|
||||
),
|
||||
evidence: replayEvidenceSchema.parse(evidence),
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
cause instanceof z.ZodError
|
||||
? "Controlled replay produced an invalid bounded result"
|
||||
: "Controlled replay could not establish or clean up its sandbox",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const createReplayEvidence = (
|
||||
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
|
||||
executed: z.infer<typeof replayExecutionResultSchema>,
|
||||
side: "left" | "right",
|
||||
outcomes: z.infer<typeof replayExecutionResultSchema>["outcomes"],
|
||||
) => {
|
||||
const manifest =
|
||||
side === "left" ? prepared.publicPlan.left : prepared.publicPlan.right;
|
||||
const subject = manifest?.modules[0];
|
||||
const result = replayExecutionResultSchema.parse({
|
||||
...executed,
|
||||
outcomes,
|
||||
comparison: undefined,
|
||||
reproducer: null,
|
||||
});
|
||||
return createEvidence(
|
||||
subject === undefined
|
||||
? undefined
|
||||
: {
|
||||
path: subject.canonical_path,
|
||||
sha256: subject.sha256,
|
||||
format: "javascript",
|
||||
},
|
||||
{
|
||||
id: "rea-javascript-replay",
|
||||
name: "REA isolated JavaScript replay",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
predicateType: "javascript-controlled-replay-observation",
|
||||
operation: OPERATION,
|
||||
parameters: {
|
||||
replay_plan: jsonValueSchema.parse(
|
||||
JSON.parse(JSON.stringify(prepared.publicPlan)),
|
||||
),
|
||||
side,
|
||||
},
|
||||
result: jsonValueSchema.parse(JSON.parse(JSON.stringify(result))),
|
||||
rawResult: jsonValueSchema.parse(
|
||||
JSON.parse(
|
||||
JSON.stringify({ cases: prepared.publicPlan.cases, outcomes }),
|
||||
),
|
||||
),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: prepared.publicPlan.plan_digest,
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
isolation: "container",
|
||||
},
|
||||
limitations: executed.limitations,
|
||||
locations: (manifest?.modules ?? []).map((module) => ({
|
||||
kind: "artifact-path" as const,
|
||||
path: module.canonical_path,
|
||||
})),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const asJson = (value: unknown): JsonValue =>
|
||||
jsonValueSchema.parse(
|
||||
JSON.parse(
|
||||
JSON.stringify(controlledReplayOutputSchema.parse(value)),
|
||||
) as unknown,
|
||||
);
|
||||
|
||||
const permissionRequest = (
|
||||
input: z.infer<typeof controlledReplayInputSchema>,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
) => ({
|
||||
capability: "javascript_replay" as const,
|
||||
roots: [...input.left.modules, ...(input.right?.modules ?? [])].map(
|
||||
({ path }) => path,
|
||||
),
|
||||
executables: [
|
||||
policy.nodePath,
|
||||
policy.bubblewrapPath,
|
||||
policy.systemdRunPath,
|
||||
policy.systemctlPath,
|
||||
policy.shellPath,
|
||||
],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
operation_identity: `${OPERATION}:${input.plan_digest ?? "plan"}`,
|
||||
});
|
||||
@@ -124,7 +124,13 @@ export class PermissionAuthority {
|
||||
readonly restartRequired?: boolean;
|
||||
} = {},
|
||||
): Promise<
|
||||
Result<PermissionDecision, PermissionPathError | PermissionRequiredError>
|
||||
Result<
|
||||
PermissionDecision & {
|
||||
readonly allowed: true;
|
||||
readonly request: PermissionRequest;
|
||||
},
|
||||
PermissionPathError | PermissionRequiredError
|
||||
>
|
||||
> {
|
||||
const evaluated = await this.explain(request, access, options);
|
||||
if (!evaluated.ok) return evaluated;
|
||||
@@ -143,7 +149,10 @@ export class PermissionAuthority {
|
||||
} = {},
|
||||
): Promise<
|
||||
Result<
|
||||
PermissionDecision & { readonly allowed: true },
|
||||
PermissionDecision & {
|
||||
readonly allowed: true;
|
||||
readonly request: PermissionRequest;
|
||||
},
|
||||
PermissionPathError | PermissionRequiredError
|
||||
>
|
||||
> {
|
||||
@@ -160,7 +169,7 @@ export class PermissionAuthority {
|
||||
options.restartRequired ?? false,
|
||||
),
|
||||
);
|
||||
return ok(decision);
|
||||
return ok({ ...decision, request: canonical.value });
|
||||
}
|
||||
|
||||
/** Add authority beneath the administrator ceiling. */
|
||||
|
||||
@@ -34,6 +34,7 @@ const grantSchema = z.object({
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
"javascript_replay",
|
||||
]),
|
||||
roots: z.array(z.string()),
|
||||
executables: z.array(z.string()),
|
||||
|
||||
@@ -4,12 +4,17 @@ import {
|
||||
compareApplicationVersionsEvidence,
|
||||
traceApplicationFeatureEvidence,
|
||||
} from "./application/JavaScriptApplicationWorkflowService.js";
|
||||
import { runControlledReplay } from "./application/JavaScriptReplayService.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "./cliJsonInput.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import { LinuxJavaScriptReplayRunner } from "./replay/LinuxJavaScriptReplayRunner.js";
|
||||
import { SystemJavaScriptReplayHost } from "./replay/SystemJavaScriptReplayHost.js";
|
||||
|
||||
/** Register CLI equivalents of provider-neutral application graph workflows. */
|
||||
export const registerApplicationCommands = (
|
||||
@@ -30,6 +35,35 @@ export const registerApplicationCommands = (
|
||||
"Compare two authenticated JavaScript Application Graph versions",
|
||||
compareApplicationVersionsEvidence,
|
||||
);
|
||||
cli.command(CLI_COMMANDS.runControlledReplay, {
|
||||
description:
|
||||
"Plan or execute an approved extracted-module replay in the Linux sandbox",
|
||||
args: z.object({
|
||||
inputJson: z.string().describe("Inline replay JSON or JSON file path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.runControlledReplay, async () => {
|
||||
const input = await parseCliJsonInput(
|
||||
args.inputJson,
|
||||
CLI_COMMANDS.runControlledReplay,
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return projectAnalysisError(config.error);
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) return projectAnalysisError(authority.error);
|
||||
const result = await runControlledReplay(
|
||||
{
|
||||
policy: config.value.javascriptReplayPolicy,
|
||||
host: new SystemJavaScriptReplayHost(),
|
||||
runner: new LinuxJavaScriptReplayRunner(),
|
||||
authority: authority.value,
|
||||
},
|
||||
input.value,
|
||||
);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const registerJsonCommand = (
|
||||
|
||||
@@ -42,6 +42,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
reconcileJavaScriptRuntime: "reconcile-javascript-runtime",
|
||||
traceApplicationFeature: "trace-application-feature",
|
||||
compareApplicationVersions: "compare-application-versions",
|
||||
runControlledReplay: "run-controlled-replay",
|
||||
});
|
||||
|
||||
/** Ordered primary CLI inventory; aliases are intentionally excluded. */
|
||||
|
||||
@@ -51,6 +51,15 @@ export interface AppConfig {
|
||||
readonly electronObservationEnabled: boolean;
|
||||
readonly electronCdpEndpoints: readonly string[];
|
||||
readonly electronFileRoots: readonly string[];
|
||||
readonly javascriptReplayPolicy: {
|
||||
readonly enabled: boolean;
|
||||
readonly roots: readonly string[];
|
||||
readonly nodePath: string;
|
||||
readonly bubblewrapPath: string;
|
||||
readonly systemdRunPath: string;
|
||||
readonly systemctlPath: string;
|
||||
readonly shellPath: string;
|
||||
};
|
||||
readonly permissionCeilings: readonly PermissionCeiling[];
|
||||
readonly administratorPermissionGrants: readonly PermissionGrant[];
|
||||
readonly permissionProjectRoot: string | undefined;
|
||||
@@ -103,6 +112,39 @@ const environmentSchema = z
|
||||
REA_ELECTRON_OBSERVE_ENABLED: z.enum(["true", "false"]).default("false"),
|
||||
REA_ELECTRON_CDP_ENDPOINTS_JSON: z.string().default("[]"),
|
||||
REA_ELECTRON_FILE_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_JAVASCRIPT_REPLAY_ENABLED: z.enum(["true", "false"]).default("false"),
|
||||
REA_JAVASCRIPT_REPLAY_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_JAVASCRIPT_REPLAY_NODE_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_JAVASCRIPT_REPLAY_NODE_PATH must be absolute")
|
||||
.default(process.execPath),
|
||||
REA_JAVASCRIPT_REPLAY_BWRAP_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_JAVASCRIPT_REPLAY_BWRAP_PATH must be absolute")
|
||||
.default("/usr/bin/bwrap"),
|
||||
REA_JAVASCRIPT_REPLAY_SYSTEMD_RUN_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
isAbsolute,
|
||||
"REA_JAVASCRIPT_REPLAY_SYSTEMD_RUN_PATH must be absolute",
|
||||
)
|
||||
.default("/usr/bin/systemd-run"),
|
||||
REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
isAbsolute,
|
||||
"REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH must be absolute",
|
||||
)
|
||||
.default("/usr/bin/systemctl"),
|
||||
REA_JAVASCRIPT_REPLAY_SHELL_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_JAVASCRIPT_REPLAY_SHELL_PATH must be absolute")
|
||||
.default("/usr/bin/bash"),
|
||||
REA_PERMISSION_PROJECT_ROOT: z.string().min(1).optional(),
|
||||
REA_PERMISSION_PROJECT_STORE: z.string().min(1).optional(),
|
||||
})
|
||||
@@ -332,6 +374,17 @@ export const parseConfig = (
|
||||
parsedEnvironment.data.REA_ELECTRON_FILE_ROOTS_JSON,
|
||||
);
|
||||
if (!electronFileRoots.ok) return electronFileRoots;
|
||||
const javascriptReplayRoots = parseStringArray(
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_ROOTS_JSON,
|
||||
"REA_JAVASCRIPT_REPLAY_ROOTS_JSON",
|
||||
);
|
||||
if (!javascriptReplayRoots.ok) return javascriptReplayRoots;
|
||||
if (javascriptReplayRoots.value.some((root) => !isAbsolute(root)))
|
||||
return err(
|
||||
new ConfigurationError(
|
||||
"REA_JAVASCRIPT_REPLAY_ROOTS_JSON must encode absolute roots",
|
||||
),
|
||||
);
|
||||
const permissionCeilings = [
|
||||
...(parsedEnvironment.data.REA_PROCESS_CAPTURE_ENABLED === "true"
|
||||
? [
|
||||
@@ -374,6 +427,21 @@ export const parseConfig = (
|
||||
...(parsedEnvironment.data.REA_ARTIFACT_NATIVE_MOUNT_ENABLED === "true"
|
||||
? [permissionScope("native_mount", [], { mount: true })]
|
||||
: []),
|
||||
...(parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_ENABLED === "true"
|
||||
? [
|
||||
permissionScope("javascript_replay", javascriptReplayRoots.value, {
|
||||
executables: [
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_NODE_PATH,
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_BWRAP_PATH,
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_SYSTEMD_RUN_PATH,
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH,
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_SHELL_PATH,
|
||||
],
|
||||
network: "none",
|
||||
mount: true,
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
] satisfies readonly PermissionCeiling[];
|
||||
return ok({
|
||||
analysisProvider: parsedEnvironment.data.REA_ANALYSIS_PROVIDER,
|
||||
@@ -417,6 +485,17 @@ export const parseConfig = (
|
||||
parsedEnvironment.data.REA_ELECTRON_OBSERVE_ENABLED === "true",
|
||||
electronCdpEndpoints: electronEndpoints.value,
|
||||
electronFileRoots: electronFileRoots.value,
|
||||
javascriptReplayPolicy: {
|
||||
enabled: parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_ENABLED === "true",
|
||||
roots: javascriptReplayRoots.value,
|
||||
nodePath: parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_NODE_PATH,
|
||||
bubblewrapPath: parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_BWRAP_PATH,
|
||||
systemdRunPath:
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_SYSTEMD_RUN_PATH,
|
||||
systemctlPath:
|
||||
parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH,
|
||||
shellPath: parsedEnvironment.data.REA_JAVASCRIPT_REPLAY_SHELL_PATH,
|
||||
},
|
||||
permissionCeilings,
|
||||
administratorPermissionGrants: administratorGrants(permissionCeilings),
|
||||
permissionProjectRoot: parsedEnvironment.data.REA_PERMISSION_PROJECT_ROOT,
|
||||
|
||||
@@ -7,6 +7,10 @@ import {
|
||||
traceApplicationFeatureInputSchema,
|
||||
} from "../domain/javascriptFeatureTraceSchemas.js";
|
||||
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
controlledReplayInputSchema,
|
||||
controlledReplayOutputSchema,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import {
|
||||
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
@@ -62,4 +66,62 @@ export const APPLICATION_TOOL_CONTRACTS = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "run_controlled_replay",
|
||||
description:
|
||||
"Plan or execute a content-bound extracted-module JavaScript replay inside the Linux Bubblewrap, seccomp, and cgroup boundary. Execution requires approved: true and the exact plan digest. Supports deterministic boundary cases and optional left/right differential comparison; observations have controlled-replay authority and do not claim real application runtime behavior.",
|
||||
kind: "application",
|
||||
inputSchema: controlledReplayInputSchema,
|
||||
outputSchema: controlledReplayOutputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
examples: [
|
||||
{
|
||||
title: "Plan one extracted ESM parser replay",
|
||||
input: {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "parser",
|
||||
path: "/approved/parser.mjs",
|
||||
format: "esm",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "parser",
|
||||
entry_export: "default",
|
||||
},
|
||||
cases: [{ case_id: "empty", arguments: [""] }],
|
||||
determinism: {
|
||||
clock_iso: "2000-01-01T00:00:00.000Z",
|
||||
random_seed: 0,
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
platform: "linux",
|
||||
},
|
||||
limits: {
|
||||
wall_time_ms: 3000,
|
||||
memory_bytes: 134217728,
|
||||
tasks: 8,
|
||||
cpu_quota_percent: 50,
|
||||
tmpfs_bytes: 16777216,
|
||||
module_bytes: 4194304,
|
||||
input_bytes: 262144,
|
||||
protocol_bytes: 16777216,
|
||||
output_bytes: 524288,
|
||||
stderr_bytes: 32768,
|
||||
result_depth: 16,
|
||||
result_nodes: 10000,
|
||||
},
|
||||
approved: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
@@ -99,6 +99,7 @@ export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [
|
||||
generic("configuration_invalid"),
|
||||
generic("target_unavailable"),
|
||||
generic("execution_failure"),
|
||||
generic("plan_stale"),
|
||||
]);
|
||||
|
||||
/** JSON Schema document used by generated API documentation and clients. */
|
||||
|
||||
+51
-1
@@ -1,8 +1,58 @@
|
||||
import { systemDoctorHost, type DoctorHost } from "./application/Doctor.js";
|
||||
import {
|
||||
systemDoctorHost,
|
||||
type DoctorCheck,
|
||||
type DoctorHost,
|
||||
} from "./application/Doctor.js";
|
||||
import { inspectSystemGhidraProvider } from "./ghidra/GhidraDoctor.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import { SystemJavaScriptReplayHost } from "./replay/SystemJavaScriptReplayHost.js";
|
||||
|
||||
/** Compose provider diagnostics at the outer CLI adapter boundary. */
|
||||
export const createSystemDoctorHost = (): DoctorHost =>
|
||||
systemDoctorHost({
|
||||
providerInspections: async () => [await inspectSystemGhidraProvider()],
|
||||
javascriptReplayCheck: inspectJavaScriptReplay,
|
||||
});
|
||||
|
||||
const inspectJavaScriptReplay = async (): Promise<DoctorCheck> => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return {
|
||||
name: "javascript-replay",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: config.error.message,
|
||||
remediation: "Fix the reported REA_JAVASCRIPT_REPLAY_* configuration.",
|
||||
};
|
||||
if (!config.value.javascriptReplayPolicy.enabled)
|
||||
return {
|
||||
name: "javascript-replay",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
detail:
|
||||
"disabled by default; no extracted-module execution path is admitted",
|
||||
};
|
||||
try {
|
||||
await new SystemJavaScriptReplayHost().probe(
|
||||
config.value.javascriptReplayPolicy,
|
||||
);
|
||||
return {
|
||||
name: "javascript-replay",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
detail: "Linux namespace, seccomp, and delegated cgroup probes passed",
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
name: "javascript-replay",
|
||||
ok: false,
|
||||
classification:
|
||||
process.platform === "linux"
|
||||
? "missing_dependency"
|
||||
: "unsupported_host",
|
||||
detail: cause instanceof Error ? cause.message : "sandbox probe failed",
|
||||
remediation:
|
||||
"Install and configure compatible Bubblewrap and systemd user cgroup delegation, or disable controlled replay.",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
+30
-1
@@ -38,6 +38,7 @@ const ANALYSIS_ERROR_TAGS = [
|
||||
"NoBinaryOpenError",
|
||||
"BinaryTargetError",
|
||||
"PermissionRequiredError",
|
||||
"ReplayPlanStaleError",
|
||||
] as const;
|
||||
|
||||
/** Stable tag for an expected analysis failure. */
|
||||
@@ -491,7 +492,8 @@ export interface AnalysisErrorProjection
|
||||
| "outside_approved_root"
|
||||
| "configuration_invalid"
|
||||
| "target_unavailable"
|
||||
| "execution_failure";
|
||||
| "execution_failure"
|
||||
| "plan_stale";
|
||||
readonly category:
|
||||
| "invalid_input"
|
||||
| "permission_required"
|
||||
@@ -527,6 +529,18 @@ export class PermissionRequiredError extends AnalysisError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Approved replay commitment no longer matches the immediately rebuilt plan. */
|
||||
export class ReplayPlanStaleError extends AnalysisError {
|
||||
readonly _tag = "ReplayPlanStaleError" as const;
|
||||
|
||||
constructor(
|
||||
readonly approvedDigest: string,
|
||||
readonly actualDigest: string,
|
||||
) {
|
||||
super("Controlled replay plan changed before execution");
|
||||
}
|
||||
}
|
||||
|
||||
/** Project expected failures into exhaustive, secret-safe caller fields. */
|
||||
export const projectAnalysisError = (
|
||||
error: AnalysisError,
|
||||
@@ -552,6 +566,7 @@ export const projectAnalysisError = (
|
||||
};
|
||||
|
||||
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
if (error instanceof ReplayPlanStaleError) return "plan_stale";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (
|
||||
error instanceof ProviderSelectionError &&
|
||||
@@ -658,12 +673,20 @@ const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
case "UnknownRegistryError":
|
||||
case "PermissionRequiredError":
|
||||
throw new TypeError("Unhandled specialized analysis error");
|
||||
case "ReplayPlanStaleError":
|
||||
throw new TypeError("Unhandled specialized replay error");
|
||||
}
|
||||
};
|
||||
|
||||
const errorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return {
|
||||
approved_plan_digest: error.approvedDigest,
|
||||
actual_plan_digest: error.actualDigest,
|
||||
application_code_admitted: false,
|
||||
};
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return {
|
||||
capability: error.requested.capability,
|
||||
@@ -777,6 +800,8 @@ const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
|
||||
]);
|
||||
|
||||
const remediationAction = (error: AnalysisError): string => {
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "Review the rebuilt replay plan and explicitly approve its new digest.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return error.elicitationSupported
|
||||
? "Approve the exact missing scope, then retry the operation."
|
||||
@@ -787,6 +812,7 @@ const remediationAction = (error: AnalysisError): string => {
|
||||
const errorCategory = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (error instanceof ReplayPlanStaleError) return "integrity_mismatch";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (
|
||||
error instanceof ProviderSelectionError &&
|
||||
@@ -862,6 +888,8 @@ const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
};
|
||||
|
||||
const userMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "The controlled replay plan changed before execution. Refresh the current state and try again.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return "This operation needs additional local permission. Review the requested scope and remediation.";
|
||||
if (error instanceof AnalysisInputError)
|
||||
@@ -1007,6 +1035,7 @@ const KNOWN_ERROR_TAGS = {
|
||||
NoBinaryOpenError: true,
|
||||
BinaryTargetError: true,
|
||||
PermissionRequiredError: true,
|
||||
ReplayPlanStaleError: true,
|
||||
} as const satisfies Readonly<Record<AnalysisErrorTag, true>>;
|
||||
|
||||
const assertKnownTag = (tag: AnalysisErrorTag): void => {
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceEnvelopeSchema } from "./evidence.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const absolutePathSchema = z.string().startsWith("/").max(4096);
|
||||
const aliasSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.regex(/^[A-Za-z0-9_./:@-]+$/u);
|
||||
|
||||
const replayModuleSchema = z
|
||||
.object({
|
||||
alias: aliasSchema,
|
||||
path: absolutePathSchema,
|
||||
format: z.enum(["esm", "commonjs-factory"]),
|
||||
role: z.enum(["module", "stub"]).default("module"),
|
||||
dependencies: z
|
||||
.record(z.string().min(1).max(256), aliasSchema)
|
||||
.refine((value) => Object.keys(value).length <= 128, {
|
||||
message: "Replay modules may declare at most 128 dependencies",
|
||||
})
|
||||
.default({}),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const replaySideSchema = z
|
||||
.object({
|
||||
modules: z.array(replayModuleSchema).min(1).max(128),
|
||||
entry_alias: aliasSchema,
|
||||
entry_export: z.string().min(1).max(256).default("default"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const explicitCaseSchema = z
|
||||
.object({
|
||||
case_id: z.string().min(1).max(128),
|
||||
arguments: z.array(z.json()).max(16),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const generatorSchema = z
|
||||
.object({
|
||||
preset: z.enum([
|
||||
"parser-boundaries",
|
||||
"sanitizer-boundaries",
|
||||
"clipboard-boundaries",
|
||||
]),
|
||||
seed: z.number().int().min(0).max(0xffff_ffff),
|
||||
count: z.number().int().min(1).max(64),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const replayLimitsSchema = z
|
||||
.object({
|
||||
wall_time_ms: z.number().int().min(100).max(10_000).default(3_000),
|
||||
memory_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(16 * 1024 * 1024)
|
||||
.max(512 * 1024 * 1024)
|
||||
.default(128 * 1024 * 1024),
|
||||
tasks: z.number().int().min(1).max(32).default(8),
|
||||
cpu_quota_percent: z.number().int().min(1).max(100).default(50),
|
||||
tmpfs_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1024 * 1024)
|
||||
.max(64 * 1024 * 1024)
|
||||
.default(16 * 1024 * 1024),
|
||||
module_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(16 * 1024 * 1024)
|
||||
.default(4 * 1024 * 1024),
|
||||
input_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1024 * 1024)
|
||||
.default(256 * 1024),
|
||||
protocol_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1024 * 1024)
|
||||
.max(64 * 1024 * 1024)
|
||||
.default(16 * 1024 * 1024),
|
||||
output_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(4 * 1024 * 1024)
|
||||
.default(512 * 1024),
|
||||
stderr_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(256 * 1024)
|
||||
.default(32 * 1024),
|
||||
result_depth: z.number().int().min(1).max(64).default(16),
|
||||
result_nodes: z.number().int().min(1).max(100_000).default(10_000),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const determinismSchema = z
|
||||
.object({
|
||||
clock_iso: z.iso.datetime().default("2000-01-01T00:00:00.000Z"),
|
||||
random_seed: z.number().int().min(0).max(0xffff_ffff).default(0),
|
||||
locale: z.literal("en-US").default("en-US"),
|
||||
timezone: z.literal("UTC").default("UTC"),
|
||||
platform: z.literal("linux").default("linux"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const controlledReplayInputSchema = z
|
||||
.object({
|
||||
mode: z.enum(["plan", "execute"]),
|
||||
left: replaySideSchema,
|
||||
right: replaySideSchema.optional(),
|
||||
cases: z.array(explicitCaseSchema).max(128).default([]),
|
||||
generator: generatorSchema.optional(),
|
||||
determinism: determinismSchema.default({
|
||||
clock_iso: "2000-01-01T00:00:00.000Z",
|
||||
random_seed: 0,
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
platform: "linux",
|
||||
}),
|
||||
limits: replayLimitsSchema.default({
|
||||
wall_time_ms: 3_000,
|
||||
memory_bytes: 128 * 1024 * 1024,
|
||||
tasks: 8,
|
||||
cpu_quota_percent: 50,
|
||||
tmpfs_bytes: 16 * 1024 * 1024,
|
||||
module_bytes: 4 * 1024 * 1024,
|
||||
input_bytes: 256 * 1024,
|
||||
protocol_bytes: 16 * 1024 * 1024,
|
||||
output_bytes: 512 * 1024,
|
||||
stderr_bytes: 32 * 1024,
|
||||
result_depth: 16,
|
||||
result_nodes: 10_000,
|
||||
}),
|
||||
approved: z.boolean().default(false),
|
||||
plan_digest: digestSchema.optional(),
|
||||
reproducer_export: z
|
||||
.object({
|
||||
path: absolutePathSchema,
|
||||
approved: z.boolean(),
|
||||
include_sources: z.boolean().default(false),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (value.cases.length === 0 && value.generator === undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["cases"],
|
||||
message: "At least one explicit or generated case is required",
|
||||
});
|
||||
if (value.cases.length + (value.generator?.count ?? 0) > 128)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["generator", "count"],
|
||||
message: "Explicit and generated replay cases must total at most 128",
|
||||
});
|
||||
if (
|
||||
value.mode === "execute" &&
|
||||
(value.approved !== true || value.plan_digest === undefined)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["approved"],
|
||||
message: "Execution requires literal approval and a plan digest",
|
||||
});
|
||||
});
|
||||
|
||||
const moduleCommitmentSchema = z
|
||||
.object({
|
||||
alias: aliasSchema,
|
||||
canonical_path: z.string().min(1),
|
||||
format: z.enum(["esm", "commonjs-factory"]),
|
||||
role: z.enum(["module", "stub"]),
|
||||
byte_count: z.number().int().min(0),
|
||||
sha256: digestSchema,
|
||||
dependencies: z.record(z.string(), aliasSchema),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const runtimeIdentitySchema = z
|
||||
.object({
|
||||
path: z.string().min(1),
|
||||
version: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
const runtimeFileIdentitySchema = z
|
||||
.object({
|
||||
source_path: z.string().min(1),
|
||||
destination_path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
const replayPlanSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
plan_digest: digestSchema,
|
||||
policy_version: z.literal("linux-bwrap-systemd-v1"),
|
||||
policy_sha256: digestSchema,
|
||||
network: z.literal("none"),
|
||||
filesystem: z
|
||||
.object({
|
||||
host_writes: z.literal(false),
|
||||
private_tmpfs_bytes: z.number().int(),
|
||||
})
|
||||
.strict(),
|
||||
runtime: z
|
||||
.object({
|
||||
executable: runtimeIdentitySchema,
|
||||
worker: runtimeIdentitySchema,
|
||||
read_only_files: z.array(runtimeFileIdentitySchema).min(1),
|
||||
})
|
||||
.strict(),
|
||||
sandbox: z
|
||||
.object({
|
||||
bubblewrap: runtimeIdentitySchema,
|
||||
systemd_run: runtimeIdentitySchema,
|
||||
systemctl: runtimeIdentitySchema,
|
||||
shell: runtimeIdentitySchema,
|
||||
seccomp_sha256: digestSchema,
|
||||
})
|
||||
.strict(),
|
||||
left: z
|
||||
.object({
|
||||
modules: z.array(moduleCommitmentSchema),
|
||||
entry_alias: aliasSchema,
|
||||
entry_export: z.string(),
|
||||
})
|
||||
.strict(),
|
||||
right: z
|
||||
.object({
|
||||
modules: z.array(moduleCommitmentSchema),
|
||||
entry_alias: aliasSchema,
|
||||
entry_export: z.string(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
cases: z.array(
|
||||
z
|
||||
.object({
|
||||
case_id: z.string(),
|
||||
arguments: z.array(z.json()),
|
||||
sha256: digestSchema,
|
||||
})
|
||||
.strict(),
|
||||
),
|
||||
determinism: determinismSchema,
|
||||
limits: replayLimitsSchema,
|
||||
effects: z.array(z.string()),
|
||||
reproducer_export: z
|
||||
.object({
|
||||
path: z.string().min(1),
|
||||
include_sources: z.boolean(),
|
||||
authority: z.literal("evidence_write"),
|
||||
})
|
||||
.strict()
|
||||
.nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const replayOutcomeSchema = z
|
||||
.object({
|
||||
case_id: z.string(),
|
||||
outcome: z.enum([
|
||||
"return",
|
||||
"exception",
|
||||
"serialization_error",
|
||||
"denied",
|
||||
"timeout",
|
||||
"oom",
|
||||
"crash",
|
||||
"cancelled",
|
||||
"protocol_error",
|
||||
]),
|
||||
value: z.json().optional(),
|
||||
exception: z
|
||||
.object({
|
||||
name: z.string(),
|
||||
message: z.string(),
|
||||
stack: z.string().nullable(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
input_sha256: digestSchema,
|
||||
output_sha256: digestSchema.nullable(),
|
||||
truncated: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const replayExecutionResultSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
plan_digest: digestSchema,
|
||||
outcomes: z.array(replayOutcomeSchema),
|
||||
comparison: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
case_id: z.string(),
|
||||
status: z.enum(["equal", "changed", "unknown"]),
|
||||
left_index: z.number().int(),
|
||||
right_index: z.number().int(),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
.optional(),
|
||||
stderr: z.string(),
|
||||
termination: z.enum([
|
||||
"completed",
|
||||
"timeout",
|
||||
"oom",
|
||||
"crash",
|
||||
"cancelled",
|
||||
"protocol_error",
|
||||
]),
|
||||
cleanup: z
|
||||
.object({
|
||||
state: z.enum(["complete", "incomplete"]),
|
||||
residual_resources: z.array(z.string()),
|
||||
})
|
||||
.strict(),
|
||||
limitations: z.array(z.string()),
|
||||
reproducer: z
|
||||
.discriminatedUnion("state", [
|
||||
z
|
||||
.object({
|
||||
state: z.literal("written"),
|
||||
path: z.string(),
|
||||
sha256: digestSchema,
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
state: z.literal("failed"),
|
||||
path: z.string(),
|
||||
error: z.string(),
|
||||
})
|
||||
.strict(),
|
||||
])
|
||||
.nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const replayEvidenceSchema = evidenceEnvelopeSchema
|
||||
.omit({ normalized_result: true })
|
||||
.extend({ normalized_result: replayExecutionResultSchema });
|
||||
|
||||
export const controlledReplayOutputSchema = z
|
||||
.object({
|
||||
phase: z.enum(["plan", "execute"]),
|
||||
plan: replayPlanSchema.nullable(),
|
||||
source_evidence: z.array(replayEvidenceSchema),
|
||||
evidence: replayEvidenceSchema.nullable(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (
|
||||
(value.phase === "plan" &&
|
||||
(value.plan === null ||
|
||||
value.evidence !== null ||
|
||||
value.source_evidence.length !== 0)) ||
|
||||
(value.phase === "execute" &&
|
||||
(value.plan !== null ||
|
||||
value.evidence === null ||
|
||||
value.source_evidence.length === 0))
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Replay output phase does not match its payload",
|
||||
});
|
||||
});
|
||||
|
||||
export type ControlledReplayInput = z.infer<typeof controlledReplayInputSchema>;
|
||||
export type ReplayPlan = z.infer<typeof replayPlanSchema>;
|
||||
export type ReplayExecutionResult = z.infer<typeof replayExecutionResultSchema>;
|
||||
@@ -16,7 +16,8 @@ export type PermissionCapability =
|
||||
| "snapshot_write"
|
||||
| "artifact_extract"
|
||||
| "native_mount"
|
||||
| "reference_read";
|
||||
| "reference_read"
|
||||
| "javascript_replay";
|
||||
|
||||
/** Ordered network authority; each mode includes the modes before it. */
|
||||
type PermissionNetwork = "none" | "loopback" | "external";
|
||||
|
||||
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.0.0-beta.4",
|
||||
clientSdkVersion: "2.0.0-beta.4",
|
||||
coreSdkVersion: "2.0.0-beta.4",
|
||||
skillVersion: "17",
|
||||
skillVersion: "18",
|
||||
} as const;
|
||||
|
||||
+11
@@ -127,6 +127,10 @@ export const run = async (
|
||||
roots: [...config.value.analysisSnapshotFilePolicy.roots],
|
||||
};
|
||||
const runtimeInvestigationRoots = [...config.value.investigationInputRoots];
|
||||
const runtimeJavascriptReplayPolicy = {
|
||||
...config.value.javascriptReplayPolicy,
|
||||
roots: [...config.value.javascriptReplayPolicy.roots],
|
||||
};
|
||||
const liveServers = new Set<ReturnType<typeof createServer>>();
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
@@ -146,6 +150,7 @@ export const run = async (
|
||||
electronObservation,
|
||||
artifactIntegrityContinueEnabled: () =>
|
||||
currentConfig.artifactIntegrityContinueEnabled,
|
||||
javascriptReplayPolicy: runtimeJavascriptReplayPolicy,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled:
|
||||
currentConfig.processExecutionPolicy.enabled,
|
||||
@@ -158,6 +163,8 @@ export const run = async (
|
||||
currentConfig.electronObservationEnabled &&
|
||||
currentConfig.electronCdpEndpoints.length > 0 &&
|
||||
currentConfig.electronFileRoots.length > 0,
|
||||
javascriptReplayEnabled:
|
||||
currentConfig.javascriptReplayPolicy.enabled,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -233,6 +240,10 @@ export const run = async (
|
||||
runtimeInvestigationRoots.length,
|
||||
...refreshed.value.investigationInputRoots,
|
||||
);
|
||||
Object.assign(
|
||||
runtimeJavascriptReplayPolicy,
|
||||
refreshed.value.javascriptReplayPolicy,
|
||||
);
|
||||
for (const server of liveServers) server.sendToolListChanged();
|
||||
});
|
||||
}) ?? (() => undefined);
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
import {
|
||||
Script,
|
||||
SourceTextModule,
|
||||
SyntheticModule,
|
||||
createContext,
|
||||
type Module,
|
||||
} from "node:vm";
|
||||
import { types } from "node:util";
|
||||
|
||||
interface WorkerModule {
|
||||
readonly alias: string;
|
||||
readonly format: "esm" | "commonjs-factory";
|
||||
readonly dependencies: Readonly<Record<string, string>>;
|
||||
readonly source: string;
|
||||
}
|
||||
|
||||
interface WorkerSide {
|
||||
readonly modules: readonly WorkerModule[];
|
||||
readonly entryAlias: string;
|
||||
readonly entryExport: string;
|
||||
}
|
||||
|
||||
interface WorkerRequest {
|
||||
readonly schemaVersion: 1;
|
||||
readonly left: WorkerSide;
|
||||
readonly right?: WorkerSide;
|
||||
readonly cases: readonly {
|
||||
readonly caseId: string;
|
||||
readonly arguments: readonly unknown[];
|
||||
readonly inputSha256: string;
|
||||
}[];
|
||||
readonly determinism: {
|
||||
readonly clockIso: string;
|
||||
readonly randomSeed: number;
|
||||
};
|
||||
readonly limits: {
|
||||
readonly resultDepth: number;
|
||||
readonly resultNodes: number;
|
||||
readonly exceptionBytes: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface WorkerOutcome {
|
||||
readonly case_id: string;
|
||||
readonly outcome: "return" | "exception" | "serialization_error" | "denied";
|
||||
readonly value?: unknown;
|
||||
readonly exception?: {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
readonly stack: string | null;
|
||||
};
|
||||
readonly input_sha256: string;
|
||||
readonly output_sha256: null;
|
||||
readonly truncated: false;
|
||||
}
|
||||
|
||||
class ReplayDeniedError extends Error {
|
||||
override readonly name = "ReplayDeniedError";
|
||||
}
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
||||
const request = JSON.parse(
|
||||
Buffer.concat(chunks).toString("utf8"),
|
||||
) as WorkerRequest;
|
||||
if (request.schemaVersion !== 1)
|
||||
throw new TypeError("Unsupported replay worker protocol");
|
||||
const left: WorkerOutcome[] = [];
|
||||
const right: WorkerOutcome[] = [];
|
||||
for (let index = 0; index < request.cases.length; index += 1) {
|
||||
const replayCase = request.cases[index];
|
||||
if (replayCase === undefined) continue;
|
||||
left.push(await runCase(request.left, replayCase, request, index));
|
||||
if (request.right !== undefined)
|
||||
right.push(await runCase(request.right, replayCase, request, index));
|
||||
}
|
||||
process.stdout.write(
|
||||
JSON.stringify({
|
||||
schema_version: 1,
|
||||
left,
|
||||
...(request.right === undefined ? {} : { right }),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const runCase = async (
|
||||
side: WorkerSide,
|
||||
replayCase: WorkerRequest["cases"][number],
|
||||
request: WorkerRequest,
|
||||
index: number,
|
||||
): Promise<WorkerOutcome> => {
|
||||
try {
|
||||
const loaded = await loadEntry(side, request, index);
|
||||
if (typeof loaded !== "function")
|
||||
throw new TypeError(`Replay export is not callable: ${side.entryExport}`);
|
||||
const returned = await Reflect.apply(loaded, undefined, [
|
||||
...replayCase.arguments,
|
||||
]);
|
||||
try {
|
||||
return {
|
||||
case_id: replayCase.caseId,
|
||||
outcome: "return",
|
||||
value: projectValue(
|
||||
returned,
|
||||
request.limits.resultDepth,
|
||||
request.limits.resultNodes,
|
||||
),
|
||||
input_sha256: replayCase.inputSha256,
|
||||
output_sha256: null,
|
||||
truncated: false,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return exceptionOutcome(
|
||||
replayCase,
|
||||
"serialization_error",
|
||||
error,
|
||||
request.limits.exceptionBytes,
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
return exceptionOutcome(
|
||||
replayCase,
|
||||
error instanceof ReplayDeniedError ? "denied" : "exception",
|
||||
error,
|
||||
request.limits.exceptionBytes,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const loadEntry = async (
|
||||
side: WorkerSide,
|
||||
request: WorkerRequest,
|
||||
caseIndex: number,
|
||||
): Promise<unknown> => {
|
||||
const modules = new Map(side.modules.map((module) => [module.alias, module]));
|
||||
const context = deterministicContext(request, caseIndex);
|
||||
const esmCache = new Map<string, Module>();
|
||||
const commonJsCache = new Map<string, Record<string, unknown>>();
|
||||
|
||||
const loadCommonJs = (alias: string): Record<string, unknown> => {
|
||||
const cached = commonJsCache.get(alias);
|
||||
if (cached !== undefined) return cached;
|
||||
const descriptor = requiredModule(modules, alias);
|
||||
if (descriptor.format !== "commonjs-factory")
|
||||
throw new TypeError(
|
||||
`Synchronous require cannot load ESM module: ${alias}`,
|
||||
);
|
||||
const module = { exports: {} as Record<string, unknown> };
|
||||
commonJsCache.set(alias, module.exports);
|
||||
const requireModule = ((specifier: string): Record<string, unknown> => {
|
||||
const dependency = descriptor.dependencies[specifier];
|
||||
if (dependency === undefined)
|
||||
throw new ReplayDeniedError(`Undeclared require: ${specifier}`);
|
||||
return loadCommonJs(dependency);
|
||||
}) as ((specifier: string) => Record<string, unknown>) &
|
||||
Record<string, unknown>;
|
||||
installRspackHelpers(requireModule);
|
||||
const source = normalizeFactorySource(descriptor.source);
|
||||
const factory = new Script(`(${source})`, {
|
||||
filename: `/modules/${alias}.js`,
|
||||
}).runInContext(context) as (
|
||||
module: { exports: Record<string, unknown> },
|
||||
exports: Record<string, unknown>,
|
||||
require_: typeof requireModule,
|
||||
) => void;
|
||||
factory(module, module.exports, requireModule);
|
||||
commonJsCache.set(alias, module.exports);
|
||||
return module.exports;
|
||||
};
|
||||
|
||||
const loadEsm = async (alias: string): Promise<Module> => {
|
||||
const cached = esmCache.get(alias);
|
||||
if (cached !== undefined) return cached;
|
||||
const descriptor = requiredModule(modules, alias);
|
||||
let module: Module;
|
||||
if (descriptor.format === "commonjs-factory") {
|
||||
const exports = loadCommonJs(alias);
|
||||
const names = [...new Set(["default", ...Object.keys(exports)])];
|
||||
module = new SyntheticModule(
|
||||
names,
|
||||
function () {
|
||||
this.setExport("default", exports);
|
||||
for (const name of Object.keys(exports))
|
||||
this.setExport(name, exports[name]);
|
||||
},
|
||||
{ context, identifier: `rea:${alias}` },
|
||||
);
|
||||
} else {
|
||||
module = new SourceTextModule(descriptor.source, {
|
||||
context,
|
||||
identifier: `rea:${alias}`,
|
||||
initializeImportMeta: (meta) => {
|
||||
meta.url = `rea:${alias}`;
|
||||
},
|
||||
importModuleDynamically: () => {
|
||||
throw new ReplayDeniedError(
|
||||
"Dynamic import is unavailable in controlled replay",
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
esmCache.set(alias, module);
|
||||
await module.link(async (specifier) => {
|
||||
const dependency = descriptor.dependencies[specifier];
|
||||
if (dependency === undefined)
|
||||
throw new ReplayDeniedError(`Undeclared import: ${specifier}`);
|
||||
return loadEsm(dependency);
|
||||
});
|
||||
await module.evaluate();
|
||||
return module;
|
||||
};
|
||||
|
||||
const entry = requiredModule(modules, side.entryAlias);
|
||||
if (entry.format === "commonjs-factory") {
|
||||
const exported = loadCommonJs(side.entryAlias);
|
||||
return side.entryExport === "default"
|
||||
? (exported.default ?? exported)
|
||||
: exported[side.entryExport];
|
||||
}
|
||||
const namespace = (await loadEsm(side.entryAlias)).namespace;
|
||||
return (namespace as Record<string, unknown>)[side.entryExport];
|
||||
};
|
||||
|
||||
const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
|
||||
let state = (request.determinism.randomSeed + caseIndex) >>> 0;
|
||||
const random = (): number => {
|
||||
state ^= state << 13;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5;
|
||||
return (state >>> 0) / 0x1_0000_0000;
|
||||
};
|
||||
const epoch = Date.parse(request.determinism.clockIso);
|
||||
class ReplayDate extends Date {
|
||||
constructor(...arguments_: [] | [string | number]) {
|
||||
super(arguments_.length === 0 ? epoch : arguments_[0]);
|
||||
}
|
||||
static override now(): number {
|
||||
return epoch;
|
||||
}
|
||||
}
|
||||
const replayMath = Object.create(Math) as Math;
|
||||
Object.defineProperty(replayMath, "random", { value: random });
|
||||
return createContext(
|
||||
{ Date: ReplayDate, Math: replayMath },
|
||||
{
|
||||
name: "rea-controlled-replay",
|
||||
codeGeneration: { strings: false, wasm: false },
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const installRspackHelpers = (
|
||||
require_: ((specifier: string) => Record<string, unknown>) &
|
||||
Record<string, unknown>,
|
||||
): void => {
|
||||
require_.d = (
|
||||
exports: Record<string, unknown>,
|
||||
definitions: Record<string, () => unknown>,
|
||||
) => {
|
||||
for (const [name, getter] of Object.entries(definitions))
|
||||
if (!Object.prototype.hasOwnProperty.call(exports, name))
|
||||
Object.defineProperty(exports, name, { enumerable: true, get: getter });
|
||||
};
|
||||
require_.r = (exports: Record<string, unknown>) => {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
};
|
||||
require_.n = (module: Record<string, unknown>) => {
|
||||
const getter = () => (module.__esModule === true ? module.default : module);
|
||||
Object.defineProperty(getter, "a", { get: getter });
|
||||
return getter;
|
||||
};
|
||||
require_.nmd = (module: Record<string, unknown>) => module;
|
||||
};
|
||||
|
||||
const requiredModule = (
|
||||
modules: ReadonlyMap<string, WorkerModule>,
|
||||
alias: string,
|
||||
): WorkerModule => {
|
||||
const module = modules.get(alias);
|
||||
if (module === undefined)
|
||||
throw new TypeError(`Undeclared module alias: ${alias}`);
|
||||
return module;
|
||||
};
|
||||
|
||||
const normalizeFactorySource = (source: string): string =>
|
||||
/^\s*\d+\s*\(/u.test(source)
|
||||
? source.replace(/^\s*\d+\s*\(/u, "function(")
|
||||
: source;
|
||||
|
||||
const projectValue = (
|
||||
value: unknown,
|
||||
maximumDepth: number,
|
||||
maximumNodes: number,
|
||||
): unknown => {
|
||||
let nodes = 0;
|
||||
const visit = (
|
||||
candidate: unknown,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
): unknown => {
|
||||
nodes += 1;
|
||||
if (nodes > maximumNodes || depth > maximumDepth)
|
||||
throw new RangeError("Replay result projection limit exceeded");
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate === "string" ||
|
||||
typeof candidate === "boolean"
|
||||
)
|
||||
return candidate;
|
||||
if (typeof candidate === "number") {
|
||||
if (!Number.isFinite(candidate))
|
||||
throw new TypeError("Non-finite replay result number");
|
||||
return candidate;
|
||||
}
|
||||
if (typeof candidate !== "object")
|
||||
throw new TypeError(
|
||||
`Unsupported replay result type: ${typeof candidate}`,
|
||||
);
|
||||
if (types.isProxy(candidate))
|
||||
throw new TypeError("Proxy replay results are unavailable");
|
||||
if (ancestors.has(candidate)) throw new TypeError("Cyclic replay result");
|
||||
ancestors.add(candidate);
|
||||
try {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(candidate);
|
||||
const output: unknown[] | Record<string, unknown> = Array.isArray(
|
||||
candidate,
|
||||
)
|
||||
? []
|
||||
: {};
|
||||
if (!Array.isArray(candidate)) {
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
}
|
||||
for (const [key, descriptor] of Object.entries(descriptors)) {
|
||||
if (key === "length" && Array.isArray(candidate)) continue;
|
||||
if (!("value" in descriptor))
|
||||
throw new TypeError("Replay result accessors are unavailable");
|
||||
if (Array.isArray(output)) {
|
||||
if (!/^\d+$/u.test(key))
|
||||
throw new TypeError(
|
||||
"Replay arrays may only contain indexed values",
|
||||
);
|
||||
output[Number(key)] = visit(descriptor.value, depth + 1, ancestors);
|
||||
} else output[key] = visit(descriptor.value, depth + 1, ancestors);
|
||||
}
|
||||
return output;
|
||||
} finally {
|
||||
ancestors.delete(candidate);
|
||||
}
|
||||
};
|
||||
return visit(value, 0, new Set());
|
||||
};
|
||||
|
||||
const exceptionOutcome = (
|
||||
replayCase: WorkerRequest["cases"][number],
|
||||
outcome: "exception" | "serialization_error" | "denied",
|
||||
error: unknown,
|
||||
maximumBytes: number,
|
||||
): WorkerOutcome => {
|
||||
const details = exceptionDetails(error);
|
||||
const name = bounded(details.name, maximumBytes);
|
||||
const message = bounded(details.message, maximumBytes);
|
||||
const stack =
|
||||
details.stack === null ? null : bounded(details.stack, maximumBytes);
|
||||
return {
|
||||
case_id: replayCase.caseId,
|
||||
outcome,
|
||||
exception: { name, message, stack },
|
||||
input_sha256: replayCase.inputSha256,
|
||||
output_sha256: null,
|
||||
truncated: false,
|
||||
};
|
||||
};
|
||||
|
||||
const exceptionDetails = (
|
||||
error: unknown,
|
||||
): {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
readonly stack: string | null;
|
||||
} => {
|
||||
if (typeof error !== "object" || error === null)
|
||||
return { name: "Error", message: "Unknown replay exception", stack: null };
|
||||
if (types.isProxy(error))
|
||||
return { name: "Error", message: "Proxy replay exception", stack: null };
|
||||
const own = Object.getOwnPropertyDescriptors(error);
|
||||
const prototype = Object.getPrototypeOf(error) as object | null;
|
||||
const inherited =
|
||||
prototype === null ? {} : Object.getOwnPropertyDescriptors(prototype);
|
||||
const stringValue = (
|
||||
descriptor: PropertyDescriptor | undefined,
|
||||
): string | null =>
|
||||
descriptor !== undefined &&
|
||||
"value" in descriptor &&
|
||||
typeof descriptor.value === "string"
|
||||
? descriptor.value
|
||||
: null;
|
||||
return {
|
||||
name: stringValue(own.name) ?? stringValue(inherited.name) ?? "Error",
|
||||
message: stringValue(own.message) ?? "Unknown replay exception",
|
||||
stack: stringValue(own.stack),
|
||||
};
|
||||
};
|
||||
|
||||
const bounded = (value: string, maximumBytes: number): string => {
|
||||
const bytes = Buffer.from(value);
|
||||
if (bytes.byteLength <= maximumBytes) return value;
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
for (let end = maximumBytes; end >= Math.max(0, maximumBytes - 3); end -= 1) {
|
||||
try {
|
||||
return decoder.decode(bytes.subarray(0, end));
|
||||
} catch {
|
||||
/* try the preceding UTF-8 boundary */
|
||||
}
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Replay worker failed";
|
||||
process.stderr.write(message.slice(0, 4096));
|
||||
process.exitCode = 70;
|
||||
});
|
||||
@@ -0,0 +1,580 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
digestBytes,
|
||||
digestJson,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
import {
|
||||
parseReplayWorkerResponse,
|
||||
type WorkerProtocolOutcome,
|
||||
type WorkerProtocolResponse,
|
||||
} from "./ReplayWorkerProtocol.js";
|
||||
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
/** Run one prepared experiment under the exact Linux ADR-0002 boundary. */
|
||||
export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
async execute(
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReplayExecutionResult> {
|
||||
if (isAborted(signal))
|
||||
return terminationResult(prepared, "", "cancelled", {
|
||||
state: "complete",
|
||||
residual_resources: [],
|
||||
});
|
||||
const unit = `rea-replay-${randomBytes(8).toString("hex")}.service`;
|
||||
const workerPath = prepared.publicPlan.runtime.worker.path;
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
if (
|
||||
digestBytes(await readFile(workerPath)) !==
|
||||
prepared.publicPlan.runtime.worker.sha256
|
||||
)
|
||||
throw new TypeError("Replay worker changed after approval");
|
||||
if (
|
||||
linuxX64ReplaySeccompDigest() !==
|
||||
prepared.publicPlan.sandbox.seccomp_sha256
|
||||
)
|
||||
throw new TypeError("Replay seccomp policy changed after approval");
|
||||
const request = workerRequest(prepared);
|
||||
const encoded = Buffer.from(JSON.stringify(request));
|
||||
if (encoded.byteLength > prepared.publicPlan.limits.protocol_bytes)
|
||||
throw new RangeError(
|
||||
"Replay worker protocol input exceeds the committed limit",
|
||||
);
|
||||
const filter = await temporaryFilterHandle();
|
||||
const arguments_ = systemdArguments(
|
||||
unit,
|
||||
policy,
|
||||
prepared,
|
||||
workerPath,
|
||||
closure,
|
||||
filter.path,
|
||||
);
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
requestTermination();
|
||||
};
|
||||
try {
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
child = spawn(policy.systemdRunPath, arguments_, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
PATH: "/usr/bin:/bin",
|
||||
LANG: "C",
|
||||
LC_ALL: "C",
|
||||
TZ: "UTC",
|
||||
...(process.env.XDG_RUNTIME_DIR === undefined
|
||||
? {}
|
||||
: { XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }),
|
||||
...(process.env.DBUS_SESSION_BUS_ADDRESS === undefined
|
||||
? {}
|
||||
: {
|
||||
DBUS_SESSION_BUS_ADDRESS:
|
||||
process.env.DBUS_SESSION_BUS_ADDRESS,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const output = boundedCollector(
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
);
|
||||
const diagnostics = boundedCollector(
|
||||
prepared.publicPlan.limits.stderr_bytes,
|
||||
);
|
||||
child.stdout?.on("data", output.append);
|
||||
child.stderr?.on("data", diagnostics.append);
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, signalName) =>
|
||||
resolve({
|
||||
code,
|
||||
signal: signalName,
|
||||
stdout: output.value(),
|
||||
stderr: diagnostics.value(),
|
||||
outputExceeded: output.exceeded(),
|
||||
}),
|
||||
);
|
||||
child.stdin?.end(encoded);
|
||||
});
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
const collected = await completion;
|
||||
if (terminationRequest !== undefined) await terminationRequest;
|
||||
const unitResult = await observeUnitResult(policy.systemctlPath, unit);
|
||||
const cleanup = await observeCleanup(policy.systemctlPath, unit);
|
||||
if (cancelled || timedOut)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
cancelled ? "cancelled" : "timeout",
|
||||
cleanup,
|
||||
);
|
||||
if (collected.outputExceeded)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
"Worker stdout exceeded the committed bound",
|
||||
);
|
||||
if (collected.code !== 0)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
collected.code === 137 || unitResult === "oom-kill" ? "oom" : "crash",
|
||||
cleanup,
|
||||
);
|
||||
let response: WorkerProtocolResponse;
|
||||
try {
|
||||
response = parseReplayWorkerResponse(
|
||||
JSON.parse(collected.stdout),
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
);
|
||||
} catch {
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
);
|
||||
}
|
||||
const outcomes = commitOutcomes(response.left);
|
||||
const right =
|
||||
response.right === undefined
|
||||
? undefined
|
||||
: commitOutcomes(response.right);
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(right ?? [])],
|
||||
...(right === undefined
|
||||
? {}
|
||||
: { comparison: compareOutcomes(outcomes, right) }),
|
||||
stderr: collected.stderr,
|
||||
termination: "completed",
|
||||
cleanup,
|
||||
limitations: [
|
||||
"Controlled replay observes the isolated extracted modules, not the original application runtime.",
|
||||
"Network and host filesystem access were unavailable; unsupported dependencies may change behavior.",
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", terminate);
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
if (child !== undefined && child.exitCode === null) {
|
||||
requestTermination();
|
||||
await terminationRequest;
|
||||
}
|
||||
await filter.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const workerRequest = (prepared: PreparedReplayPlan) => ({
|
||||
schemaVersion: 1,
|
||||
left: workerSide(prepared.publicPlan.left, prepared.leftSources),
|
||||
...(prepared.publicPlan.right === undefined ||
|
||||
prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: workerSide(prepared.publicPlan.right, prepared.rightSources) }),
|
||||
cases: prepared.publicPlan.cases.map((item) => ({
|
||||
caseId: item.case_id,
|
||||
arguments: item.arguments,
|
||||
inputSha256: item.sha256,
|
||||
})),
|
||||
determinism: {
|
||||
clockIso: prepared.publicPlan.determinism.clock_iso,
|
||||
randomSeed: prepared.publicPlan.determinism.random_seed,
|
||||
},
|
||||
limits: {
|
||||
resultDepth: prepared.publicPlan.limits.result_depth,
|
||||
resultNodes: prepared.publicPlan.limits.result_nodes,
|
||||
exceptionBytes: Math.min(
|
||||
64 * 1024,
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const workerSide = (
|
||||
side: PreparedReplayPlan["publicPlan"]["left"],
|
||||
sources: Readonly<Record<string, string>>,
|
||||
) => ({
|
||||
modules: side.modules.map((module) => ({
|
||||
alias: module.alias,
|
||||
format: module.format,
|
||||
dependencies: module.dependencies,
|
||||
source: sources[module.alias] ?? "",
|
||||
})),
|
||||
entryAlias: side.entry_alias,
|
||||
entryExport: side.entry_export,
|
||||
});
|
||||
|
||||
const systemdArguments = (
|
||||
unit: string,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
prepared: PreparedReplayPlan,
|
||||
workerPath: string,
|
||||
closure: readonly RuntimeFile[],
|
||||
filterPath: string,
|
||||
): string[] => {
|
||||
const limits = prepared.publicPlan.limits;
|
||||
const descriptorPaths = [
|
||||
filterPath,
|
||||
...closure.map(({ sourcePath }) => sourcePath),
|
||||
workerPath,
|
||||
];
|
||||
const workerFd = descriptorPaths.length + 2;
|
||||
const wrapper = descriptorPaths
|
||||
.map((_, index) => `exec ${String(index + 3)}<"$1"; shift`)
|
||||
.concat('exec "$@"')
|
||||
.join("\n");
|
||||
return [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
`--unit=${unit}`,
|
||||
`--property=MemoryMax=${String(limits.memory_bytes)}`,
|
||||
"--property=MemorySwapMax=0",
|
||||
`--property=TasksMax=${String(limits.tasks)}`,
|
||||
`--property=CPUQuota=${String(limits.cpu_quota_percent)}%`,
|
||||
"--property=KillMode=control-group",
|
||||
"--property=SendSIGKILL=yes",
|
||||
"--",
|
||||
policy.shellPath,
|
||||
"-c",
|
||||
wrapper,
|
||||
"rea-replay-wrapper",
|
||||
...descriptorPaths,
|
||||
policy.bubblewrapPath,
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work",
|
||||
"--setenv",
|
||||
"TMPDIR",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"TZ",
|
||||
"UTC",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C",
|
||||
"--setenv",
|
||||
"LC_ALL",
|
||||
"C",
|
||||
"--tmpfs",
|
||||
"/",
|
||||
"--dir",
|
||||
"/runtime",
|
||||
"--dir",
|
||||
"/work",
|
||||
"--size",
|
||||
String(limits.tmpfs_bytes),
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
...bindArguments(closure),
|
||||
"--ro-bind-fd",
|
||||
String(workerFd),
|
||||
"/runtime/worker.js",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--remount-ro",
|
||||
"/",
|
||||
"--chdir",
|
||||
"/work",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/runtime/node",
|
||||
`--max-old-space-size=${String(Math.max(8, Math.floor(limits.memory_bytes / 1024 / 1024 / 2)))}`,
|
||||
"--experimental-vm-modules",
|
||||
"--permission",
|
||||
"--allow-fs-read=/runtime/worker.js",
|
||||
"/runtime/worker.js",
|
||||
];
|
||||
};
|
||||
|
||||
const bindArguments = (closure: readonly RuntimeFile[]): string[] => {
|
||||
const arguments_: string[] = [];
|
||||
const directories = new Set<string>();
|
||||
for (const [index, item] of closure.entries()) {
|
||||
const destination = item.destinationPath;
|
||||
let parent = dirname(destination);
|
||||
const chain: string[] = [];
|
||||
while (parent !== "/" && !directories.has(parent)) {
|
||||
chain.push(parent);
|
||||
parent = dirname(parent);
|
||||
}
|
||||
for (const directory of chain.reverse()) {
|
||||
directories.add(directory);
|
||||
arguments_.push("--dir", directory);
|
||||
}
|
||||
arguments_.push("--ro-bind-fd", String(index + 4), destination);
|
||||
}
|
||||
return arguments_;
|
||||
};
|
||||
|
||||
type RuntimeFile = Awaited<
|
||||
ReturnType<typeof resolveLinuxRuntimeClosure>
|
||||
>[number];
|
||||
|
||||
const assertRuntimeCommitment = (
|
||||
prepared: PreparedReplayPlan,
|
||||
closure: readonly RuntimeFile[],
|
||||
): void => {
|
||||
const observed = closure.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
}));
|
||||
if (
|
||||
digestJson(observed) !==
|
||||
digestJson(prepared.publicPlan.runtime.read_only_files)
|
||||
)
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
};
|
||||
|
||||
const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
interface CollectedProcess {
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly outputExceeded: boolean;
|
||||
}
|
||||
|
||||
const boundedCollector = (maximum: number) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let overflow = false;
|
||||
return {
|
||||
append: (chunk: Buffer) => {
|
||||
const retained = chunk.subarray(0, Math.max(0, maximum - bytes));
|
||||
if (retained.byteLength > 0) chunks.push(retained);
|
||||
bytes += retained.byteLength;
|
||||
if (retained.byteLength < chunk.byteLength) overflow = true;
|
||||
},
|
||||
value: () => Buffer.concat(chunks).toString("utf8"),
|
||||
exceeded: () => overflow,
|
||||
};
|
||||
};
|
||||
|
||||
const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximum: number,
|
||||
) =>
|
||||
new Promise<{ code: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stdout = boundedCollector(maximum);
|
||||
const stderr = boundedCollector(maximum);
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
child.stdout?.on("data", stdout.append);
|
||||
child.stderr?.on("data", stderr.append);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout: stdout.value(), stderr: stderr.value() });
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const killUnit = async (systemctl: string, unit: string): Promise<void> => {
|
||||
try {
|
||||
await collect(
|
||||
systemctl,
|
||||
["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
|
||||
4096,
|
||||
);
|
||||
} catch {
|
||||
/* cleanup continues */
|
||||
}
|
||||
};
|
||||
|
||||
const observeCleanup = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<ReplayExecutionResult["cleanup"]> => {
|
||||
try {
|
||||
const state = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=ActiveState", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
if (
|
||||
state.code !== 0 ||
|
||||
state.stdout.trim() === "inactive" ||
|
||||
state.stdout.trim() === "failed" ||
|
||||
state.stdout.trim().length === 0
|
||||
) {
|
||||
await collect(systemctl, ["--user", "reset-failed", unit], 4096);
|
||||
return { state: "complete", residual_resources: [] };
|
||||
}
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
} catch {
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
}
|
||||
};
|
||||
|
||||
const observeUnitResult = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const result = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=Result", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
return result.stdout.trim();
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
|
||||
const compareOutcomes = (
|
||||
left: ReplayExecutionResult["outcomes"],
|
||||
right: ReplayExecutionResult["outcomes"],
|
||||
): NonNullable<ReplayExecutionResult["comparison"]> =>
|
||||
left.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status:
|
||||
right[index] === undefined
|
||||
? "unknown"
|
||||
: item.outcome === right[index].outcome &&
|
||||
item.output_sha256 === right[index].output_sha256
|
||||
? "equal"
|
||||
: "changed",
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
}));
|
||||
|
||||
const terminationResult = (
|
||||
prepared: PreparedReplayPlan,
|
||||
stderr: string,
|
||||
termination: "timeout" | "oom" | "crash" | "cancelled" | "protocol_error",
|
||||
cleanup: ReplayExecutionResult["cleanup"],
|
||||
limitation?: string,
|
||||
): ReplayExecutionResult => {
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(differential ? outcomes : [])],
|
||||
...(differential
|
||||
? {
|
||||
comparison: outcomes.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status: "unknown" as const,
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stderr,
|
||||
termination,
|
||||
cleanup,
|
||||
limitations: [
|
||||
limitation ??
|
||||
`Replay terminated with ${termination}; the requested functional result remains unknown.`,
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, realpath } from "node:fs/promises";
|
||||
|
||||
import type { ReplayRuntimeFileIdentity } from "../application/JavaScriptReplayPlanning.js";
|
||||
|
||||
const LDD_OUTPUT_LIMIT = 64 * 1024;
|
||||
|
||||
/** Resolve and content-address the exact ELF closure mounted into a replay. */
|
||||
export const resolveLinuxRuntimeClosure = async (
|
||||
nodePath: string,
|
||||
): Promise<readonly ReplayRuntimeFileIdentity[]> => {
|
||||
const canonicalNode = await realpath(nodePath);
|
||||
const collected = await collectLdd(canonicalNode);
|
||||
if (collected.code !== 0)
|
||||
throw new TypeError(
|
||||
"Node runtime dependency closure could not be resolved",
|
||||
);
|
||||
const paths = [...collected.stdout.matchAll(/(?:=>\s+)?(\/[^\s()]+)/gu)]
|
||||
.map((match) => match[1])
|
||||
.filter((value): value is string => value !== undefined);
|
||||
const libraries = await Promise.all(
|
||||
[...new Set(paths)].map(async (path) => {
|
||||
const sourcePath = await realpath(path);
|
||||
return identity(sourcePath, path);
|
||||
}),
|
||||
);
|
||||
return [await identity(canonicalNode, "/runtime/node"), ...libraries];
|
||||
};
|
||||
|
||||
const identity = async (
|
||||
sourcePath: string,
|
||||
destinationPath: string,
|
||||
): Promise<ReplayRuntimeFileIdentity> => ({
|
||||
sourcePath,
|
||||
destinationPath,
|
||||
sha256: createHash("sha256")
|
||||
.update(await readFile(sourcePath))
|
||||
.digest("hex"),
|
||||
});
|
||||
|
||||
const collectLdd = async (
|
||||
path: string,
|
||||
): Promise<{ readonly code: number | null; readonly stdout: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn("/usr/bin/ldd", [path], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
let stdout = "";
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
const remaining = Math.max(
|
||||
0,
|
||||
LDD_OUTPUT_LIMIT - Buffer.byteLength(stdout),
|
||||
);
|
||||
stdout += chunk.subarray(0, remaining).toString("utf8");
|
||||
});
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const BPF_LD_W_ABS = 0x20;
|
||||
const BPF_JMP_JEQ_K = 0x15;
|
||||
const BPF_RET_K = 0x06;
|
||||
const SECCOMP_RET_KILL_PROCESS = 0x8000_0000;
|
||||
const SECCOMP_RET_ERRNO = 0x0005_0000 | 1;
|
||||
const SECCOMP_RET_ALLOW = 0x7fff_0000;
|
||||
const AUDIT_ARCH_X86_64 = 0xc000_003e;
|
||||
const IOCTL = 16;
|
||||
const TIOCSTI = 0x5412;
|
||||
|
||||
const DENIED_X86_64_SYSCALLS = [
|
||||
101, 103, 155, 161, 163, 165, 166, 167, 168, 169, 172, 173, 175, 176, 179,
|
||||
212, 246, 248, 249, 250, 272, 298, 303, 304, 308, 310, 311, 312, 313, 320,
|
||||
321, 323, 425, 426, 427, 428, 429, 430, 431, 432, 433, 442,
|
||||
] as const;
|
||||
|
||||
interface Instruction {
|
||||
readonly code: number;
|
||||
readonly jt: number;
|
||||
readonly jf: number;
|
||||
readonly k: number;
|
||||
}
|
||||
|
||||
/** Build the architecture-checked deny filter committed by ADR-0002. */
|
||||
export const buildLinuxX64ReplaySeccomp = (): Uint8Array => {
|
||||
const instructions: Instruction[] = [
|
||||
{ code: BPF_LD_W_ABS, jt: 0, jf: 0, k: 4 },
|
||||
{ code: BPF_JMP_JEQ_K, jt: 1, jf: 0, k: AUDIT_ARCH_X86_64 },
|
||||
{ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_KILL_PROCESS },
|
||||
{ code: BPF_LD_W_ABS, jt: 0, jf: 0, k: 0 },
|
||||
];
|
||||
for (const syscall of DENIED_X86_64_SYSCALLS) {
|
||||
instructions.push({ code: BPF_JMP_JEQ_K, jt: 0, jf: 1, k: syscall });
|
||||
instructions.push({ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_ERRNO });
|
||||
}
|
||||
instructions.push(
|
||||
{ code: BPF_JMP_JEQ_K, jt: 0, jf: 3, k: IOCTL },
|
||||
{ code: BPF_LD_W_ABS, jt: 0, jf: 0, k: 24 },
|
||||
{ code: BPF_JMP_JEQ_K, jt: 0, jf: 1, k: TIOCSTI },
|
||||
{ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_ERRNO },
|
||||
{ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW },
|
||||
);
|
||||
const encoded = new Uint8Array(instructions.length * 8);
|
||||
const view = new DataView(encoded.buffer);
|
||||
instructions.forEach((instruction, index) => {
|
||||
const offset = index * 8;
|
||||
view.setUint16(offset, instruction.code, true);
|
||||
view.setUint8(offset + 2, instruction.jt);
|
||||
view.setUint8(offset + 3, instruction.jf);
|
||||
view.setUint32(offset + 4, instruction.k, true);
|
||||
});
|
||||
return encoded;
|
||||
};
|
||||
|
||||
export const linuxX64ReplaySeccompDigest = (): string =>
|
||||
createHash("sha256").update(buildLinuxX64ReplaySeccomp()).digest("hex");
|
||||
@@ -0,0 +1,76 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const workerOutcomeSchema = z
|
||||
.object({
|
||||
case_id: z.string(),
|
||||
outcome: z.enum(["return", "exception", "serialization_error", "denied"]),
|
||||
value: z.json().optional(),
|
||||
exception: z
|
||||
.object({
|
||||
name: z.string(),
|
||||
message: z.string(),
|
||||
stack: z.string().nullable(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
input_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
output_sha256: z.null(),
|
||||
truncated: z.literal(false),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (value.outcome === "return" && value.value === undefined)
|
||||
context.addIssue({ code: "custom", message: "Return value is missing" });
|
||||
if (value.outcome !== "return" && value.exception === undefined)
|
||||
context.addIssue({ code: "custom", message: "Exception is missing" });
|
||||
if (value.outcome === "return" && value.exception !== undefined)
|
||||
context.addIssue({ code: "custom", message: "Return has an exception" });
|
||||
});
|
||||
|
||||
const workerResponseSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
left: z.array(workerOutcomeSchema),
|
||||
right: z.array(workerOutcomeSchema).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type WorkerProtocolOutcome = z.infer<typeof workerOutcomeSchema>;
|
||||
export type WorkerProtocolResponse = z.infer<typeof workerResponseSchema>;
|
||||
|
||||
interface ExpectedCase {
|
||||
readonly case_id: string;
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
/** Strictly authenticate case ordering and commitments in worker output. */
|
||||
export const parseReplayWorkerResponse = (
|
||||
rawResponse: unknown,
|
||||
cases: readonly ExpectedCase[],
|
||||
differential: boolean,
|
||||
): WorkerProtocolResponse => {
|
||||
const response = workerResponseSchema.parse(rawResponse);
|
||||
if ((response.right !== undefined) !== differential)
|
||||
throw new TypeError("Replay worker differential response is incomplete");
|
||||
validateOutcomeSequence(response.left, cases);
|
||||
if (response.right !== undefined)
|
||||
validateOutcomeSequence(response.right, cases);
|
||||
return response;
|
||||
};
|
||||
|
||||
const validateOutcomeSequence = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
cases: readonly ExpectedCase[],
|
||||
): void => {
|
||||
if (outcomes.length !== cases.length)
|
||||
throw new TypeError("Replay worker response case count changed");
|
||||
outcomes.forEach((outcome, index) => {
|
||||
const expected = cases[index];
|
||||
if (
|
||||
expected === undefined ||
|
||||
outcome.case_id !== expected.case_id ||
|
||||
outcome.input_sha256 !== expected.sha256
|
||||
)
|
||||
throw new TypeError("Replay worker response case identity changed");
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,268 @@
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
mkdtemp,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn, type StdioOptions } from "node:child_process";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
ReplayExecutableIdentity,
|
||||
ReplaySourceBytes,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { digestBytes } from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
|
||||
const VERSION_OUTPUT_LIMIT = 16 * 1024;
|
||||
|
||||
/** Production planning host for descriptor-backed reads and fail-closed probes. */
|
||||
export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
async readSource(
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
): Promise<ReplaySourceBytes> {
|
||||
const canonicalPath = await realpath(path);
|
||||
const handle = await open(
|
||||
canonicalPath,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW,
|
||||
);
|
||||
try {
|
||||
const metadata = await handle.stat();
|
||||
if (!metadata.isFile() || metadata.size > maximumBytes)
|
||||
throw new RangeError(
|
||||
`Replay source exceeds its declared limit: ${canonicalPath}`,
|
||||
);
|
||||
const bytes = await handle.readFile();
|
||||
return { canonicalPath, bytes };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
async identifyExecutable(
|
||||
path: string,
|
||||
versionArguments: readonly string[],
|
||||
): Promise<ReplayExecutableIdentity> {
|
||||
const canonicalPath = await realpath(path);
|
||||
const metadata = await stat(canonicalPath);
|
||||
if (!metadata.isFile())
|
||||
throw new TypeError(`Replay executable is not a file: ${canonicalPath}`);
|
||||
const [bytes, version] = await Promise.all([
|
||||
readFile(canonicalPath),
|
||||
capture(canonicalPath, versionArguments, VERSION_OUTPUT_LIMIT),
|
||||
]);
|
||||
return {
|
||||
path: canonicalPath,
|
||||
version: version.trim(),
|
||||
sha256: digestBytes(bytes),
|
||||
};
|
||||
}
|
||||
|
||||
identifyWorker(): Promise<ReplayExecutableIdentity> {
|
||||
return this.identifyExecutable(
|
||||
fileURLToPath(new URL("./JavaScriptReplayWorker.js", import.meta.url)),
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
identifyRuntimeClosure(nodePath: string) {
|
||||
return resolveLinuxRuntimeClosure(nodePath);
|
||||
}
|
||||
|
||||
seccompDigest(): string {
|
||||
return linuxX64ReplaySeccompDigest();
|
||||
}
|
||||
|
||||
async probe(policy: JavaScriptReplayPolicy): Promise<void> {
|
||||
if (process.platform !== "linux" || process.arch !== "x64")
|
||||
throw new TypeError("Controlled replay requires Linux x86_64 in v1");
|
||||
const bwrapMetadata = await stat(policy.bubblewrapPath);
|
||||
if ((bwrapMetadata.mode & 0o4000) !== 0)
|
||||
throw new TypeError("Setuid Bubblewrap is not admitted by replay policy");
|
||||
if (
|
||||
(await readFile("/sys/fs/cgroup/cgroup.controllers", "utf8")).trim()
|
||||
.length === 0
|
||||
)
|
||||
throw new TypeError("Controlled replay requires delegated cgroup v2");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-probe-"));
|
||||
const filterPath = join(directory, "seccomp.bpf");
|
||||
await writeFile(filterPath, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const filter = await open(filterPath, "r");
|
||||
try {
|
||||
await run(
|
||||
policy.bubblewrapPath,
|
||||
[
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind-try",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/usr/bin/true",
|
||||
],
|
||||
["ignore", "pipe", "pipe", filter.fd],
|
||||
);
|
||||
await runExpectFailure(
|
||||
policy.bubblewrapPath,
|
||||
[
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind-try",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/usr/bin/unshare",
|
||||
"--mount",
|
||||
"/usr/bin/true",
|
||||
],
|
||||
["ignore", "pipe", "pipe", filter.fd],
|
||||
);
|
||||
await run(policy.systemdRunPath, [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
"--property=MemoryMax=16777216",
|
||||
"--property=MemorySwapMax=0",
|
||||
"--property=TasksMax=2",
|
||||
"--",
|
||||
"/usr/bin/true",
|
||||
]);
|
||||
} finally {
|
||||
await filter.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const capture = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximumBytes: number,
|
||||
): Promise<string> => {
|
||||
if (arguments_.length === 0) return "content-addressed-worker-v1";
|
||||
const result = await collect(executable, arguments_, maximumBytes);
|
||||
if (result.code !== 0)
|
||||
throw new TypeError(`Replay executable probe failed: ${executable}`);
|
||||
return result.stdout.length > 0 ? result.stdout : result.stderr;
|
||||
};
|
||||
|
||||
const run = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
stdio?: StdioOptions,
|
||||
): Promise<void> => {
|
||||
const result = await collect(
|
||||
executable,
|
||||
arguments_,
|
||||
VERSION_OUTPUT_LIMIT,
|
||||
stdio,
|
||||
);
|
||||
if (result.code !== 0)
|
||||
throw new TypeError(
|
||||
`Replay feature probe failed (${String(result.code)}): ${executable}: ${result.stderr.trim()}`,
|
||||
);
|
||||
};
|
||||
|
||||
const runExpectFailure = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
stdio: StdioOptions,
|
||||
): Promise<void> => {
|
||||
const result = await collect(
|
||||
executable,
|
||||
arguments_,
|
||||
VERSION_OUTPUT_LIMIT,
|
||||
stdio,
|
||||
);
|
||||
if (result.code === 0)
|
||||
throw new TypeError(
|
||||
`Replay denial probe unexpectedly succeeded: ${executable}`,
|
||||
);
|
||||
};
|
||||
|
||||
const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximumBytes: number,
|
||||
stdio: StdioOptions = ["ignore", "pipe", "pipe"],
|
||||
): Promise<{
|
||||
readonly code: number | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], { stdio });
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
const retain = (current: string, chunk: Buffer): string => {
|
||||
const remaining = Math.max(0, maximumBytes - Buffer.byteLength(current));
|
||||
return current + chunk.subarray(0, remaining).toString("utf8");
|
||||
};
|
||||
if (child.stdout !== null)
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout = retain(stdout, chunk);
|
||||
});
|
||||
if (child.stderr !== null)
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr = retain(stderr, chunk);
|
||||
});
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout, stderr });
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,13 @@ import { registerBrowserTools } from "./registerBrowserTools.js";
|
||||
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
|
||||
import { registerElectronTools } from "./registerElectronTools.js";
|
||||
import { registerApplicationTools } from "./registerApplicationTools.js";
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { LinuxJavaScriptReplayRunner } from "../replay/LinuxJavaScriptReplayRunner.js";
|
||||
import { SystemJavaScriptReplayHost } from "../replay/SystemJavaScriptReplayHost.js";
|
||||
|
||||
export interface CreateServerOptions {
|
||||
readonly logger?: Logger;
|
||||
@@ -31,11 +38,15 @@ export interface CreateServerOptions {
|
||||
readonly browserObservation?: BrowserObservationPort;
|
||||
readonly electronObservation?: ElectronObservationPort;
|
||||
readonly artifactIntegrityContinueEnabled?: () => boolean;
|
||||
readonly javascriptReplayPolicy?: JavaScriptReplayPolicy;
|
||||
readonly javascriptReplayHost?: JavaScriptReplayHost;
|
||||
readonly javascriptReplayRunner?: JavaScriptReplayRunner;
|
||||
readonly availabilityPolicy?: () => {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
readonly javascriptReplayEnabled?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,6 +185,21 @@ export const createServer = (
|
||||
logger: toolLogger,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
replay: {
|
||||
policy: options.javascriptReplayPolicy ?? {
|
||||
enabled: false,
|
||||
roots: [],
|
||||
nodePath: process.execPath,
|
||||
bubblewrapPath: "/usr/bin/bwrap",
|
||||
systemdRunPath: "/usr/bin/systemd-run",
|
||||
systemctlPath: "/usr/bin/systemctl",
|
||||
shellPath: "/usr/bin/bash",
|
||||
},
|
||||
host: options.javascriptReplayHost ?? new SystemJavaScriptReplayHost(),
|
||||
runner:
|
||||
options.javascriptReplayRunner ?? new LinuxJavaScriptReplayRunner(),
|
||||
authority: options.permissionAuthority,
|
||||
},
|
||||
});
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
if (session !== undefined) {
|
||||
|
||||
@@ -5,15 +5,24 @@ import {
|
||||
compareApplicationVersionsEvidence,
|
||||
traceApplicationFeatureEvidence,
|
||||
} from "../application/JavaScriptApplicationWorkflowService.js";
|
||||
import {
|
||||
runControlledReplay,
|
||||
type JavaScriptReplayDependencies,
|
||||
} from "../application/JavaScriptReplayService.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "../contracts/applicationToolContracts.js";
|
||||
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { applicationVersionComparisonResultSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { parseEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import {
|
||||
controlledReplayInputSchema,
|
||||
controlledReplayOutputSchema,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
|
||||
interface ApplicationToolRegistration {
|
||||
readonly logger: Logger;
|
||||
@@ -21,6 +30,7 @@ interface ApplicationToolRegistration {
|
||||
readonly recordEvidenceWithUnknown:
|
||||
| BinarySessionPort["recordEvidenceWithUnknown"]
|
||||
| undefined;
|
||||
readonly replay: JavaScriptReplayDependencies;
|
||||
}
|
||||
|
||||
/** Register provider-neutral JavaScript application graph workflows. */
|
||||
@@ -28,7 +38,8 @@ export const registerApplicationTools = (
|
||||
server: McpServer,
|
||||
options: ApplicationToolRegistration,
|
||||
): void => {
|
||||
const [traceContract, compareContract] = APPLICATION_TOOL_CONTRACTS;
|
||||
const [traceContract, compareContract, replayContract] =
|
||||
APPLICATION_TOOL_CONTRACTS;
|
||||
server.registerTool(
|
||||
traceContract.name,
|
||||
toolRegistrationOptions(traceContract),
|
||||
@@ -77,6 +88,41 @@ export const registerApplicationTools = (
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
replayContract.name,
|
||||
toolRegistrationOptions(replayContract),
|
||||
async (input, context) => {
|
||||
const parsed = controlledReplayInputSchema.parse(input);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
replayContract.name,
|
||||
() =>
|
||||
runControlledReplay(options.replay, parsed, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress: mcpProgressReporter(context),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, replayContract);
|
||||
const output = controlledReplayOutputSchema.parse(result.value);
|
||||
if (output.evidence !== null) {
|
||||
const sourcesRecorded = recordSources(
|
||||
options.recordEvidence,
|
||||
output.source_evidence.map((item) => parseEvidence(item)),
|
||||
);
|
||||
if (!sourcesRecorded.ok)
|
||||
return toCallToolResult(sourcesRecorded, replayContract);
|
||||
const recorded = options.recordEvidence?.(
|
||||
parseEvidence(output.evidence),
|
||||
);
|
||||
if (recorded !== undefined && !recorded.ok)
|
||||
return toCallToolResult(recorded, replayContract);
|
||||
}
|
||||
return toCallToolResult(result, replayContract, {
|
||||
evidenceResourcesAvailable:
|
||||
output.evidence !== null && options.recordEvidence !== undefined,
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const recordSources = (
|
||||
|
||||
Reference in New Issue
Block a user