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()),
|
||||
|
||||
Reference in New Issue
Block a user