feat: add evidence-backed process investigations
This commit is contained in:
@@ -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
@@ -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)),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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
@@ -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 = (
|
||||
|
||||
@@ -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],
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user