feat: add evidence-backed process investigations

This commit is contained in:
morluto
2026-07-12 20:36:00 +08:00
parent 9f60348d1b
commit cc8681a856
53 changed files with 2774 additions and 290 deletions
+22 -1
View File
@@ -29,9 +29,30 @@ export interface ProviderIdentity {
readonly version: string | null;
}
type AnalysisOperation = string;
interface CapabilityEffects {
readonly mutatesArtifact: boolean;
readonly launchesProcess: boolean;
readonly mayShowUi: boolean;
readonly mayAccessNetwork: boolean;
readonly mayWriteFilesystem: boolean;
readonly requiresPrivileges: boolean;
}
export interface CapabilityDescriptor {
readonly operation: AnalysisOperation;
readonly version: number;
readonly available: boolean;
readonly pagination: "none" | "offset" | "cursor";
readonly exhaustive: boolean;
readonly effects: CapabilityEffects;
readonly limitations: readonly string[];
}
/** Factory and capability declaration for an analysis implementation. */
export interface AnalysisProvider {
identity(): ProviderIdentity;
capabilities(): readonly string[];
capabilities(): readonly CapabilityDescriptor[];
createClient(target: BinaryTarget): AnalysisClient;
}
+35
View File
@@ -7,12 +7,16 @@ import {
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Evidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import type {
AnalysisClient,
AnalysisClientFactory,
AnalysisOperationPort,
AnalysisProvider,
ProviderIdentity,
} from "./AnalysisProvider.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
export interface BinarySessionPort extends AnalysisOperationPort {
@@ -26,6 +30,10 @@ export interface BinarySessionPort extends AnalysisOperationPort {
close(): Promise<Result<null, AnalysisError>>;
status(): JsonValue;
activeTarget(): BinaryTarget | undefined;
recordEvidence(evidence: Evidence): void;
exportEvidenceBundle(): EvidenceBundle;
importEvidenceBundle(bundle: unknown): number;
providerIdentity(): ProviderIdentity;
}
/**
@@ -43,12 +51,38 @@ export class BinarySession implements BinarySessionPort {
#transition: Promise<void> = Promise.resolve();
readonly #calls = new Set<Promise<unknown>>();
readonly #createClient: AnalysisClientFactory;
readonly #providerIdentity: ProviderIdentity;
readonly #evidence = new EvidenceLedger({ maxRecords: 10_000 });
constructor(readonly provider: AnalysisProvider | AnalysisClientFactory) {
this.#createClient =
typeof provider === "function"
? provider
: (target) => provider.createClient(target);
this.#providerIdentity =
typeof provider === "function"
? { id: "unidentified", name: "Unidentified provider", version: null }
: provider.identity();
}
/** Identify the provider producing evidence for this session. */
providerIdentity(): ProviderIdentity {
return this.#providerIdentity;
}
/** Add one successful public observation to the session ledger. */
recordEvidence(evidence: Evidence): void {
this.#evidence.record(evidence);
}
/** Return a deterministic snapshot without clearing session evidence. */
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
}
/** Atomically merge a validated evidence bundle into this session. */
importEvidenceBundle(bundle: unknown): number {
return this.#evidence.import(bundle);
}
/**
@@ -102,6 +136,7 @@ export class BinarySession implements BinarySessionPort {
this.#active = undefined;
await this.#drainCalls();
await previous?.client.close();
this.#evidence.clear();
return ok(null);
});
}
+1 -1
View File
@@ -25,7 +25,7 @@ export const runDirectAnalysis = async (
return { error: opened.error._tag, message: opened.error.message };
const result = await session.execute(tool, arguments_);
return result.ok
? createEvidence(opened.value, {
? createEvidence(opened.value, session.providerIdentity(), {
operation: tool,
parameters: arguments_,
result: result.value,
+10 -1
View File
@@ -4,6 +4,7 @@ import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { AnalysisProtocolError, type AnalysisError } from "../domain/errors.js";
import {
parseDocuments,
parseFunctionDossier,
parseAddressedPage,
parseListCount,
parseRelatedAddresses,
@@ -84,7 +85,7 @@ export class EnhancedTools {
case "analyze_function": {
const parsed = enhancedInputSchemas.analyze_function.safeParse(input);
return parsed.success
? this.#call("analyze_function", parsed.data, signal)
? this.#analyzeFunction(parsed.data, signal)
: invalidInput(name, parsed.error);
}
case "trace_feature": {
@@ -96,6 +97,14 @@ export class EnhancedTools {
}
}
async #analyzeFunction(
input: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): EnhancedResult {
const result = await this.#call("analyze_function", input, signal);
return result.ok ? parseFunctionDossier(result.value) : result;
}
async #swiftClasses(pattern: string, signal?: AbortSignal): EnhancedResult {
const procedures = await this.#allProcedures(signal);
return procedures.ok
+80
View File
@@ -0,0 +1,80 @@
import {
createEvidenceBundle,
evidenceBundleSchema,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import { parseEvidence, type Evidence } from "../domain/evidence.js";
export interface EvidenceLedgerLimits {
readonly maxRecords: number;
}
/** Bounded, session-owned set of immutable evidence records. */
export class EvidenceLedger {
readonly #records = new Map<string, Evidence>();
constructor(private readonly limits: EvidenceLedgerLimits) {
if (!Number.isSafeInteger(limits.maxRecords) || limits.maxRecords < 1)
throw new RangeError("maxRecords must be a positive safe integer");
}
/** Record evidence idempotently; conflicting content is rejected. */
record(input: Evidence): "added" | "duplicate" {
const evidence = parseEvidence(input);
const existing = this.#records.get(evidence.evidence_id);
if (existing !== undefined) {
if (!recordsAgree(existing, evidence))
throw new Error(`Conflicting evidence record: ${evidence.evidence_id}`);
return "duplicate";
}
if (this.#records.size >= this.limits.maxRecords)
throw new RangeError("Evidence ledger record limit exceeded");
this.#records.set(evidence.evidence_id, evidence);
return "added";
}
/** Validate an entire bundle before atomically merging its records. */
import(input: unknown): number {
const bundle = evidenceBundleSchema.parse(input);
const pending = new Map(this.#records);
for (const unparsed of bundle.records) {
const evidence = parseEvidence(unparsed);
const existing = pending.get(evidence.evidence_id);
if (existing !== undefined && !recordsAgree(existing, evidence))
throw new Error(`Conflicting evidence record: ${evidence.evidence_id}`);
pending.set(evidence.evidence_id, evidence);
}
if (pending.size > this.limits.maxRecords)
throw new RangeError("Evidence ledger record limit exceeded");
const added = pending.size - this.#records.size;
this.#records.clear();
for (const [id, evidence] of pending) this.#records.set(id, evidence);
return added;
}
/** Export records in deterministic, semantically irrelevant ID order. */
export(): EvidenceBundle {
return createEvidenceBundle([...this.#records.values()]);
}
/** Clear records when the owning session closes. */
clear(): void {
this.#records.clear();
}
}
const recordsAgree = (left: Evidence, right: Evidence): boolean =>
JSON.stringify(withoutLocalPath(left)) ===
JSON.stringify(withoutLocalPath(right));
const withoutLocalPath = (evidence: Evidence): Evidence => ({
...evidence,
subject:
evidence.subject === null
? null
: {
...evidence.subject,
name: "<non-identity-name>",
local_path: "<non-identity-local-path>",
},
});
+110
View File
@@ -0,0 +1,110 @@
import { createServer, type Server } from "node:http";
import { WebSocketServer, type WebSocket } from "ws";
import type {
ProcessScenario,
ProtocolEvent,
} from "../domain/processCapture.js";
/** Owned loopback replay endpoints and their bounded protocol observations. */
export interface LoopbackReplay {
readonly httpUrl: string;
readonly websocketUrl: string;
readonly events: ProtocolEvent[];
close(): Promise<void>;
}
const closeServer = async (server: Server): Promise<void> =>
new Promise((resolveClose, rejectClose) => {
server.close((error) =>
error === undefined ? resolveClose() : rejectClose(error),
);
});
/** Start bounded HTTP and WebSocket replay endpoints bound only to IPv4 loopback. */
export const startLoopbackReplay = async (
scenario: ProcessScenario,
): Promise<LoopbackReplay> => {
const events: ProtocolEvent[] = [];
const record = (event: Omit<ProtocolEvent, "sequence">): void => {
if (events.length < 10_000)
events.push({ sequence: events.length, ...event });
};
const server = createServer((request, response) => {
const method = request.method ?? "GET";
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
record({ protocol: "http", direction: "request", method, path, data: "" });
const route = scenario.replay.http.find(
(candidate) => candidate.method === method && candidate.path === path,
);
response.statusCode = route?.status ?? 404;
const body = route?.body ?? "";
response.end(body);
record({
protocol: "http",
direction: "response",
method,
path,
data: body,
});
});
const websocket = new WebSocketServer({
noServer: true,
maxPayload: 1_000_000,
clientTracking: true,
});
server.on("upgrade", (request, socket, head) => {
if (new URL(request.url ?? "/", "http://127.0.0.1").pathname !== "/ws") {
socket.destroy();
return;
}
websocket.handleUpgrade(request, socket, head, (client) =>
websocket.emit("connection", client, request),
);
});
websocket.on("connection", (client: WebSocket) => {
client.on("error", () => undefined);
client.on("message", (value) =>
record({
protocol: "websocket",
direction: "received",
method: null,
path: "/ws",
data: value.toString(),
}),
);
for (const message of scenario.replay.websocket_messages) {
client.send(message);
record({
protocol: "websocket",
direction: "sent",
method: null,
path: "/ws",
data: message,
});
}
});
await new Promise<void>((resolveListen, rejectListen) => {
server.once("error", rejectListen);
server.listen(0, "127.0.0.1", () => {
server.off("error", rejectListen);
resolveListen();
});
});
const address = server.address();
if (address === null || typeof address === "string") {
await closeServer(server);
throw new Error("loopback replay did not acquire a TCP port");
}
return {
httpUrl: `http://127.0.0.1:${String(address.port)}`,
websocketUrl: `ws://127.0.0.1:${String(address.port)}/ws`,
events,
async close() {
for (const client of websocket.clients) client.terminate();
await new Promise<void>((resolveClose) =>
websocket.close(() => resolveClose()),
);
await closeServer(server);
},
};
};
+511
View File
@@ -0,0 +1,511 @@
import { createHash } from "node:crypto";
import {
lstat,
mkdtemp,
readdir,
readFile,
readlink,
realpath,
rm,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { spawn, type IPty } from "node-pty";
import type {
FileState,
ProcessCapture,
ProcessExecutionPolicy,
ProcessSample,
ProcessScenario,
TerminalFrame,
} from "../domain/processCapture.js";
import { authorizeProcessScenario } from "../domain/processCapture.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisError } from "../domain/errors.js";
import { startLoopbackReplay, type LoopbackReplay } from "./LoopbackReplay.js";
const execFileAsync = promisify(execFile);
const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
const assertRealPathAuthority = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
): Promise<void> => {
const executable = await realpath(scenario.executable);
const executableRoots = await Promise.all(
policy.executableRoots.map((root) => realpath(root)),
);
if (!executableRoots.some((root) => isWithin(executable, root)))
throw new ProcessCaptureError(
"resolved executable is outside approved roots",
);
const workingDirectory = await realpath(scenario.working_directory);
const workingRoots = await Promise.all(
policy.workingRoots.map((root) => realpath(root)),
);
if (!workingRoots.some((root) => isWithin(workingDirectory, root)))
throw new ProcessCaptureError(
"resolved working directory is outside approved roots",
);
for (const root of scenario.filesystem_roots) {
const resolvedRoot = await realpath(root);
if (!workingRoots.some((approved) => isWithin(resolvedRoot, approved)))
throw new ProcessCaptureError(
"resolved filesystem root is outside approved roots",
);
}
};
/** Expected refusal or runtime failure from the process capture adapter. */
export class ProcessCaptureError extends AnalysisError {
readonly _tag = "ProcessCaptureError";
}
/** Runtime availability of the native PTY adapter on this host. */
export type ProcessCaptureCapability =
| { readonly available: true; readonly backend: "node-pty" }
| {
readonly available: false;
readonly backend: "node-pty";
readonly reason: string;
};
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
export const probeProcessCaptureCapability =
async (): Promise<ProcessCaptureCapability> => {
try {
const terminal = spawn(
process.platform === "win32" ? "cmd.exe" : "/bin/sh",
process.platform === "win32" ? ["/c", "exit", "0"] : ["-c", "exit 0"],
{
cwd: tmpdir(),
env: { HOME: tmpdir(), TERM: "xterm-256color" },
cols: 80,
rows: 24,
name: "xterm-256color",
},
);
await new Promise<void>((resolveExit) =>
terminal.onExit(() => resolveExit()),
);
return { available: true, backend: "node-pty" };
} catch {
return {
available: false,
backend: "node-pty",
reason: "the native PTY backend could not start a probe process",
};
}
};
interface SnapshotResult {
readonly files: readonly FileState[];
readonly truncated: boolean;
}
const hashFile = async (
path: string,
maxBytes: number,
): Promise<string | null> => {
const value = await readFile(path);
if (value.byteLength > maxBytes) return null;
return createHash("sha256").update(value).digest("hex");
};
const snapshotRoots = async (
scenario: ProcessScenario,
): Promise<SnapshotResult> => {
const entries: FileState[] = [];
let remainingBytes = scenario.limits.file_bytes;
let truncated = false;
const visit = async (root: string, path: string): Promise<void> => {
if (entries.length >= scenario.limits.files) {
truncated = true;
return;
}
let stats;
try {
stats = await lstat(path);
} catch (error: unknown) {
if (error instanceof Error && "code" in error && error.code === "ENOENT")
return;
throw error;
}
const relativePath = relative(root, path) || ".";
if (stats.isSymbolicLink()) {
entries.push({
path: `${root}:${relativePath}`,
type: "symlink",
mode: stats.mode,
size: stats.size,
sha256: null,
symlink_target: await readlink(path),
});
return;
}
if (stats.isFile()) {
const allowedBytes = Math.max(
0,
Math.min(remainingBytes, scenario.limits.file_bytes),
);
const sha256 =
allowedBytes >= stats.size ? await hashFile(path, allowedBytes) : null;
remainingBytes -= sha256 === null ? 0 : stats.size;
if (sha256 === null) truncated = true;
entries.push({
path: `${root}:${relativePath}`,
type: "file",
mode: stats.mode,
size: stats.size,
sha256,
symlink_target: null,
});
return;
}
const type = stats.isDirectory() ? "directory" : "other";
entries.push({
path: `${root}:${relativePath}`,
type,
mode: stats.mode,
size: stats.size,
sha256: null,
symlink_target: null,
});
if (type !== "directory") return;
for (const child of (await readdir(path)).sort())
await visit(root, join(path, child));
};
for (const root of scenario.filesystem_roots) await visit(root, root);
return { files: entries, truncated };
};
const sampleProcesses = async (
rootPid: number,
elapsedMs: number,
limit: number,
): Promise<readonly ProcessSample[]> => {
if (process.platform === "win32") return [];
const { stdout } = await execFileAsync("ps", ["-axo", "pid=,ppid=,command="]);
const rows = stdout
.split("\n")
.map((line) => /\s*(\d+)\s+(\d+)\s+(.*)/.exec(line))
.filter((match): match is RegExpExecArray => match !== null)
.map((match) => ({
pid: Number(match[1]),
parent_pid: Number(match[2]),
command: match[3] ?? "",
}));
const owned = new Set([rootPid]);
let changed = true;
while (changed) {
changed = false;
for (const row of rows) {
if (owned.has(row.parent_pid) && !owned.has(row.pid)) {
owned.add(row.pid);
changed = true;
}
}
}
return rows
.filter((row) => owned.has(row.pid))
.slice(0, limit)
.map((row) => ({ at_ms: elapsedMs, ...row }));
};
const makeEnvironment = (
scenario: ProcessScenario,
home: string,
replay: LoopbackReplay,
): Record<string, string> => {
const environment: Record<string, string> = {
HOME: home,
TERM: "xterm-256color",
...scenario.environment,
};
for (const name of scenario.inherit_environment) {
const value = process.env[name];
if (value !== undefined) environment[name] = value;
}
environment.REA_REPLAY_HTTP_URL = replay.httpUrl;
environment.REA_REPLAY_WEBSOCKET_URL = replay.websocketUrl;
return environment;
};
const normalizeTerminalData = (
value: string,
scenario: ProcessScenario,
temporaryRoot: string,
pid: number,
): string => {
let normalized = value;
for (const alias of scenario.secret_aliases) {
const secret = scenario.environment[alias];
if (secret !== undefined && secret.length > 0)
normalized = normalized.replaceAll(secret, "<redacted>");
}
if (scenario.normalization.paths)
normalized = normalized.replaceAll(temporaryRoot, "<temporary-root>");
if (scenario.normalization.pids)
normalized = normalized.replaceAll(String(pid), "<pid>");
if (scenario.normalization.ports)
normalized = normalized.replaceAll(/(?<=[:=])\d{2,5}\b/g, "<port>");
for (const pattern of scenario.normalization.patterns)
normalized = normalized.replaceAll(pattern.pattern, pattern.replacement);
return normalized;
};
const scheduleScenarioEvents = (
scenario: ProcessScenario,
getTerminal: () => IPty | undefined,
timers: Set<NodeJS.Timeout>,
): void => {
for (const event of scenario.events) {
const timer = setTimeout(() => {
const terminal = getTerminal();
if (event.type === "input") terminal?.write(event.data);
else if (event.type === "resize")
terminal?.resize(event.columns, event.rows);
else terminal?.kill(event.signal);
}, event.at_ms);
timers.add(timer);
}
};
interface TerminalExitOptions {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly started: number;
readonly lastOutput: () => number;
readonly signal: AbortSignal | undefined;
readonly timers: Set<NodeJS.Timeout>;
}
interface CaptureResultOptions {
readonly frames: readonly TerminalFrame[];
readonly exit: { readonly exitCode: number; readonly signal?: number };
readonly samples: readonly ProcessSample[];
readonly replay: LoopbackReplay;
readonly before: SnapshotResult;
readonly after: SnapshotResult;
readonly truncated: boolean;
readonly scenario: ProcessScenario;
readonly rootPid: number;
}
const normalizeSamples = (
samples: readonly ProcessSample[],
scenario: ProcessScenario,
rootPid: number,
): readonly ProcessSample[] => {
const identifiers = [
rootPid,
...samples.flatMap((sample) => [sample.pid, sample.parent_pid]),
];
const mapping = new Map<number, number>();
for (const identifier of identifiers)
if (identifier > 0 && !mapping.has(identifier))
mapping.set(identifier, mapping.size + 1);
return samples.map((sample) => ({
at_ms:
Math.floor(sample.at_ms / scenario.normalization.time_bucket_ms) *
scenario.normalization.time_bucket_ms,
pid: mapping.get(sample.pid) ?? 1,
parent_pid: mapping.get(sample.parent_pid) ?? 0,
command: normalizeTerminalData(
sample.command,
scenario,
"<no-temporary-root>",
rootPid,
),
}));
};
const redactProtocolEvents = (
events: readonly ProcessCapture["protocol_events"][number][],
scenario: ProcessScenario,
): readonly ProcessCapture["protocol_events"][number][] =>
events.map((event) => ({
...event,
data: normalizeTerminalData(
event.data,
scenario,
"<no-temporary-root>",
-1,
),
}));
const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
schema_version: 1,
frames: options.frames,
exit: {
code: options.exit.exitCode < 0 ? null : options.exit.exitCode,
signal: options.exit.signal ?? null,
},
process_samples: normalizeSamples(
options.samples,
options.scenario,
options.rootPid,
),
protocol_events: redactProtocolEvents(
options.replay.events,
options.scenario,
),
files_before: options.before.files,
files_after: options.after.files,
truncated: options.truncated,
limitations: [
"Process trees are sampled and may omit short-lived descendants.",
"Filesystem observations are before/after snapshots, not syscall traces.",
"The harness does not enforce external network isolation.",
],
});
const awaitTerminalExit = async ({
terminal,
scenario,
started,
lastOutput,
signal,
timers,
}: TerminalExitOptions): Promise<{ exitCode: number; signal?: number }> =>
new Promise((resolveExit) => {
terminal.onExit(resolveExit);
const timeout = setInterval(() => {
if (
Date.now() - started >= scenario.timeout_ms ||
Date.now() - lastOutput() >= scenario.idle_timeout_ms ||
signal?.aborted === true
) {
terminal.kill("SIGKILL");
}
}, 20);
timers.add(timeout);
});
/** Execute one authorized scenario and return bounded observations. */
const runProcessScenario = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
signal?: AbortSignal,
): Promise<ProcessCapture> => {
const decision = authorizeProcessScenario(scenario, policy);
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
await assertRealPathAuthority(scenario, policy);
if (signal?.aborted === true)
throw new ProcessCaptureError("process capture was cancelled");
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
const home = join(temporaryRoot, "home");
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
const before = await snapshotRoots(scenario);
const frames: TerminalFrame[] = [];
const samples: ProcessSample[] = [];
let outputBytes = 0;
let truncated = before.truncated;
let terminal: IPty | undefined;
let replay: LoopbackReplay | undefined;
const started = Date.now();
let lastOutput = started;
const timers = new Set<NodeJS.Timeout>();
try {
replay = await startLoopbackReplay(scenario);
terminal = spawn(scenario.executable, [...scenario.arguments], {
cwd: scenario.working_directory,
env: makeEnvironment(scenario, home, replay),
cols: 80,
rows: 24,
name: "xterm-256color",
});
terminal.onData((data) => {
lastOutput = Date.now();
const bytes = Buffer.byteLength(data);
if (
frames.length >= scenario.limits.frames ||
outputBytes + bytes > scenario.limits.output_bytes
) {
truncated = true;
return;
}
outputBytes += bytes;
frames.push({
sequence: frames.length,
at_ms:
Math.floor(
(Date.now() - started) / scenario.normalization.time_bucket_ms,
) * scenario.normalization.time_bucket_ms,
data: normalizeTerminalData(
data,
scenario,
temporaryRoot,
terminal?.pid ?? -1,
),
});
});
scheduleScenarioEvents(scenario, () => terminal, timers);
const sampler = setInterval(() => {
void sampleProcesses(
terminal?.pid ?? -1,
Date.now() - started,
scenario.limits.processes - samples.length,
)
.then((values) => samples.push(...values))
.catch(() => undefined);
}, 50);
timers.add(sampler);
const exit = await awaitTerminalExit({
terminal,
scenario,
started,
lastOutput: () => lastOutput,
signal,
timers,
});
await new Promise((resolveSettle) =>
setTimeout(resolveSettle, scenario.settle_ms),
);
const after = await snapshotRoots(scenario);
truncated ||=
after.truncated || samples.length >= scenario.limits.processes;
return buildCaptureResult({
frames,
exit,
samples,
replay,
before,
after,
truncated,
scenario,
rootPid: terminal.pid,
});
} catch (cause: unknown) {
terminal?.kill("SIGKILL");
throw new ProcessCaptureError("process capture failed", { cause });
} finally {
for (const timer of timers) clearTimeout(timer);
await replay?.close();
await rm(temporaryRoot, { recursive: true, force: true });
}
};
/** Execute one scenario through a typed expected-failure channel. */
export const captureProcessScenario = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
signal?: AbortSignal,
): Promise<Result<ProcessCapture, ProcessCaptureError>> => {
try {
return ok(await runProcessScenario(scenario, policy, signal));
} catch (cause: unknown) {
return err(
cause instanceof ProcessCaptureError
? cause
: new ProcessCaptureError("process capture failed", { cause }),
);
}
};
+48
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { ConfigurationError } from "./domain/errors.js";
import { err, ok, type Result } from "./domain/result.js";
import type { LogLevel } from "./logger.js";
import type { ProcessExecutionPolicy } from "./domain/processCapture.js";
const DEFAULT_HOPPER_LAUNCHER_PATH =
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
@@ -13,6 +14,7 @@ export interface AppConfig {
readonly hopperTargetKind: "executable" | "database";
readonly hopperLoaderArgs: readonly string[];
readonly logLevel: LogLevel;
readonly processExecutionPolicy: ProcessExecutionPolicy;
}
const environmentSchema = z.object({
@@ -23,8 +25,33 @@ const environmentSchema = z.object({
REA_LOG_LEVEL: z
.enum(["trace", "debug", "info", "warn", "error", "fatal", "silent"])
.default("info"),
REA_PROCESS_CAPTURE_ENABLED: z.enum(["true", "false"]).default("false"),
REA_PROCESS_EXECUTABLE_ROOTS_JSON: z.string().default("[]"),
REA_PROCESS_WORKING_ROOTS_JSON: z.string().default("[]"),
REA_PROCESS_ALLOWED_ENV_JSON: z.string().default("[]"),
});
const parseStringArray = (
encoded: string,
name: string,
): Result<readonly string[], ConfigurationError> => {
try {
const parsed = z
.array(z.string().min(1))
.max(128)
.safeParse(JSON.parse(encoded));
return parsed.success
? ok(parsed.data)
: err(
new ConfigurationError(`${name} must encode an array of strings`, {
cause: parsed.error,
}),
);
} catch (cause: unknown) {
return err(new ConfigurationError(`${name} must be valid JSON`, { cause }));
}
};
/**
* Parse Hopper launcher configuration once at the composition root.
* Explicit loader arguments override REA's header-derived defaults for a
@@ -64,6 +91,21 @@ export const parseConfig = (
),
);
}
const executableRoots = parseStringArray(
parsedEnvironment.data.REA_PROCESS_EXECUTABLE_ROOTS_JSON,
"REA_PROCESS_EXECUTABLE_ROOTS_JSON",
);
if (!executableRoots.ok) return executableRoots;
const workingRoots = parseStringArray(
parsedEnvironment.data.REA_PROCESS_WORKING_ROOTS_JSON,
"REA_PROCESS_WORKING_ROOTS_JSON",
);
if (!workingRoots.ok) return workingRoots;
const allowedEnvironment = parseStringArray(
parsedEnvironment.data.REA_PROCESS_ALLOWED_ENV_JSON,
"REA_PROCESS_ALLOWED_ENV_JSON",
);
if (!allowedEnvironment.ok) return allowedEnvironment;
return ok({
hopperLauncherPath:
parsedEnvironment.data.HOPPER_LAUNCHER_PATH ??
@@ -72,5 +114,11 @@ export const parseConfig = (
hopperTargetKind: parsedEnvironment.data.HOPPER_TARGET_KIND,
hopperLoaderArgs: parsedArgs.data,
logLevel: parsedEnvironment.data.REA_LOG_LEVEL,
processExecutionPolicy: {
enabled: parsedEnvironment.data.REA_PROCESS_CAPTURE_ENABLED === "true",
executableRoots: executableRoots.value,
workingRoots: workingRoots.value,
allowedEnvironment: allowedEnvironment.value,
},
});
};
+23
View File
@@ -28,6 +28,29 @@ export const enhancedInputSchemas = {
limit: z.number().int().min(1).max(500).default(100),
max_pseudocode_chars: z.number().int().min(1).max(100_000).default(20_000),
max_instructions: z.number().int().min(1).max(5_000).default(500),
pseudocode_offset: z.number().int().min(0).default(0),
assembly_offset: z.number().int().min(0).default(0),
collection_offset: z
.object({
comments: z.number().int().min(0).default(0),
callers: z.number().int().min(0).default(0),
callees: z.number().int().min(0).default(0),
incoming_references: z.number().int().min(0).default(0),
outgoing_references: z.number().int().min(0).default(0),
referenced_strings: z.number().int().min(0).default(0),
referenced_names: z.number().int().min(0).default(0),
basic_blocks: z.number().int().min(0).default(0),
})
.default({
comments: 0,
callers: 0,
callees: 0,
incoming_references: 0,
outgoing_references: 0,
referenced_strings: 0,
referenced_names: 0,
basic_blocks: 0,
}),
}),
trace_feature: z.object({
query: z.string().min(1),
+32 -1
View File
@@ -1,4 +1,9 @@
import { z } from "zod";
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
import {
processCaptureSchema,
processScenarioSchema,
} from "../domain/processCapture.js";
import { enhancedInputSchemas } from "./enhancedInputs.js";
import {
@@ -44,6 +49,7 @@ export interface ToolContract {
const annotations = (name: string, kind: ToolKind): ToolAnnotations => ({
readOnlyHint:
kind === "enhanced" ||
name === "export_evidence_bundle" ||
(!name.startsWith("set_") &&
name !== "unset_bookmark" &&
name !== "goto_address" &&
@@ -354,11 +360,36 @@ export const SESSION_TOOL_CONTRACTS = [
"Report whether a target is open and, when open, its canonical path, format, and kind. Use before analysis calls or target switches; this performs no analysis.",
z.object({}),
),
session(
"export_evidence_bundle",
"Return the session's deterministic Evidence v2 bundle without clearing it. Records are sorted by evidence ID, and array order carries no investigative meaning.",
z.object({}),
),
session(
"import_evidence_bundle",
"Validate and atomically merge a local Evidence v2 bundle supplied as data. Semantic IDs are recomputed; tampering, unsupported versions, conflicts, and ledger overflow reject the entire import.",
z.object({ bundle: evidenceBundleSchema }),
),
session(
"capture_process_scenario",
"Run one bounded process under a PTY using operator-approved executable and working roots. Requires approved: true on every call. Captures normalized terminal frames, sampled descendants, filesystem snapshots, and loopback HTTP/WebSocket replay. This launches a process and is disabled unless operator policy enables it; it is not a security sandbox.",
processScenarioSchema,
),
session(
"compare_process_captures",
"Compare two bounded process captures across terminal, exit, sampled process, filesystem, HTTP, and WebSocket evidence. Missing or truncated observations are never treated as equivalent.",
z.object({
left_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
left: processCaptureSchema,
right_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
right: processCaptureSchema,
}),
),
] as const satisfies readonly ToolContract[];
/**
* Complete ordered public inventory used by registration and verification.
* Keep this collection at 46 tools unless a deliberate contract change updates
* Keep this collection at 50 tools unless a deliberate contract change updates
* snapshots, package verification, and real-Hopper verification together.
*/
export const TOOL_CONTRACTS = [
+60 -24
View File
@@ -1,24 +1,19 @@
import { z } from "zod";
import { evidenceSchema } from "../domain/evidence.js";
import { processCaptureSchema } from "../domain/processCapture.js";
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
const evidenceMetadata = {
schema_version: z.literal(1),
artifact: z
.object({
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
format: z.enum(["hopper", "mach-o", "elf", "pe"]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
})
.nullable(),
provider: z.object({ id: z.literal("hopper"), version: z.null() }),
operation: z.string().min(1),
parameters: z.record(z.string(), z.json()),
confidence: z.literal("observed"),
limitations: z.array(z.string()),
};
const resultOf = (schema: z.ZodType) =>
z.object({ ...evidenceMetadata, result: schema });
evidenceSchema.omit({ result: true }).extend({ result: schema });
const lifecycleResultOf = (schema: z.ZodType) => z.object({ result: schema });
const comparisonStatus = z.enum([
"unchanged",
"added",
"removed",
"changed",
"truncated",
"unknown",
]);
const nullableText = z.string().nullable();
const addressList = z.array(z.string());
const addressedEntry = z.object({ address: z.string(), name: z.string() });
@@ -92,7 +87,18 @@ const graphNode = z.union([
z.object({ address: z.string(), calls: z.array(z.string()) }),
z.object({ address: z.string(), error: z.string() }),
]);
const unavailableOrBoundedStrings = z.union([unavailable, bounded(z.string())]);
const referenceEdge = z.object({
source_address: z.string(),
target_address: z.string(),
source_procedure: procedureIdentity.nullable(),
target_procedure: procedureIdentity.nullable(),
kind: unavailable,
});
const referencedValue = z.object({
address: z.string(),
value: z.string(),
source_address: z.string(),
});
const functionDossierOutput = resultOf(
z.object({
procedure: z.object({
@@ -116,18 +122,23 @@ const functionDossierOutput = resultOf(
text: z.string(),
}),
),
callers: bounded(z.string()),
callees: bounded(z.string()),
incoming_references: bounded(z.string()),
referenced_strings: unavailableOrBoundedStrings,
referenced_names: unavailableOrBoundedStrings,
callers: bounded(procedureIdentity),
callees: bounded(procedureIdentity),
incoming_references: bounded(referenceEdge),
outgoing_references: bounded(referenceEdge),
referenced_strings: bounded(referencedValue),
referenced_names: bounded(referencedValue),
basic_blocks: bounded(
z.object({
start: z.string(),
end: z.string(),
successors: z.union([unavailable, z.array(z.string())]),
successors: z.array(z.string()),
}),
),
instruction_scan: z.object({
scanned: z.number().int().min(0),
truncated: z.boolean(),
}),
}),
);
@@ -284,4 +295,29 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
}),
]),
),
export_evidence_bundle: lifecycleResultOf(evidenceBundleSchema),
import_evidence_bundle: lifecycleResultOf(
z.object({
imported: z.number().int().min(0),
total: z.number().int().min(0),
}),
),
capture_process_scenario: lifecycleResultOf(
evidenceSchema
.omit({ result: true })
.extend({ result: processCaptureSchema }),
),
compare_process_captures: lifecycleResultOf(
evidenceSchema.omit({ result: true }).extend({
result: z.object({
status: comparisonStatus,
terminal: comparisonStatus,
exit: comparisonStatus,
filesystem: comparisonStatus,
protocol: comparisonStatus,
process: comparisonStatus,
limitations: z.array(z.string()),
}),
}),
),
};
+6 -1
View File
@@ -8,7 +8,12 @@ export abstract class HopperError extends AnalysisError {}
/** Provider-neutral invalid analysis input or output at an application boundary. */
export class AnalysisProtocolError extends AnalysisError {
readonly _tag = "HopperProtocolError";
readonly _tag = "AnalysisProtocolError";
}
/** An evidence bundle or bounded session ledger rejected caller-controlled data. */
export class EvidenceLedgerError extends AnalysisError {
readonly _tag = "EvidenceLedgerError";
}
/** Hopper did not respond within the configured operation deadline. */
+163 -27
View File
@@ -1,62 +1,198 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import type { BinaryTarget } from "./binaryTarget.js";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
const artifactEvidenceSchema = z.object({
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const providerSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.object({
name: z.string().min(1),
digest: z.object({ sha256: digestSchema }),
format: z.enum(["hopper", "mach-o", "elf", "pe"]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
local_path: z.string(),
});
const locationSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("address"), address: z.string().min(1) }),
z.object({
kind: z.literal("address-range"),
start: z.string().min(1),
end: z.string().min(1),
}),
z.object({ kind: z.literal("artifact-path"), path: z.string().min(1) }),
]);
const evidenceAuthoritySchema = z.enum([
"shipped-artifact",
"controlled-replay",
"historical-reference",
"external-service",
"analyst-inference",
]);
const executionEnvironmentSchema = z.object({
id: z.string().min(1),
platform: z.string().min(1),
architecture: z.string().min(1),
isolation: z.enum(["none", "process", "container", "virtual-machine"]),
});
/** Strict JSON representation of one successful public analysis observation. */
/** Strict, provider-neutral record for one successful public observation. */
export const evidenceSchema = z.object({
schema_version: z.literal(1),
artifact: artifactEvidenceSchema.nullable(),
provider: z.object({ id: z.literal("hopper"), version: z.null() }),
schema_version: z.literal(2),
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
subject: subjectSchema.nullable(),
provider: providerSchema,
predicate_type: z.string().min(1),
operation: z.string().min(1),
parameters: z.record(z.string(), jsonValueSchema),
result: jsonValueSchema,
confidence: z.literal("observed"),
raw_payload_sha256: digestSchema.nullable(),
confidence: z.enum(["observed", "derived", "inferred"]),
authority: evidenceAuthoritySchema,
environment: executionEnvironmentSchema.nullable(),
limitations: z.array(z.string()),
locations: z.array(locationSchema),
evidence_links: z.array(z.string().regex(/^ev_[a-f0-9]{64}$/u)),
});
export type Evidence = z.infer<typeof evidenceSchema>;
type EvidenceLocation = z.infer<typeof locationSchema>;
type EvidenceAuthority = z.infer<typeof evidenceAuthoritySchema>;
type ExecutionEnvironment = z.infer<typeof executionEnvironmentSchema>;
export interface EvidenceProvider {
readonly id: string;
readonly name: string;
readonly version: string | null;
}
export interface EvidenceObservation {
readonly predicateType?: string;
readonly operation: string;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly result: JsonValue;
readonly redactedRawPayload?: JsonValue;
readonly confidence?: "observed" | "derived" | "inferred";
readonly authority?: EvidenceAuthority;
readonly environment?: ExecutionEnvironment | null;
readonly limitations?: readonly string[];
readonly locations?: readonly EvidenceLocation[];
readonly evidenceLinks?: readonly string[];
}
/** Build deterministic evidence without claiming unavailable provider metadata. */
const sha256 = (value: string): string =>
createHash("sha256").update(value).digest("hex");
/** Serialize JSON according to RFC 8785 JSON Canonicalization Scheme. */
const canonicalJson = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("RFC 8785 canonicalization rejected a JSON value");
return serialized;
};
const semanticProjection = (
evidence: Omit<Evidence, "evidence_id">,
): JsonValue => ({
schema_version: evidence.schema_version,
subject:
evidence.subject === null
? null
: {
digest: evidence.subject.digest,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
provider: evidence.provider,
predicate_type: evidence.predicate_type,
operation: evidence.operation,
parameters: evidence.parameters,
result: evidence.result,
confidence: evidence.confidence,
authority: evidence.authority,
environment: evidence.environment,
limitations: evidence.limitations,
locations: evidence.locations,
evidence_links: evidence.evidence_links,
});
/** Recompute the semantic identifier, excluding paths and raw payload bytes. */
const computeEvidenceId = (evidence: Omit<Evidence, "evidence_id">): string =>
`ev_${sha256(canonicalJson(semanticProjection(evidence)))}`;
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
export const parseEvidence = (input: unknown): Evidence => {
const evidence = evidenceSchema.parse(input);
const { evidence_id: evidenceId, ...withoutId } = evidence;
if (computeEvidenceId(withoutId) !== evidenceId)
throw new TypeError(
"Evidence semantic identifier does not match its record",
);
return evidence;
};
/** Build deterministic Evidence v2 from an immutable artifact subject. */
export const createEvidence = (
target: BinaryTarget | undefined,
provider: EvidenceProvider,
observation: EvidenceObservation,
): Evidence =>
evidenceSchema.parse({
schema_version: 1,
artifact:
target === undefined
): Evidence => {
const subject =
target === undefined
? null
: {
name: target.path.split("/").at(-1) ?? target.path,
digest: { sha256: target.sha256 },
format: target.format,
architecture: target.architecture ?? null,
local_path: target.path,
};
const semantic = {
schema_version: 2,
subject:
subject === null
? null
: {
path: target.path,
sha256: target.sha256,
format: target.format,
architecture: target.architecture ?? null,
digest: subject.digest,
format: subject.format,
architecture: subject.architecture,
},
provider: { id: "hopper", version: null },
provider: {
id: provider.id,
name: provider.name,
version: provider.version,
},
predicate_type: observation.predicateType ?? "rea.analysis/v2",
operation: observation.operation,
parameters: observation.parameters,
result: observation.result,
confidence: "observed",
limitations:
target === undefined
? [
"Artifact identity is unavailable for this fixed-target adapter.",
...(observation.limitations ?? []),
]
: [...(observation.limitations ?? [])],
confidence: observation.confidence ?? "observed",
authority: observation.authority ?? "shipped-artifact",
environment: observation.environment ?? null,
limitations: [
...(target === undefined
? ["Artifact identity is unavailable for this observation."]
: []),
...(observation.limitations ?? []),
],
locations: [...(observation.locations ?? [])],
evidence_links: [...(observation.evidenceLinks ?? [])],
} satisfies JsonValue;
return evidenceSchema.parse({
...semantic,
evidence_id: `ev_${sha256(canonicalJson(semantic))}`,
subject,
raw_payload_sha256:
observation.redactedRawPayload === undefined
? null
: sha256(canonicalJson(observation.redactedRawPayload)),
});
};
+20
View File
@@ -0,0 +1,20 @@
import { z } from "zod";
import { evidenceSchema, type Evidence } from "./evidence.js";
export const evidenceBundleSchema = z.object({
bundle_version: z.literal(1),
records: z.array(evidenceSchema),
});
export type EvidenceBundle = z.infer<typeof evidenceBundleSchema>;
/** Project records into a deterministic bundle whose order has no semantics. */
export const createEvidenceBundle = (
records: readonly Evidence[],
): EvidenceBundle => ({
bundle_version: 1,
records: [...records].sort((left, right) =>
left.evidence_id.localeCompare(right.evidence_id),
),
});
+151 -1
View File
@@ -1,7 +1,7 @@
import { z } from "zod";
import type { JsonValue } from "./jsonValue.js";
import { HopperProtocolError } from "./errors.js";
import { AnalysisProtocolError, HopperProtocolError } from "./errors.js";
import { err, ok, type Result } from "./result.js";
export interface AddressedName {
@@ -36,6 +36,156 @@ const addressedPageSchema = z.object({
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
});
const unavailableSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
const procedureIdentitySchema = z
.object({ address: z.string(), name: z.string() })
.strict();
const boundedSchema = <T extends z.ZodType>(item: T) =>
z
.object({
items: z.array(item),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
})
.strict()
.superRefine((value, context) => {
if (value.returned !== value.items.length) {
context.addIssue({
code: "custom",
message: "returned must equal the number of items",
path: ["returned"],
});
}
if (value.total !== null && value.total < value.returned) {
context.addIssue({
code: "custom",
message: "total cannot be smaller than returned",
path: ["total"],
});
}
if (value.next_offset !== null && !value.truncated) {
context.addIssue({
code: "custom",
message: "a continuation requires truncated output",
path: ["next_offset"],
});
}
});
const referenceEdgeSchema = z
.object({
source_address: z.string(),
target_address: z.string(),
source_procedure: procedureIdentitySchema.nullable(),
target_procedure: procedureIdentitySchema.nullable(),
kind: unavailableSchema,
})
.strict();
const functionDossierSchema = z
.object({
procedure: z
.object({
address: z.string(),
name: z.string(),
signature: z.string().nullable(),
locals: z.array(z.json()),
})
.strict(),
pseudocode: z
.object({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
})
.strict()
.superRefine((value, context) => {
if (value.returned_chars !== value.text.length) {
context.addIssue({
code: "custom",
message: "returned_chars must equal the text length",
path: ["returned_chars"],
});
}
if (value.total_chars < value.returned_chars) {
context.addIssue({
code: "custom",
message: "total_chars cannot be smaller than returned_chars",
path: ["total_chars"],
});
}
if (value.next_offset !== null && !value.truncated) {
context.addIssue({
code: "custom",
message: "a continuation requires truncated pseudocode",
path: ["next_offset"],
});
}
}),
assembly: boundedSchema(z.string()),
comments: boundedSchema(
z
.object({
address: z.string(),
kind: z.enum(["comment", "inline"]),
text: z.string(),
})
.strict(),
),
callers: boundedSchema(procedureIdentitySchema),
callees: boundedSchema(procedureIdentitySchema),
incoming_references: boundedSchema(referenceEdgeSchema),
outgoing_references: boundedSchema(referenceEdgeSchema),
referenced_strings: boundedSchema(
z
.object({
address: z.string(),
value: z.string(),
source_address: z.string(),
})
.strict(),
),
referenced_names: boundedSchema(
z
.object({
address: z.string(),
value: z.string(),
source_address: z.string(),
})
.strict(),
),
basic_blocks: boundedSchema(
z
.object({
start: z.string(),
end: z.string(),
successors: z.array(z.string()),
})
.strict(),
),
instruction_scan: z
.object({ scanned: z.number().int().min(0), truncated: z.boolean() })
.strict(),
})
.strict();
/** Strictly parse a complete Hopper function dossier at the provider boundary. */
export const parseFunctionDossier = (
value: JsonValue,
): Result<JsonValue, AnalysisProtocolError> => {
const parsed = functionDossierSchema.safeParse(value);
return parsed.success
? ok(parsed.data)
: err(
new AnalysisProtocolError("Invalid analyze_function provider output", {
cause: parsed.error,
}),
);
};
/** Parse page entries and continuation metadata returned by list operations. */
export const parseAddressedPage = (
+396
View File
@@ -0,0 +1,396 @@
import { resolve } from "node:path";
import { z } from "zod";
const positiveBudget = z.number().int().positive();
const timedEventBase = { at_ms: z.number().int().nonnegative() };
/** Exact boundary schema for bounded dynamic process scenarios. */
export const processScenarioSchema = z
.object({
approved: z
.literal(true)
.describe(
"Explicit per-call acknowledgement that this operation launches the target",
),
executable: z.string().startsWith("/"),
arguments: z.array(z.string()).max(256).default([]),
working_directory: z.string().startsWith("/"),
environment: z.record(z.string(), z.string()).default({}),
inherit_environment: z.array(z.string()).max(64).default([]),
secret_aliases: z.array(z.string()).max(64).default([]),
filesystem_roots: z.array(z.string().startsWith("/")).max(16).default([]),
events: z
.array(
z.discriminatedUnion("type", [
z.object({
...timedEventBase,
type: z.literal("input"),
data: z.string(),
}),
z.object({
...timedEventBase,
type: z.literal("resize"),
columns: z.number().int().min(1).max(1_000),
rows: z.number().int().min(1).max(1_000),
}),
z.object({
...timedEventBase,
type: z.literal("signal"),
signal: z.enum(["SIGINT", "SIGTERM", "SIGKILL"]),
}),
]),
)
.max(1_000)
.default([]),
timeout_ms: positiveBudget.max(300_000).default(30_000),
idle_timeout_ms: positiveBudget.max(300_000).default(30_000),
settle_ms: z.number().int().nonnegative().max(10_000).default(100),
limits: z
.object({
output_bytes: positiveBudget.max(10_000_000).default(1_000_000),
frames: positiveBudget.max(100_000).default(10_000),
files: positiveBudget.max(100_000).default(10_000),
file_bytes: positiveBudget.max(100_000_000).default(10_000_000),
processes: positiveBudget.max(10_000).default(1_000),
})
.default({
output_bytes: 1_000_000,
frames: 10_000,
files: 10_000,
file_bytes: 10_000_000,
processes: 1_000,
}),
normalization: z
.object({
paths: z.boolean().default(true),
pids: z.boolean().default(true),
ports: z.boolean().default(true),
time_bucket_ms: positiveBudget.max(60_000).default(10),
patterns: z
.array(
z.object({
pattern: z.string().max(500),
replacement: z.string().max(100),
}),
)
.max(32)
.default([]),
})
.default({
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
}),
replay: z
.object({
http: z
.array(
z.object({
method: z.string().max(16),
path: z.string().startsWith("/"),
status: z.number().int().min(100).max(599),
body: z.string().max(1_000_000),
}),
)
.max(100)
.default([]),
websocket_messages: z
.array(z.string().max(1_000_000))
.max(100)
.default([]),
})
.default({ http: [], websocket_messages: [] }),
})
.strict()
.superRefine((scenario, context) => {
for (let index = 1; index < scenario.events.length; index += 1) {
if (scenario.events[index]!.at_ms < scenario.events[index - 1]!.at_ms) {
context.addIssue({
code: "custom",
message: "events must be ordered by at_ms",
path: ["events", index],
});
}
}
const secrets = new Set(scenario.secret_aliases);
for (const alias of secrets) {
if (!(alias in scenario.environment)) {
context.addIssue({
code: "custom",
message: "secret alias has no environment value",
path: ["secret_aliases"],
});
}
}
});
/** A parsed, bounded dynamic process observation scenario. */
export type ProcessScenario = z.infer<typeof processScenarioSchema>;
/** Parse untrusted process scenario input and apply safe default budgets. */
export const parseProcessScenario = (input: unknown): ProcessScenario =>
processScenarioSchema.parse(input);
/** Operator-owned policy for process capture. */
export interface ProcessExecutionPolicy {
readonly enabled: boolean;
readonly executableRoots: readonly string[];
readonly workingRoots: readonly string[];
readonly allowedEnvironment: readonly string[];
}
/** A safe, caller-visible process-policy decision. */
export type ProcessPolicyDecision =
| { readonly allowed: true }
| { readonly allowed: false; readonly reason: string };
const isWithin = (candidate: string, root: string): boolean =>
resolve(candidate) === resolve(root) ||
resolve(candidate).startsWith(
`${resolve(root)}${resolve(root).endsWith("/") ? "" : "/"}`,
);
/** Evaluate scenario authority before any process or filesystem side effect occurs. */
export const authorizeProcessScenario = (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
): ProcessPolicyDecision => {
if (!policy.enabled)
return { allowed: false, reason: "process capture is disabled" };
if (
!policy.executableRoots.some((root) => isWithin(scenario.executable, root))
) {
return { allowed: false, reason: "executable is outside approved roots" };
}
if (
!policy.workingRoots.some((root) =>
isWithin(scenario.working_directory, root),
)
) {
return {
allowed: false,
reason: "working directory is outside approved roots",
};
}
const requestedNames = [
...Object.keys(scenario.environment),
...scenario.inherit_environment,
];
if (
requestedNames.some((name) => !policy.allowedEnvironment.includes(name))
) {
return {
allowed: false,
reason: "scenario requests an environment variable not allowed by policy",
};
}
if (
scenario.filesystem_roots.some(
(path) => !policy.workingRoots.some((root) => isWithin(path, root)),
)
) {
return {
allowed: false,
reason: "filesystem root is outside approved roots",
};
}
return { allowed: true };
};
/** One bounded terminal observation. */
export interface TerminalFrame {
readonly sequence: number;
readonly at_ms: number;
readonly data: string;
}
/** One filesystem state used for before/after comparison. */
export interface FileState {
readonly path: string;
readonly type: "file" | "directory" | "symlink" | "other";
readonly mode: number;
readonly size: number;
readonly sha256: string | null;
readonly symlink_target: string | null;
}
/** A sampled owned-process observation; sampling cannot prove syscall completeness. */
export interface ProcessSample {
readonly at_ms: number;
readonly pid: number;
readonly parent_pid: number;
readonly command: string;
}
/** A bounded loopback replay observation. */
export interface ProtocolEvent {
readonly sequence: number;
readonly protocol: "http" | "websocket";
readonly direction: "request" | "response" | "received" | "sent";
readonly method: string | null;
readonly path: string | null;
readonly data: string;
}
/** A bounded process observation with explicit incompleteness metadata. */
export interface ProcessCapture {
readonly schema_version: 1;
readonly frames: readonly TerminalFrame[];
readonly exit: {
readonly code: number | null;
readonly signal: number | null;
};
readonly process_samples: readonly ProcessSample[];
readonly protocol_events: readonly ProtocolEvent[];
readonly files_before: readonly FileState[];
readonly files_after: readonly FileState[];
readonly truncated: boolean;
readonly limitations: readonly string[];
}
/** Exact serialized shape of a bounded process capture. */
export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
schema_version: z.literal(1),
frames: z.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
data: z.string(),
}),
),
exit: z.object({
code: z.number().int().nullable(),
signal: z.number().int().nullable(),
}),
process_samples: z.array(
z.object({
at_ms: z.number().int().nonnegative(),
pid: z.number().int().positive(),
parent_pid: z.number().int().nonnegative(),
command: z.string(),
}),
),
protocol_events: z.array(
z.object({
sequence: z.number().int().nonnegative(),
protocol: z.enum(["http", "websocket"]),
direction: z.enum(["request", "response", "received", "sent"]),
method: z.string().nullable(),
path: z.string().nullable(),
data: z.string(),
}),
),
files_before: z.array(
z.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
}),
),
files_after: z.array(
z.object({
path: z.string(),
type: z.enum(["file", "directory", "symlink", "other"]),
mode: z.number().int().nonnegative(),
size: z.number().int().nonnegative(),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
symlink_target: z.string().nullable(),
}),
),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
/** Comparison classification that never equates incomplete evidence. */
type ComparisonStatus =
| "unchanged"
| "added"
| "removed"
| "changed"
| "truncated"
| "unknown";
/** Pure normalized comparison between two captures. */
export interface ProcessCaptureComparison {
readonly status: ComparisonStatus;
readonly terminal: ComparisonStatus;
readonly exit: ComparisonStatus;
readonly filesystem: ComparisonStatus;
readonly protocol: ComparisonStatus;
readonly process: ComparisonStatus;
readonly limitations: readonly string[];
}
const stableFiles = (files: readonly FileState[]): string =>
JSON.stringify(
[...files].sort((left, right) => left.path.localeCompare(right.path)),
);
/** Compare bounded captures without claiming equality for incomplete observations. */
export const compareProcessCaptures = (
left: ProcessCapture,
right: ProcessCapture,
): ProcessCaptureComparison => {
if (left.truncated || right.truncated) {
return {
status: "truncated",
terminal: "truncated",
exit: "truncated",
filesystem: "truncated",
protocol: "truncated",
process: "truncated",
limitations: ["At least one capture is truncated."],
};
}
const terminal =
left.frames.map(({ data }) => data).join("") ===
right.frames.map(({ data }) => data).join("")
? "unchanged"
: "changed";
const exit =
JSON.stringify(left.exit) === JSON.stringify(right.exit)
? "unchanged"
: "changed";
const filesystem =
stableFiles(left.files_after) === stableFiles(right.files_after)
? "unchanged"
: "changed";
const protocol =
JSON.stringify(left.protocol_events) ===
JSON.stringify(right.protocol_events)
? "unchanged"
: "changed";
const process =
JSON.stringify(left.process_samples.map(({ command }) => command)) ===
JSON.stringify(right.process_samples.map(({ command }) => command))
? "unchanged"
: "changed";
const status =
terminal === "unchanged" &&
exit === "unchanged" &&
filesystem === "unchanged" &&
protocol === "unchanged" &&
process === "unchanged"
? "unchanged"
: "changed";
return {
status,
terminal,
exit,
filesystem,
protocol,
process,
limitations: [...left.limitations, ...right.limitations],
};
};
+2 -5
View File
@@ -13,13 +13,10 @@ import {
HopperTimeoutError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
import { silentLogger, type Logger } from "../logger.js";
import {
parseResponseLine,
responseResult,
type JsonValue,
} from "./protocol.js";
import { parseResponseLine, responseResult } from "./protocol.js";
const MAX_LINE_BYTES = 10 * 1024 * 1024;
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
+22 -2
View File
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
import type {
AnalysisClient,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import type { AppConfig } from "../config.js";
@@ -17,7 +18,7 @@ const IDENTITY: ProviderIdentity = {
version: null,
};
const CAPABILITIES = [
const OPERATIONS = [
"direct-analysis",
"decompilation",
"disassembly",
@@ -27,6 +28,25 @@ const CAPABILITIES = [
"analysis-metadata-mutation",
] as const;
const CAPABILITIES: readonly CapabilityDescriptor[] = OPERATIONS.map(
(operation) => ({
operation,
version: 1,
available: true,
pagination: "none",
exhaustive: false,
effects: {
mutatesArtifact: operation === "analysis-metadata-mutation",
launchesProcess: true,
mayShowUi: true,
mayAccessNetwork: false,
mayWriteFilesystem: operation === "analysis-metadata-mutation",
requiresPrivileges: false,
},
limitations: ["Results depend on Hopper's completed static analysis."],
}),
);
/** Concrete analysis provider backed by REA's private Hopper bridge. */
export class HopperProvider implements AnalysisProvider {
constructor(
@@ -38,7 +58,7 @@ export class HopperProvider implements AnalysisProvider {
return IDENTITY;
}
capabilities(): readonly string[] {
capabilities(): readonly CapabilityDescriptor[] {
return CAPABILITIES;
}
-2
View File
@@ -4,8 +4,6 @@ import { HopperProtocolError, HopperRemoteError } from "../domain/errors.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
export { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
const responseSchema = z.union([
z.object({
id: z.number().int().nonnegative(),
+14 -5
View File
@@ -44,12 +44,21 @@ export const run = async (): Promise<number> => {
}
let handle: StdioServerHandle;
try {
handle = serveStdio(() => createServer(session, session, logger), {
onerror: () => {
serverLogger.error("MCP stdio transport error");
process.stderr.write("MCP stdio transport error\n");
handle = serveStdio(
() =>
createServer(
session,
session,
logger,
config.value.processExecutionPolicy,
),
{
onerror: () => {
serverLogger.error("MCP stdio transport error");
process.stderr.write("MCP stdio transport error\n");
},
},
});
);
} catch {
await session.close();
serverLogger.error("Failed to start MCP stdio transport");
+26 -3
View File
@@ -7,6 +7,7 @@ import { registerEnhancedTools } from "./registerEnhancedTools.js";
import { registerOfficialTools } from "./registerOfficialTools.js";
import { registerSessionTools } from "./registerSessionTools.js";
import { silentLogger, type Logger } from "../logger.js";
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
/**
* Construct one MCP server without acquiring subprocess resources.
@@ -17,6 +18,7 @@ export const createServer = (
analysis: AnalysisOperationPort,
session?: BinarySessionPort,
logger: Logger = silentLogger,
processPolicy?: ProcessExecutionPolicy,
): McpServer => {
const server = new McpServer(
{ name: PRODUCT_IDENTITY.mcpServerKey, version: "0.1.0" },
@@ -31,8 +33,29 @@ export const createServer = (
const toolLogger = logger.child({ layer: "server" });
const activeTarget =
session === undefined ? undefined : () => session.activeTarget();
registerOfficialTools(server, analysis, toolLogger, activeTarget);
registerEnhancedTools(server, analysis, toolLogger, activeTarget);
if (session !== undefined) registerSessionTools(server, session, toolLogger);
const provider = session?.providerIdentity();
const recordEvidence =
session === undefined
? undefined
: (evidence: Parameters<typeof session.recordEvidence>[0]) =>
session.recordEvidence(evidence);
registerOfficialTools(
server,
analysis,
toolLogger,
activeTarget,
provider,
recordEvidence,
);
registerEnhancedTools(
server,
analysis,
toolLogger,
activeTarget,
provider,
recordEvidence,
);
if (session !== undefined)
registerSessionTools(server, session, toolLogger, processPolicy);
return server;
};
+32 -14
View File
@@ -14,6 +14,8 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import type { ProviderIdentity } from "../application/AnalysisProvider.js";
import type { Evidence } from "../domain/evidence.js";
/** Register composed workflows against the same port as direct bridge tools. */
export const registerEnhancedTools = (
@@ -21,10 +23,21 @@ export const registerEnhancedTools = (
analysis: AnalysisOperationPort,
logger: Logger,
activeTarget?: () => BinaryTarget | undefined,
provider: ProviderIdentity = {
id: "unidentified",
name: "Unidentified provider",
version: null,
},
recordEvidence?: (evidence: Evidence) => void,
): void => {
const services = new EnhancedTools(analysis);
for (const contract of ENHANCED_TOOL_CONTRACTS) {
registerEnhancedTool(server, services, contract, { logger, activeTarget });
registerEnhancedTool(server, services, contract, {
logger,
activeTarget,
provider,
recordEvidence,
});
}
};
@@ -35,6 +48,8 @@ const registerEnhancedTool = (
registration: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly provider: ProviderIdentity;
readonly recordEvidence: ((evidence: Evidence) => void) | undefined;
},
): void => {
const name = enhancedToolNameSchema.parse(contract.name);
@@ -60,19 +75,22 @@ const registerEnhancedTool = (
const result = await logToolExecution(registration.logger, name, () =>
services.execute(name, input, context.mcpReq.signal),
);
return toCallToolResult(
result.ok
? {
ok: true,
value: createEvidence(registration.activeTarget?.(), {
operation: name,
parameters,
result: result.value,
}),
}
: result,
contract,
);
if (result.ok) {
const evidence = createEvidence(
registration.activeTarget?.(),
registration.provider,
{
operation: name,
parameters,
result: result.value,
confidence: "derived",
redactedRawPayload: result.value,
},
);
registration.recordEvidence?.(evidence);
return toCallToolResult({ ok: true, value: evidence }, contract);
}
return toCallToolResult(result, contract);
},
);
};
+31 -14
View File
@@ -11,6 +11,8 @@ import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence } from "../domain/evidence.js";
import type { ProviderIdentity } from "../application/AnalysisProvider.js";
import type { Evidence } from "../domain/evidence.js";
/** Register direct bridge proxies, preserving MCP cancellation and typed errors. */
export const registerOfficialTools = (
@@ -18,9 +20,20 @@ export const registerOfficialTools = (
analysis: AnalysisOperationPort,
logger: Logger,
activeTarget?: () => BinaryTarget | undefined,
provider: ProviderIdentity = {
id: "unidentified",
name: "Unidentified provider",
version: null,
},
recordEvidence?: (evidence: Evidence) => void,
): void => {
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
registerOfficialTool(server, analysis, contract, { logger, activeTarget });
registerOfficialTool(server, analysis, contract, {
logger,
activeTarget,
provider,
recordEvidence,
});
}
};
@@ -31,6 +44,8 @@ const registerOfficialTool = (
registration: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly provider: ProviderIdentity;
readonly recordEvidence: ((evidence: Evidence) => void) | undefined;
},
): void => {
server.registerTool(
@@ -51,19 +66,21 @@ const registerOfficialTool = (
signal: context.mcpReq.signal,
}),
);
return toCallToolResult(
result.ok
? {
ok: true,
value: createEvidence(registration.activeTarget?.(), {
operation: contract.name,
parameters: arguments_,
result: result.value,
}),
}
: result,
contract,
);
if (result.ok) {
const evidence = createEvidence(
registration.activeTarget?.(),
registration.provider,
{
operation: contract.name,
parameters: arguments_,
result: result.value,
redactedRawPayload: result.value,
},
);
registration.recordEvidence?.(evidence);
return toCallToolResult({ ok: true, value: evidence }, contract);
}
return toCallToolResult(result, contract);
},
);
};
+196 -1
View File
@@ -6,14 +6,200 @@ import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import { toCallToolResult } from "./toolResult.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { err, ok } from "../domain/result.js";
import { EvidenceLedgerError } from "../domain/errors.js";
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
import {
compareProcessCaptures,
processCaptureSchema,
processScenarioSchema,
} from "../domain/processCapture.js";
import { captureProcessScenario } from "../application/ProcessHarness.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
const DENY_PROCESS_POLICY: ProcessExecutionPolicy = {
enabled: false,
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
};
const PROCESS_PROVIDER = {
id: "rea-process",
name: "REA deterministic process harness",
version: "1",
} as const;
interface ProcessToolRegistration {
readonly server: McpServer;
readonly session: BinarySessionPort;
readonly logger: Logger;
readonly processPolicy: ProcessExecutionPolicy;
readonly captureContract: (typeof SESSION_TOOL_CONTRACTS)[5];
readonly compareContract: (typeof SESSION_TOOL_CONTRACTS)[6];
}
const registerProcessTools = ({
server,
session,
logger,
processPolicy,
captureContract,
compareContract,
}: ProcessToolRegistration): void => {
server.registerTool(
captureContract.name,
{
description: captureContract.description,
inputSchema: captureContract.inputSchema,
outputSchema: captureContract.outputSchema,
annotations: captureContract.annotations,
},
async (input, context) => {
const scenario = processScenarioSchema.parse(input);
const captured = await logToolExecution(
logger,
captureContract.name,
() =>
captureProcessScenario(
scenario,
processPolicy,
context.mcpReq.signal,
),
);
if (!captured.ok) return toCallToolResult(captured, captureContract);
const evidence = createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v1",
operation: captureContract.name,
parameters: {
executable_name:
scenario.executable.split("/").at(-1) ?? scenario.executable,
argument_count: scenario.arguments.length,
event_count: scenario.events.length,
filesystem_root_count: scenario.filesystem_roots.length,
},
result: jsonValueSchema.parse(captured.value),
confidence: "observed",
authority: "controlled-replay",
environment: {
id: `${process.platform}-${process.arch}`,
platform: process.platform,
architecture: process.arch,
isolation: "process",
},
limitations: captured.value.limitations,
});
session.recordEvidence(evidence);
return toCallToolResult(ok(evidence), captureContract);
},
);
server.registerTool(
compareContract.name,
{
description: compareContract.description,
inputSchema: compareContract.inputSchema,
outputSchema: compareContract.outputSchema,
annotations: compareContract.annotations,
},
(input) => {
const parsed = z
.object({
left_evidence_id: z.string(),
left: processCaptureSchema,
right_evidence_id: z.string(),
right: processCaptureSchema,
})
.parse(input);
const comparison = compareProcessCaptures(parsed.left, parsed.right);
const evidence = createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-comparison/v1",
operation: compareContract.name,
parameters: {},
result: jsonValueSchema.parse(comparison),
confidence: "derived",
authority: "analyst-inference",
limitations: comparison.limitations,
evidenceLinks: [parsed.left_evidence_id, parsed.right_evidence_id],
});
session.recordEvidence(evidence);
return toCallToolResult(ok(evidence), compareContract);
},
);
};
interface EvidenceToolRegistration {
readonly server: McpServer;
readonly session: BinarySessionPort;
readonly exportContract: (typeof SESSION_TOOL_CONTRACTS)[3];
readonly importContract: (typeof SESSION_TOOL_CONTRACTS)[4];
}
const registerEvidenceTools = ({
server,
session,
exportContract,
importContract,
}: EvidenceToolRegistration): void => {
server.registerTool(
exportContract.name,
{
description: exportContract.description,
inputSchema: exportContract.inputSchema,
outputSchema: exportContract.outputSchema,
annotations: exportContract.annotations,
},
() => toCallToolResult(ok(session.exportEvidenceBundle()), exportContract),
);
server.registerTool(
importContract.name,
{
description: importContract.description,
inputSchema: importContract.inputSchema,
outputSchema: importContract.outputSchema,
annotations: importContract.annotations,
},
(input) => {
try {
const bundle = z.object({ bundle: z.unknown() }).parse(input).bundle;
const imported = session.importEvidenceBundle(bundle);
return toCallToolResult(
ok({
imported,
total: session.exportEvidenceBundle().records.length,
}),
importContract,
);
} catch (cause: unknown) {
return toCallToolResult(
err(
new EvidenceLedgerError("Evidence bundle validation failed", {
cause,
}),
),
importContract,
);
}
},
);
};
/** Register MCP-only target lifecycle operations on a long-lived session. */
export const registerSessionTools = (
server: McpServer,
session: BinarySessionPort,
logger: Logger,
processPolicy: ProcessExecutionPolicy = DENY_PROCESS_POLICY,
): void => {
const [openContract, closeContract, statusContract] = SESSION_TOOL_CONTRACTS;
const [
openContract,
closeContract,
statusContract,
exportContract,
importContract,
captureContract,
compareContract,
] = SESSION_TOOL_CONTRACTS;
server.registerTool(
openContract.name,
{
@@ -72,4 +258,13 @@ export const registerSessionTools = (
() =>
toCallToolResult({ ok: true, value: session.status() }, statusContract),
);
registerEvidenceTools({ server, session, exportContract, importContract });
registerProcessTools({
server,
session,
logger,
processPolicy,
captureContract,
compareContract,
});
};