Add evidence-backed investigation workflows
This commit is contained in:
@@ -1,19 +1,66 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { OfficialToolName } from "../contracts/toolContracts.js";
|
||||
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
|
||||
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
|
||||
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { EvidenceLocation } from "../domain/evidence.js";
|
||||
import type { EvidenceSubjectTarget } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
|
||||
interface ExecutionOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Closed operations accepted by provider-backed analysis sessions. */
|
||||
export type AnalysisOperation =
|
||||
| OfficialToolName
|
||||
| EnhancedToolName
|
||||
| NativeToolName
|
||||
| ArtifactToolName
|
||||
| "health";
|
||||
|
||||
/** Atomic successful provider observation with exact producing provenance. */
|
||||
export interface AnalysisExecution {
|
||||
readonly result: JsonValue;
|
||||
readonly rawResult: JsonValue | null;
|
||||
readonly provider: ProviderIdentity;
|
||||
readonly limitations: readonly string[];
|
||||
readonly locations: readonly EvidenceLocation[];
|
||||
readonly subject: EvidenceSubjectTarget | null;
|
||||
}
|
||||
|
||||
/** Build a validated atomic provider observation at an adapter boundary. */
|
||||
export const createAnalysisExecution = (
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options: {
|
||||
readonly rawResult?: unknown;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly subject?: EvidenceSubjectTarget;
|
||||
} = {},
|
||||
): AnalysisExecution => ({
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult:
|
||||
options.rawResult === undefined
|
||||
? jsonValueSchema.parse(result)
|
||||
: jsonValueSchema.parse(options.rawResult),
|
||||
provider,
|
||||
limitations: [...(options.limitations ?? [])],
|
||||
locations: [...(options.locations ?? [])],
|
||||
subject: options.subject ?? null,
|
||||
});
|
||||
|
||||
/** Provider-neutral application capability for one analysis operation. */
|
||||
export interface AnalysisOperationPort {
|
||||
execute(
|
||||
operation: string,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<JsonValue, AnalysisError>>;
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Provider session bound to exactly one parsed artifact. */
|
||||
@@ -29,26 +76,37 @@ 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;
|
||||
readonly changesPermissions: boolean;
|
||||
readonly requiresRoot: boolean;
|
||||
}
|
||||
|
||||
export interface CapabilityDescriptor {
|
||||
readonly operation: AnalysisOperation;
|
||||
readonly version: number;
|
||||
readonly available: boolean;
|
||||
type CapabilityAvailability =
|
||||
| { readonly available: true; readonly reason: null }
|
||||
| { readonly available: false; readonly reason: string };
|
||||
|
||||
interface CapabilityLimits {
|
||||
readonly maxResults: number | null;
|
||||
readonly maxPayloadBytes: number | null;
|
||||
readonly timeoutMs: number | null;
|
||||
}
|
||||
|
||||
export type CapabilityDescriptor = CapabilityAvailability & {
|
||||
readonly provider: ProviderIdentity;
|
||||
readonly operation: Exclude<AnalysisOperation, "health">;
|
||||
readonly inputContractVersion: number;
|
||||
readonly outputContractVersion: number;
|
||||
readonly pagination: "none" | "offset" | "cursor";
|
||||
readonly exhaustive: boolean;
|
||||
readonly effects: CapabilityEffects;
|
||||
readonly limits: CapabilityLimits;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
};
|
||||
|
||||
/** Factory and capability declaration for an analysis implementation. */
|
||||
export interface AnalysisProvider {
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
|
||||
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../artifacts/ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactLimits,
|
||||
type ArtifactReader,
|
||||
} from "../artifacts/ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
|
||||
import { SafeOutputTree } from "../artifacts/SafeOutputTree.js";
|
||||
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../artifacts/MachOSliceArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
type ArtifactExtractionResult,
|
||||
type ArtifactGraphManifest,
|
||||
type ArtifactNode,
|
||||
type ArtifactOccurrence,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { inventoryArtifact } from "./ArtifactInventory.js";
|
||||
import {
|
||||
digestCanonical,
|
||||
pageOf,
|
||||
toOutputLimits,
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
|
||||
const PAGE_SIZE = 500;
|
||||
|
||||
/** Already-approved extraction request from a caller-owned policy boundary. */
|
||||
export interface ArtifactExtractionInput {
|
||||
readonly inputPath: string;
|
||||
readonly inputFormat: BinaryTarget["format"];
|
||||
readonly outputRoot: string;
|
||||
readonly occurrenceIds: readonly string[];
|
||||
readonly offset: number;
|
||||
readonly limit: number;
|
||||
readonly limits: ArtifactLimits;
|
||||
}
|
||||
|
||||
/** Extract only explicitly selected inventory occurrences into an absent root. */
|
||||
export const extractArtifact = async (
|
||||
input: ArtifactExtractionInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactExtractionResult> => {
|
||||
validateSelection(input.occurrenceIds);
|
||||
const sourcePath = await realpath(input.inputPath);
|
||||
const selectedIds = new Set(input.occurrenceIds);
|
||||
const inventory = await loadInventory(
|
||||
sourcePath,
|
||||
input.limits,
|
||||
selectedIds,
|
||||
signal,
|
||||
);
|
||||
const selected = input.occurrenceIds.map((id) => {
|
||||
const occurrence = inventory.occurrences.get(id);
|
||||
if (occurrence === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`Selected artifact occurrence was not found: ${id}`,
|
||||
);
|
||||
if (
|
||||
(occurrence.entry_kind !== "file" && occurrence.entry_kind !== "slice") ||
|
||||
occurrence.artifact_id === null ||
|
||||
occurrence.encrypted ||
|
||||
occurrence.logical_path === "."
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Selected occurrence is not an extractable regular child file: ${id}`,
|
||||
);
|
||||
const node = inventory.nodes.get(occurrence.artifact_id);
|
||||
if (node === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Selected occurrence has no inventory node: ${id}`,
|
||||
);
|
||||
return { occurrence, node };
|
||||
});
|
||||
return materializeSelection({
|
||||
input,
|
||||
sourcePath,
|
||||
inventory,
|
||||
selected,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
interface SelectedOccurrence {
|
||||
readonly occurrence: ArtifactOccurrence;
|
||||
readonly node: ArtifactNode;
|
||||
}
|
||||
|
||||
interface ExtractedOccurrence {
|
||||
readonly artifact_id: string;
|
||||
readonly relative_path: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes_written: number;
|
||||
readonly created: true;
|
||||
}
|
||||
|
||||
const materializeSelection = async ({
|
||||
input,
|
||||
sourcePath,
|
||||
inventory,
|
||||
selected,
|
||||
signal,
|
||||
}: {
|
||||
readonly input: ArtifactExtractionInput;
|
||||
readonly sourcePath: string;
|
||||
readonly inventory: LoadedInventory;
|
||||
readonly selected: readonly SelectedOccurrence[];
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<ArtifactExtractionResult> => {
|
||||
const byPath = new Map(
|
||||
selected.map((item) => [item.occurrence.logical_path, item]),
|
||||
);
|
||||
const reader = await createReader(sourcePath, input.inputFormat);
|
||||
const output = await SafeOutputTree.create(input.outputRoot, input.limits);
|
||||
let readerClosed = false;
|
||||
const extracted: ExtractedOccurrence[] = [];
|
||||
try {
|
||||
const found = new Set<string>();
|
||||
const registry = new ArtifactPathRegistry();
|
||||
let entryCount = 0;
|
||||
for await (const entry of reader.entries(signal)) {
|
||||
entryCount += 1;
|
||||
if (entryCount > input.limits.maxEntries)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Artifact entry limit exceeded during extraction",
|
||||
);
|
||||
const path = normalizeArtifactPath(entry.path, input.limits);
|
||||
registry.add(path, entry.kind);
|
||||
const selectedItem = byPath.get(path);
|
||||
if (selectedItem === undefined) continue;
|
||||
preflight(entry, input.limits);
|
||||
const stream = await reader.open(entry, signal);
|
||||
const written = await output.write(
|
||||
path,
|
||||
stream,
|
||||
selectedItem.node.sha256,
|
||||
signal,
|
||||
);
|
||||
extracted.push({
|
||||
artifact_id: selectedItem.node.artifact_id,
|
||||
relative_path: written.relativePath,
|
||||
sha256: written.sha256,
|
||||
bytes_written: written.bytesWritten,
|
||||
created: true,
|
||||
});
|
||||
found.add(path);
|
||||
}
|
||||
if (found.size !== selected.length)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Selected inventory occurrence disappeared before extraction",
|
||||
);
|
||||
await reader.close();
|
||||
readerClosed = true;
|
||||
extracted.sort((left, right) =>
|
||||
left.relative_path.localeCompare(right.relative_path, "en"),
|
||||
);
|
||||
const result = createExtractionResult(
|
||||
input,
|
||||
inventory,
|
||||
selected,
|
||||
extracted,
|
||||
);
|
||||
const verifiedSource = await inventoryArtifact(
|
||||
sourcePath,
|
||||
input.limits,
|
||||
pageInput(0, 0),
|
||||
signal,
|
||||
);
|
||||
assertSameManifest(inventory.manifest, verifiedSource.manifest);
|
||||
await output.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
if (!readerClosed) await reader.close().catch(() => undefined);
|
||||
await output.rollback();
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const createExtractionResult = (
|
||||
input: ArtifactExtractionInput,
|
||||
inventory: LoadedInventory,
|
||||
selected: readonly SelectedOccurrence[],
|
||||
extracted: readonly ExtractedOccurrence[],
|
||||
): ArtifactExtractionResult => {
|
||||
const extractionSemantic = {
|
||||
schema_version: 1 as const,
|
||||
source_manifest_id: inventory.manifest.manifest_id,
|
||||
selected_occurrence_ids: selected
|
||||
.map(({ occurrence }) => occurrence.occurrence_id)
|
||||
.sort((left, right) => left.localeCompare(right)),
|
||||
files_sha256: digestCanonical(extracted),
|
||||
output_root_alias: "$OUTPUT_ROOT" as const,
|
||||
};
|
||||
return artifactExtractionResultSchema.parse({
|
||||
manifest: inventory.manifest,
|
||||
extraction_manifest: {
|
||||
...extractionSemantic,
|
||||
extraction_id: `aex_${digestCanonical(extractionSemantic)}`,
|
||||
},
|
||||
output_root: "$OUTPUT_ROOT",
|
||||
artifacts: pageOf(extracted, input.offset, input.limit),
|
||||
containment_verified: true,
|
||||
cleanup: { attempted: false, verified: true, residual_paths: [] },
|
||||
limits: toOutputLimits(input.limits),
|
||||
provenance: [],
|
||||
limitations: [
|
||||
"Only caller-selected regular file occurrences were materialized.",
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
interface LoadedInventory {
|
||||
readonly manifest: ArtifactGraphManifest;
|
||||
readonly occurrences: ReadonlyMap<string, ArtifactOccurrence>;
|
||||
readonly nodes: ReadonlyMap<string, ArtifactNode>;
|
||||
}
|
||||
|
||||
const loadInventory = async (
|
||||
path: string,
|
||||
limits: ArtifactLimits,
|
||||
selectedIds: ReadonlySet<string>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<LoadedInventory> => {
|
||||
const first = await inventoryArtifact(path, limits, pageInput(0, 0), signal);
|
||||
const occurrences = new Map<string, ArtifactOccurrence>();
|
||||
const neededNodes = new Set<string>();
|
||||
collectOccurrences(
|
||||
first.occurrences.items,
|
||||
selectedIds,
|
||||
occurrences,
|
||||
neededNodes,
|
||||
);
|
||||
for (
|
||||
let offset = first.occurrences.next_offset;
|
||||
offset !== null && occurrences.size < selectedIds.size;
|
||||
offset += PAGE_SIZE
|
||||
) {
|
||||
const page = await inventoryArtifact(
|
||||
path,
|
||||
limits,
|
||||
pageInput(0, offset),
|
||||
signal,
|
||||
);
|
||||
assertSameManifest(first.manifest, page.manifest);
|
||||
collectOccurrences(
|
||||
page.occurrences.items,
|
||||
selectedIds,
|
||||
occurrences,
|
||||
neededNodes,
|
||||
);
|
||||
}
|
||||
const nodes = new Map<string, ArtifactNode>();
|
||||
collectNodes(first.nodes.items, neededNodes, nodes);
|
||||
for (
|
||||
let offset = first.nodes.next_offset;
|
||||
offset !== null && nodes.size < neededNodes.size;
|
||||
offset += PAGE_SIZE
|
||||
) {
|
||||
const page = await inventoryArtifact(
|
||||
path,
|
||||
limits,
|
||||
pageInput(offset, 0),
|
||||
signal,
|
||||
);
|
||||
assertSameManifest(first.manifest, page.manifest);
|
||||
collectNodes(page.nodes.items, neededNodes, nodes);
|
||||
}
|
||||
return { manifest: first.manifest, occurrences, nodes };
|
||||
};
|
||||
|
||||
const pageInput = (nodeOffset: number, occurrenceOffset: number) => ({
|
||||
nodeOffset,
|
||||
nodeLimit: PAGE_SIZE,
|
||||
occurrenceOffset,
|
||||
occurrenceLimit: PAGE_SIZE,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 1,
|
||||
});
|
||||
|
||||
const collectOccurrences = (
|
||||
items: readonly ArtifactOccurrence[],
|
||||
selected: ReadonlySet<string>,
|
||||
output: Map<string, ArtifactOccurrence>,
|
||||
neededNodes: Set<string>,
|
||||
): void => {
|
||||
for (const item of items) {
|
||||
if (!selected.has(item.occurrence_id)) continue;
|
||||
output.set(item.occurrence_id, item);
|
||||
if (item.artifact_id !== null) neededNodes.add(item.artifact_id);
|
||||
}
|
||||
};
|
||||
|
||||
const collectNodes = (
|
||||
items: readonly ArtifactNode[],
|
||||
selected: ReadonlySet<string>,
|
||||
output: Map<string, ArtifactNode>,
|
||||
): void => {
|
||||
for (const item of items)
|
||||
if (selected.has(item.artifact_id)) output.set(item.artifact_id, item);
|
||||
};
|
||||
|
||||
const createReader = async (
|
||||
path: string,
|
||||
format: BinaryTarget["format"],
|
||||
): Promise<ArtifactReader> => {
|
||||
if ((await lstat(path)).isDirectory())
|
||||
return new DirectoryArtifactReader(path);
|
||||
if (format === "asar") return new AsarArtifactReader(path);
|
||||
if (format === "ipa" || format === "apk" || format === "zip")
|
||||
return new ZipArtifactReader(path, format);
|
||||
if (format === "mach-o") return new MachOSliceArtifactReader(path);
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`Artifact format has no extraction reader: ${format}`,
|
||||
);
|
||||
};
|
||||
|
||||
const validateSelection = (ids: readonly string[]): void => {
|
||||
if (ids.length === 0 || ids.length > PAGE_SIZE)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Extraction requires 1 to 500 explicitly selected occurrences",
|
||||
);
|
||||
if (new Set(ids).size !== ids.length)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Extraction occurrence selection contains duplicates",
|
||||
);
|
||||
};
|
||||
|
||||
const preflight = (entry: ArtifactEntry, limits: ArtifactLimits): void => {
|
||||
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Selected artifact entry cannot be read: ${entry.path}`,
|
||||
);
|
||||
if (entry.declaredSize !== null && entry.declaredSize > limits.maxEntryBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Selected artifact exceeds byte limit: ${entry.path}`,
|
||||
);
|
||||
if (
|
||||
entry.declaredSize !== null &&
|
||||
entry.compressedSize !== null &&
|
||||
(entry.compressedSize === 0
|
||||
? entry.declaredSize > 0
|
||||
: entry.declaredSize / entry.compressedSize > limits.maxCompressionRatio)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Selected artifact exceeds compression ratio limit: ${entry.path}`,
|
||||
);
|
||||
};
|
||||
|
||||
const assertSameManifest = (
|
||||
expected: ArtifactGraphManifest,
|
||||
observed: ArtifactGraphManifest,
|
||||
): void => {
|
||||
if (expected.manifest_id !== observed.manifest_id)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Artifact changed while resolving extraction selection",
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,359 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { extname } from "node:path";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type {
|
||||
ArtifactEntry,
|
||||
ArtifactLimits,
|
||||
} from "../artifacts/ArtifactReader.js";
|
||||
import type {
|
||||
ArtifactCommand,
|
||||
ArtifactEdge,
|
||||
ArtifactNode,
|
||||
ArtifactOccurrence,
|
||||
} from "../domain/artifactGraph.js";
|
||||
|
||||
/** Mutable internal occurrence used until root-bound IDs are known. */
|
||||
export interface MutableOccurrence {
|
||||
occurrence_id: string;
|
||||
artifact_id: string | null;
|
||||
parent_occurrence_id: string | null;
|
||||
logical_path: string;
|
||||
entry_kind: ArtifactOccurrence["entry_kind"];
|
||||
declared_size: number | null;
|
||||
compressed_size: number | null;
|
||||
executable: boolean;
|
||||
encrypted: boolean;
|
||||
hash_status: ArtifactOccurrence["hash_status"];
|
||||
source_location: ArtifactOccurrence["source_location"];
|
||||
limitations: string[];
|
||||
}
|
||||
|
||||
export const createOccurrence = (
|
||||
entry: ArtifactEntry,
|
||||
path: string,
|
||||
parent: string | null,
|
||||
): MutableOccurrence => ({
|
||||
occurrence_id: `occ_${digestCanonical({ path, kind: entry.kind })}`,
|
||||
artifact_id: null,
|
||||
parent_occurrence_id: parent,
|
||||
logical_path: path,
|
||||
entry_kind: entry.kind,
|
||||
declared_size: entry.declaredSize,
|
||||
compressed_size: entry.compressedSize,
|
||||
executable: entry.executable,
|
||||
encrypted: entry.encrypted,
|
||||
hash_status: entry.encrypted ? "unavailable" : "not-hashed-limit",
|
||||
source_location:
|
||||
entry.byteOffset === null || entry.declaredSize === null
|
||||
? null
|
||||
: { offset: entry.byteOffset, length: entry.declaredSize },
|
||||
limitations: [...entry.limitations],
|
||||
});
|
||||
|
||||
export const materializeDirectoryNodes = (
|
||||
occurrences: MutableOccurrence[],
|
||||
nodes: Map<string, ArtifactNode>,
|
||||
): void => {
|
||||
const directories = occurrences
|
||||
.filter(({ entry_kind: kind }) => kind === "directory")
|
||||
.sort(
|
||||
(left, right) => depth(right.logical_path) - depth(left.logical_path),
|
||||
);
|
||||
const childrenByParent = new Map<string, MutableOccurrence[]>();
|
||||
for (const occurrence of occurrences) {
|
||||
if (occurrence.parent_occurrence_id === null) continue;
|
||||
const children = childrenByParent.get(occurrence.parent_occurrence_id);
|
||||
if (children === undefined)
|
||||
childrenByParent.set(occurrence.parent_occurrence_id, [occurrence]);
|
||||
else children.push(occurrence);
|
||||
}
|
||||
for (const directory of directories) {
|
||||
const children = (childrenByParent.get(directory.occurrence_id) ?? [])
|
||||
.map(({ logical_path, artifact_id, entry_kind }) => ({
|
||||
name: logical_path.split("/").at(-1),
|
||||
artifact_id,
|
||||
entry_kind,
|
||||
}))
|
||||
.sort((left, right) =>
|
||||
String(left.name).localeCompare(String(right.name)),
|
||||
);
|
||||
const node = createArtifactNode({
|
||||
sha256: digestCanonical({ kind: "directory", children }),
|
||||
size: 0,
|
||||
kind: directory.logical_path.toLowerCase().endsWith(".framework")
|
||||
? "framework"
|
||||
: "container",
|
||||
format: "directory",
|
||||
executable: false,
|
||||
contentState: "virtual",
|
||||
});
|
||||
const existing = nodes.get(node.artifact_id);
|
||||
nodes.set(
|
||||
node.artifact_id,
|
||||
existing?.kind === "framework" ? existing : node,
|
||||
);
|
||||
directory.artifact_id = node.artifact_id;
|
||||
directory.hash_status = "verified";
|
||||
}
|
||||
};
|
||||
|
||||
export const createRootNode = (input: {
|
||||
readonly path: string;
|
||||
readonly format: ArtifactNode["format"];
|
||||
readonly directory: boolean;
|
||||
readonly digest: { readonly sha256: string; readonly bytes: number } | null;
|
||||
readonly occurrences: readonly MutableOccurrence[];
|
||||
}): ArtifactNode =>
|
||||
createArtifactNode({
|
||||
sha256:
|
||||
input.digest?.sha256 ??
|
||||
digestCanonical({
|
||||
kind: "directory-root",
|
||||
children: input.occurrences.map(({ logical_path, artifact_id }) => ({
|
||||
logical_path,
|
||||
artifact_id,
|
||||
})),
|
||||
}),
|
||||
size: input.digest?.bytes ?? 0,
|
||||
kind:
|
||||
input.directory ||
|
||||
["zip", "ipa", "apk", "asar", "dmg", "pkg"].includes(input.format)
|
||||
? "container"
|
||||
: classifyArtifactPath(input.path).kind,
|
||||
format: input.format,
|
||||
executable: false,
|
||||
contentState: "materialized",
|
||||
});
|
||||
|
||||
export const createArtifactNode = (input: {
|
||||
readonly sha256: string;
|
||||
readonly size: number;
|
||||
readonly kind: ArtifactNode["kind"];
|
||||
readonly format: ArtifactNode["format"];
|
||||
readonly executable: boolean;
|
||||
readonly contentState: ArtifactNode["content_state"];
|
||||
}): ArtifactNode => ({
|
||||
artifact_id: `art_${digestCanonical({ schema_version: 1, sha256: input.sha256 })}`,
|
||||
kind: input.kind,
|
||||
format: input.format,
|
||||
sha256: input.sha256,
|
||||
size: input.size,
|
||||
media_type: null,
|
||||
architecture: null,
|
||||
executable: input.executable,
|
||||
content_state: input.contentState,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
export const rootOccurrenceFor = (
|
||||
node: ArtifactNode,
|
||||
declaredSize: number,
|
||||
): MutableOccurrence => ({
|
||||
occurrence_id: `occ_${digestCanonical({ root: node.artifact_id })}`,
|
||||
artifact_id: node.artifact_id,
|
||||
parent_occurrence_id: null,
|
||||
logical_path: ".",
|
||||
entry_kind: node.format === "directory" ? "directory" : "file",
|
||||
declared_size: declaredSize,
|
||||
compressed_size: null,
|
||||
executable: node.executable,
|
||||
encrypted: false,
|
||||
hash_status: "verified",
|
||||
source_location: null,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
export const rekeyOccurrences = (
|
||||
rootArtifactId: string,
|
||||
occurrences: MutableOccurrence[],
|
||||
): void => {
|
||||
const replacements = new Map<string, string>();
|
||||
for (const occurrence of occurrences)
|
||||
replacements.set(
|
||||
occurrence.occurrence_id,
|
||||
`occ_${digestCanonical({
|
||||
root_artifact_id: rootArtifactId,
|
||||
logical_path: occurrence.logical_path,
|
||||
entry_kind: occurrence.entry_kind,
|
||||
})}`,
|
||||
);
|
||||
for (const occurrence of occurrences) {
|
||||
occurrence.occurrence_id =
|
||||
replacements.get(occurrence.occurrence_id) ?? occurrence.occurrence_id;
|
||||
if (occurrence.parent_occurrence_id !== null)
|
||||
occurrence.parent_occurrence_id =
|
||||
replacements.get(occurrence.parent_occurrence_id) ??
|
||||
occurrence.parent_occurrence_id;
|
||||
}
|
||||
};
|
||||
|
||||
export const createArtifactEdges = (
|
||||
rootArtifactId: string,
|
||||
occurrences: MutableOccurrence[],
|
||||
producer?: ArtifactCommand,
|
||||
): ArtifactEdge[] => {
|
||||
const byId = new Map(occurrences.map((item) => [item.occurrence_id, item]));
|
||||
const edges: ArtifactEdge[] = [];
|
||||
for (const occurrence of occurrences) {
|
||||
if (
|
||||
occurrence.parent_occurrence_id === null ||
|
||||
occurrence.artifact_id === null
|
||||
)
|
||||
continue;
|
||||
const mappedSource = occurrence.logical_path.endsWith(".map")
|
||||
? occurrences.find(
|
||||
({ logical_path: path }) =>
|
||||
path === occurrence.logical_path.slice(0, -".map".length),
|
||||
)
|
||||
: undefined;
|
||||
const parentArtifactId =
|
||||
mappedSource?.artifact_id ??
|
||||
byId.get(occurrence.parent_occurrence_id)?.artifact_id ??
|
||||
rootArtifactId;
|
||||
const semantic = {
|
||||
parent_artifact_id: parentArtifactId,
|
||||
child_artifact_id: occurrence.artifact_id,
|
||||
relation:
|
||||
occurrence.entry_kind === "slice"
|
||||
? ("slice-of" as const)
|
||||
: relationFor(occurrence.logical_path),
|
||||
occurrence_id: occurrence.occurrence_id,
|
||||
logical_path: occurrence.logical_path,
|
||||
};
|
||||
edges.push({
|
||||
edge_id: `edge_${digestCanonical(semantic)}`,
|
||||
...semantic,
|
||||
producer: occurrence.entry_kind === "slice" ? (producer ?? null) : null,
|
||||
ordinal: edges.length,
|
||||
});
|
||||
}
|
||||
return edges;
|
||||
};
|
||||
|
||||
export const nearestParent = (
|
||||
path: string,
|
||||
occurrences: ReadonlyMap<string, MutableOccurrence>,
|
||||
): MutableOccurrence | undefined => {
|
||||
const parts = path.split("/");
|
||||
while (parts.length > 1) {
|
||||
parts.pop();
|
||||
const candidate = occurrences.get(parts.join("/"));
|
||||
if (candidate?.entry_kind === "directory") return candidate;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const classifyArtifactPath = (
|
||||
path: string,
|
||||
): Pick<ArtifactNode, "kind" | "format"> => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.endsWith(".map"))
|
||||
return { kind: "source-map", format: "source-map" };
|
||||
if (/\.(?:m?js|cjs)$/u.test(lower))
|
||||
return { kind: "javascript", format: "javascript-bundle" };
|
||||
if (lower.endsWith(".asar")) return { kind: "container", format: "asar" };
|
||||
const archiveFormat = archiveFormatForExtension(extname(lower));
|
||||
if (archiveFormat !== undefined)
|
||||
return { kind: "container", format: archiveFormat };
|
||||
if (/\.framework(?:\/|$)/u.test(lower))
|
||||
return { kind: "framework", format: "file" };
|
||||
if (/\.(?:node|dylib|so)$/u.test(lower))
|
||||
return {
|
||||
kind: lower.endsWith(".node") ? "native-addon" : "dynamic-library",
|
||||
format: "file",
|
||||
};
|
||||
if (lower.endsWith(".plist")) return { kind: "plist", format: "plist" };
|
||||
if (lower.endsWith(".entitlements"))
|
||||
return { kind: "entitlements", format: "entitlements" };
|
||||
return { kind: "resource", format: "file" };
|
||||
};
|
||||
|
||||
/** Classify executable formats from bytes while retaining path-specific roles. */
|
||||
export const classifyArtifactContent = (
|
||||
path: string,
|
||||
prefix: Buffer,
|
||||
): Pick<ArtifactNode, "kind" | "format"> => {
|
||||
const byPath = classifyArtifactPath(path);
|
||||
if (prefix.length >= 4) {
|
||||
const magic = prefix.readUInt32BE(0);
|
||||
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
|
||||
return {
|
||||
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
|
||||
format: "mach-o-universal",
|
||||
};
|
||||
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
|
||||
return {
|
||||
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
|
||||
? byPath.kind
|
||||
: "executable",
|
||||
format: "mach-o",
|
||||
};
|
||||
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
|
||||
return {
|
||||
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
|
||||
? byPath.kind
|
||||
: "executable",
|
||||
format: "elf",
|
||||
};
|
||||
}
|
||||
if (prefix.length >= 2 && prefix[0] === 0x4d && prefix[1] === 0x5a)
|
||||
return {
|
||||
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
|
||||
format: "pe",
|
||||
};
|
||||
return byPath;
|
||||
};
|
||||
|
||||
export const pageOf = <Value>(
|
||||
items: readonly Value[],
|
||||
offset: number,
|
||||
limit: number,
|
||||
) => ({
|
||||
items: items.slice(offset, offset + limit),
|
||||
offset,
|
||||
limit,
|
||||
total: items.length,
|
||||
next_offset: offset + limit < items.length ? offset + limit : null,
|
||||
});
|
||||
|
||||
export const toOutputLimits = (limits: ArtifactLimits) => ({
|
||||
max_entries: limits.maxEntries,
|
||||
max_total_bytes: limits.maxTotalBytes,
|
||||
max_entry_bytes: limits.maxEntryBytes,
|
||||
max_compression_ratio: limits.maxCompressionRatio,
|
||||
max_depth: limits.maxDepth,
|
||||
max_path_bytes: limits.maxPathBytes,
|
||||
});
|
||||
|
||||
export const digestCanonical = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Artifact value is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const relationFor = (path: string): ArtifactEdge["relation"] => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.endsWith(".map")) return "maps-source";
|
||||
if (lower.includes(".framework/")) return "embeds";
|
||||
return "contains";
|
||||
};
|
||||
|
||||
const archiveFormatForExtension = (
|
||||
extension: string,
|
||||
): "zip" | "ipa" | "apk" | undefined => {
|
||||
switch (extension) {
|
||||
case ".zip":
|
||||
return "zip";
|
||||
case ".ipa":
|
||||
return "ipa";
|
||||
case ".apk":
|
||||
return "apk";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const depth = (path: string): number => path.split("/").length;
|
||||
@@ -0,0 +1,380 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { lstat, open, realpath } from "node:fs/promises";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../artifacts/ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactLimits,
|
||||
type ArtifactReader,
|
||||
} from "../artifacts/ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
|
||||
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../artifacts/MachOSliceArtifactReader.js";
|
||||
import { streamChunkToBuffer } from "../artifacts/StreamBytes.js";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
type ArtifactNode,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import {
|
||||
classifyArtifactPath,
|
||||
classifyArtifactContent,
|
||||
createArtifactEdges,
|
||||
createArtifactNode,
|
||||
createOccurrence,
|
||||
createRootNode,
|
||||
digestCanonical,
|
||||
materializeDirectoryNodes,
|
||||
nearestParent,
|
||||
pageOf,
|
||||
rekeyOccurrences,
|
||||
rootOccurrenceFor,
|
||||
toOutputLimits,
|
||||
type MutableOccurrence,
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
|
||||
interface InventoryPageInput {
|
||||
readonly nodeOffset: number;
|
||||
readonly nodeLimit: number;
|
||||
readonly occurrenceOffset: number;
|
||||
readonly occurrenceLimit: number;
|
||||
readonly edgeOffset: number;
|
||||
readonly edgeLimit: number;
|
||||
}
|
||||
|
||||
/** Inventory one local artifact without extracting or mounting it. */
|
||||
export const inventoryArtifact = async (
|
||||
inputPath: string,
|
||||
limits: ArtifactLimits,
|
||||
page: InventoryPageInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactInventoryResult> => {
|
||||
abortIfNeeded(signal);
|
||||
const path = await realpath(inputPath);
|
||||
const metadata = await lstat(path);
|
||||
const rootFormat = await classifyRoot(path, metadata.isDirectory());
|
||||
const rootDigest = metadata.isDirectory()
|
||||
? null
|
||||
: await hashReadable(createReadStream(path), limits.maxTotalBytes, signal);
|
||||
const reader = await createReader(path, rootFormat);
|
||||
|
||||
try {
|
||||
const { nodes, occurrences } = await scanReader(reader, limits, signal);
|
||||
|
||||
materializeDirectoryNodes(occurrences, nodes);
|
||||
const rootNode = createRootNode({
|
||||
path,
|
||||
format: rootFormat,
|
||||
directory: metadata.isDirectory(),
|
||||
digest: rootDigest,
|
||||
occurrences,
|
||||
});
|
||||
nodes.set(rootNode.artifact_id, rootNode);
|
||||
rekeyOccurrences(rootNode.artifact_id, occurrences);
|
||||
const rootOccurrence = rootOccurrenceFor(rootNode, metadata.size);
|
||||
for (const occurrence of occurrences)
|
||||
if (occurrence.parent_occurrence_id === null)
|
||||
occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;
|
||||
occurrences.unshift(rootOccurrence);
|
||||
const edges = createArtifactEdges(
|
||||
rootNode.artifact_id,
|
||||
occurrences,
|
||||
reader?.provenance()[0],
|
||||
);
|
||||
const orderedNodes = [...nodes.values()].sort((left, right) =>
|
||||
left.artifact_id.localeCompare(right.artifact_id),
|
||||
);
|
||||
const orderedOccurrences = occurrences.sort((left, right) =>
|
||||
left.logical_path.localeCompare(right.logical_path, "en"),
|
||||
);
|
||||
const orderedEdges = edges.sort((left, right) =>
|
||||
left.edge_id.localeCompare(right.edge_id),
|
||||
);
|
||||
if (rootDigest !== null) {
|
||||
const verified = await hashReadable(
|
||||
createReadStream(path),
|
||||
limits.maxTotalBytes,
|
||||
signal,
|
||||
);
|
||||
if (
|
||||
verified.sha256 !== rootDigest.sha256 ||
|
||||
verified.bytes !== rootDigest.bytes
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Root artifact changed during inventory",
|
||||
);
|
||||
}
|
||||
const graphSha256 = digestCanonical({
|
||||
nodes: orderedNodes,
|
||||
occurrences: orderedOccurrences,
|
||||
edges: orderedEdges,
|
||||
});
|
||||
const manifestId = `agm_${digestCanonical({
|
||||
schema_version: 1,
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
graph_sha256: graphSha256,
|
||||
})}`;
|
||||
return artifactInventoryResultSchema.parse({
|
||||
manifest: {
|
||||
schema_version: 1,
|
||||
manifest_id: manifestId,
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
root_sha256: rootNode.sha256,
|
||||
root_format: rootNode.format,
|
||||
graph_sha256: graphSha256,
|
||||
node_count: orderedNodes.length,
|
||||
occurrence_count: orderedOccurrences.length,
|
||||
edge_count: orderedEdges.length,
|
||||
},
|
||||
nodes: pageOf(orderedNodes, page.nodeOffset, page.nodeLimit),
|
||||
occurrences: pageOf(
|
||||
orderedOccurrences,
|
||||
page.occurrenceOffset,
|
||||
page.occurrenceLimit,
|
||||
),
|
||||
edges: pageOf(orderedEdges, page.edgeOffset, page.edgeLimit),
|
||||
limits: toOutputLimits(limits),
|
||||
provenance: reader?.provenance() ?? [],
|
||||
limitations: inventoryLimitations(rootFormat, reader),
|
||||
});
|
||||
} finally {
|
||||
await reader?.close();
|
||||
}
|
||||
};
|
||||
|
||||
const inventoryLimitations = (
|
||||
format: ArtifactNode["format"],
|
||||
reader: ArtifactReader | undefined,
|
||||
): string[] => {
|
||||
if (reader !== undefined) return [];
|
||||
if (format === "dmg" || format === "pkg")
|
||||
return [
|
||||
`${format.toUpperCase()} root hash is observed; child inventory requires an approved native macOS adapter.`,
|
||||
];
|
||||
if (format === "mach-o-universal" && process.platform !== "darwin")
|
||||
return ["Universal Mach-O slices require the native macOS lipo adapter."];
|
||||
return ["Artifact has no child container entries."];
|
||||
};
|
||||
|
||||
const createReader = async (
|
||||
path: string,
|
||||
format: ArtifactNode["format"],
|
||||
): Promise<ArtifactReader | undefined> => {
|
||||
switch (format) {
|
||||
case "directory":
|
||||
return new DirectoryArtifactReader(path);
|
||||
case "zip":
|
||||
case "ipa":
|
||||
case "apk":
|
||||
return new ZipArtifactReader(path, format);
|
||||
case "asar":
|
||||
return new AsarArtifactReader(path);
|
||||
case "mach-o-universal":
|
||||
return process.platform === "darwin"
|
||||
? new MachOSliceArtifactReader(path)
|
||||
: undefined;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const scanReader = async (
|
||||
reader: ArtifactReader | undefined,
|
||||
limits: ArtifactLimits,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{
|
||||
readonly nodes: Map<string, ArtifactNode>;
|
||||
readonly occurrences: MutableOccurrence[];
|
||||
}> => {
|
||||
const nodes = new Map<string, ArtifactNode>();
|
||||
const occurrences: MutableOccurrence[] = [];
|
||||
if (reader === undefined) return { nodes, occurrences };
|
||||
const occurrenceByPath = new Map<string, MutableOccurrence>();
|
||||
const registry = new ArtifactPathRegistry();
|
||||
let totalBytes = 0;
|
||||
for await (const entry of reader.entries(signal)) {
|
||||
if (occurrences.length >= limits.maxEntries)
|
||||
throw new ArtifactReaderFailure("limit", "Artifact entry limit exceeded");
|
||||
const logicalPath = normalizeArtifactPath(entry.path, limits);
|
||||
registry.add(logicalPath, entry.kind);
|
||||
preflightEntry(entry, limits);
|
||||
const parent = nearestParent(logicalPath, occurrenceByPath);
|
||||
const occurrence = createOccurrence(
|
||||
entry,
|
||||
logicalPath,
|
||||
parent?.occurrence_id ?? null,
|
||||
);
|
||||
if ((entry.kind === "file" || entry.kind === "slice") && !entry.encrypted) {
|
||||
const remainingBytes = limits.maxTotalBytes - totalBytes;
|
||||
if (remainingBytes <= 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Artifact total byte limit exceeded",
|
||||
);
|
||||
if (entry.declaredSize !== null && entry.declaredSize > remainingBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Declared artifact bytes exceed remaining cumulative limit",
|
||||
);
|
||||
const digest = await hashReadable(
|
||||
await reader.open(entry, signal),
|
||||
Math.min(limits.maxEntryBytes, remainingBytes),
|
||||
signal,
|
||||
);
|
||||
totalBytes += digest.bytes;
|
||||
if (
|
||||
entry.declaredSha256 !== null &&
|
||||
entry.declaredSha256 !== digest.sha256
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
|
||||
);
|
||||
if (totalBytes > limits.maxTotalBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Artifact total byte limit exceeded",
|
||||
);
|
||||
const classified =
|
||||
entry.kind === "slice"
|
||||
? ({ kind: "universal-slice", format: "mach-o" } as const)
|
||||
: classifyArtifactContent(logicalPath, digest.prefix);
|
||||
const node = createArtifactNode({
|
||||
sha256: digest.sha256,
|
||||
size: digest.bytes,
|
||||
kind: classified.kind,
|
||||
format: classified.format,
|
||||
executable: entry.executable,
|
||||
contentState: "embedded",
|
||||
});
|
||||
nodes.set(node.artifact_id, node);
|
||||
occurrence.artifact_id = node.artifact_id;
|
||||
occurrence.hash_status = "verified";
|
||||
}
|
||||
occurrences.push(occurrence);
|
||||
occurrenceByPath.set(logicalPath, occurrence);
|
||||
}
|
||||
return { nodes, occurrences };
|
||||
};
|
||||
|
||||
const classifyRoot = async (
|
||||
path: string,
|
||||
directory: boolean,
|
||||
): Promise<ArtifactNode["format"]> => {
|
||||
if (directory) return "directory";
|
||||
const extensionFormat = classifyContainerExtension(path);
|
||||
if (extensionFormat !== undefined) return extensionFormat;
|
||||
const handle = await open(path, "r");
|
||||
try {
|
||||
const magic = Buffer.alloc(4);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
if (
|
||||
observed.bytesRead === 4 &&
|
||||
magic[0] === 0x50 &&
|
||||
magic[1] === 0x4b &&
|
||||
[0x03, 0x05, 0x07].includes(magic[2] ?? -1) &&
|
||||
[0x04, 0x06, 0x08].includes(magic[3] ?? -1)
|
||||
)
|
||||
return "zip";
|
||||
if (observed.bytesRead === 4) {
|
||||
const header = magic.readUInt32BE(0);
|
||||
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(header))
|
||||
return "mach-o-universal";
|
||||
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(header))
|
||||
return "mach-o";
|
||||
if (magic.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) return "elf";
|
||||
}
|
||||
if (observed.bytesRead >= 2 && magic[0] === 0x4d && magic[1] === 0x5a)
|
||||
return "pe";
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
return classifyArtifactPath(path).format;
|
||||
};
|
||||
|
||||
const classifyContainerExtension = (
|
||||
path: string,
|
||||
): ArtifactNode["format"] | undefined => {
|
||||
const lower = path.toLowerCase();
|
||||
for (const format of ["asar", "ipa", "apk", "zip", "dmg", "pkg"] as const)
|
||||
if (lower.endsWith(`.${format}`)) return format;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const preflightEntry = (entry: ArtifactEntry, limits: ArtifactLimits): void => {
|
||||
if (entry.declaredSize !== null && entry.declaredSize > limits.maxEntryBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Entry exceeds byte limit: ${entry.path}`,
|
||||
);
|
||||
if (
|
||||
entry.declaredSize !== null &&
|
||||
entry.compressedSize !== null &&
|
||||
entry.compressedSize === 0 &&
|
||||
entry.declaredSize > 0
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Invalid compression ratio: ${entry.path}`,
|
||||
);
|
||||
if (
|
||||
entry.declaredSize !== null &&
|
||||
entry.compressedSize !== null &&
|
||||
entry.compressedSize > 0 &&
|
||||
entry.declaredSize / entry.compressedSize > limits.maxCompressionRatio
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Compression ratio exceeds limit: ${entry.path}`,
|
||||
);
|
||||
};
|
||||
|
||||
const hashReadable = async (
|
||||
stream: Readable,
|
||||
maximum: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{
|
||||
readonly sha256: string;
|
||||
readonly bytes: number;
|
||||
readonly prefix: Buffer;
|
||||
}> => {
|
||||
const hash = createHash("sha256");
|
||||
const prefixes: Buffer[] = [];
|
||||
let prefixBytes = 0;
|
||||
let bytes = 0;
|
||||
for await (const raw of stream) {
|
||||
abortIfNeeded(signal);
|
||||
const chunk = streamChunkToBuffer(raw);
|
||||
bytes += chunk.length;
|
||||
if (bytes > maximum) {
|
||||
stream.destroy();
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Observed entry bytes exceed limit",
|
||||
);
|
||||
}
|
||||
hash.update(chunk);
|
||||
if (prefixBytes < 16) {
|
||||
const selected = chunk.subarray(0, 16 - prefixBytes);
|
||||
prefixes.push(selected);
|
||||
prefixBytes += selected.length;
|
||||
}
|
||||
}
|
||||
return { sha256: hash.digest("hex"), bytes, prefix: Buffer.concat(prefixes) };
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Artifact inventory cancelled",
|
||||
);
|
||||
};
|
||||
@@ -1,22 +1,47 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
HopperCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
AnalysisCancelledError,
|
||||
NoBinaryOpenError,
|
||||
type AnalysisError,
|
||||
} 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 { createEvidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisExecution,
|
||||
AnalysisClientFactory,
|
||||
AnalysisOperationPort,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { EvidenceLedger } from "./EvidenceLedger.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
ResidualUnknown,
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import { UnknownRegistryError } from "../domain/errors.js";
|
||||
import type { AnalysisOperation } from "./AnalysisProvider.js";
|
||||
import { enhancedToolNameSchema } from "../contracts/enhancedInputs.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
|
||||
const REGISTRY_PROVIDER: ProviderIdentity = {
|
||||
id: "rea-unknown-registry",
|
||||
name: "REA residual unknown registry",
|
||||
version: "1",
|
||||
};
|
||||
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
|
||||
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
|
||||
export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
@@ -30,10 +55,39 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
close(): Promise<Result<null, AnalysisError>>;
|
||||
status(): JsonValue;
|
||||
activeTarget(): BinaryTarget | undefined;
|
||||
recordEvidence(evidence: Evidence): void;
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError | EvidenceLimitError>;
|
||||
hasEvidence(evidenceId: string): boolean;
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
importEvidenceBundle(bundle: unknown): number;
|
||||
providerIdentity(): ProviderIdentity;
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError>;
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError>;
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
listUnknowns(filters?: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
}): ResidualUnknown[];
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
>;
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,7 +106,11 @@ export class BinarySession implements BinarySessionPort {
|
||||
readonly #calls = new Set<Promise<unknown>>();
|
||||
readonly #createClient: AnalysisClientFactory;
|
||||
readonly #providerIdentity: ProviderIdentity;
|
||||
readonly #evidence = new EvidenceLedger({ maxRecords: 10_000 });
|
||||
readonly #capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
|
||||
readonly #evidence = new EvidenceLedger({
|
||||
maxRecords: 10_000,
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
});
|
||||
|
||||
constructor(readonly provider: AnalysisProvider | AnalysisClientFactory) {
|
||||
this.#createClient =
|
||||
@@ -63,16 +121,56 @@ export class BinarySession implements BinarySessionPort {
|
||||
typeof provider === "function"
|
||||
? { id: "unidentified", name: "Unidentified provider", version: null }
|
||||
: provider.identity();
|
||||
this.#capabilities =
|
||||
typeof provider === "function"
|
||||
? undefined
|
||||
: new Map(
|
||||
provider
|
||||
.capabilities()
|
||||
.map((descriptor) => [descriptor.operation, descriptor]),
|
||||
);
|
||||
}
|
||||
|
||||
/** Identify the provider producing evidence for this session. */
|
||||
providerIdentity(): ProviderIdentity {
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
|
||||
if (operation !== undefined) {
|
||||
const exact = this.#capabilities?.get(operation)?.provider;
|
||||
if (exact !== undefined) return exact;
|
||||
if (enhancedToolNameSchema.safeParse(operation).success) {
|
||||
const providers = new Map<string, ProviderIdentity>();
|
||||
for (const descriptor of this.#capabilities?.values() ?? [])
|
||||
if (
|
||||
descriptor.available &&
|
||||
OFFICIAL_OPERATIONS.has(descriptor.operation)
|
||||
)
|
||||
providers.set(descriptor.provider.id, descriptor.provider);
|
||||
if (providers.size === 1) {
|
||||
const provider = providers.values().next().value;
|
||||
if (provider !== undefined) return provider;
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.#providerIdentity;
|
||||
}
|
||||
|
||||
/** Add one successful public observation to the session ledger. */
|
||||
recordEvidence(evidence: Evidence): void {
|
||||
this.#evidence.record(evidence);
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<
|
||||
"added" | "duplicate",
|
||||
EvidenceIntegrityError | EvidenceLimitError
|
||||
> {
|
||||
return this.#evidence.record(evidence);
|
||||
}
|
||||
|
||||
/** Check that comparison input Evidence is already session-owned. */
|
||||
hasEvidence(evidenceId: string): boolean {
|
||||
return this.#evidence.has(evidenceId);
|
||||
}
|
||||
|
||||
/** Read one detached session-owned Evidence record by semantic ID. */
|
||||
evidenceById(evidenceId: string): Evidence | undefined {
|
||||
return this.#evidence.get(evidenceId);
|
||||
}
|
||||
|
||||
/** Return a deterministic snapshot without clearing session evidence. */
|
||||
@@ -81,10 +179,77 @@ export class BinarySession implements BinarySessionPort {
|
||||
}
|
||||
|
||||
/** Atomically merge a validated evidence bundle into this session. */
|
||||
importEvidenceBundle(bundle: unknown): number {
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
|
||||
return this.#evidence.import(bundle);
|
||||
}
|
||||
|
||||
/** Create an approved residual unknown and immutable mutation evidence. */
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const evidence = unknownMutationEvidence(this.#active?.target, input);
|
||||
return this.#evidence.recordUnknown(input, evidence);
|
||||
}
|
||||
|
||||
/** Atomically record derived Evidence and its approved residual unknown. */
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError> {
|
||||
return this.#evidence.recordWithUnknown(
|
||||
evidence,
|
||||
input,
|
||||
unknownMutationEvidence(undefined, input),
|
||||
);
|
||||
}
|
||||
|
||||
/** Update one unknown using compare-and-swap revision semantics. */
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const evidence = createEvidence(this.#active?.target, REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "update_unknown",
|
||||
parameters: {
|
||||
unknown_id: input.unknown_id,
|
||||
expected_revision: input.expected_revision,
|
||||
},
|
||||
result: { action: "update", status: input.status },
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: unknownEvidenceLinks(input),
|
||||
limitations: [
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
return this.#evidence.updateUnknown(input, evidence);
|
||||
}
|
||||
|
||||
/** Query stable current residual-unknown heads. */
|
||||
listUnknowns(
|
||||
filters: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
} = {},
|
||||
): ResidualUnknown[] {
|
||||
return this.#evidence.listUnknowns(filters);
|
||||
}
|
||||
|
||||
/** Check whether current head is a bundle-valid resolved state. */
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
> {
|
||||
return this.#evidence.verifyUnknownResolution(unknownId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open or switch targets after draining calls against the current target.
|
||||
* Returns the switch failure even if best-effort restoration also fails.
|
||||
@@ -97,7 +262,8 @@ export class BinarySession implements BinarySessionPort {
|
||||
} = {},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#serialize(async () => {
|
||||
if (isAborted(options.signal)) return err(new HopperCancelledError());
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const parsed = await parseBinaryTarget(
|
||||
path,
|
||||
process.cwd(),
|
||||
@@ -105,7 +271,8 @@ export class BinarySession implements BinarySessionPort {
|
||||
options.targetKind,
|
||||
);
|
||||
if (!parsed.ok) return parsed;
|
||||
if (isAborted(options.signal)) return err(new HopperCancelledError());
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
if (this.#active?.target.path === parsed.value.path)
|
||||
return ok(parsed.value);
|
||||
await this.#drainCalls();
|
||||
@@ -122,7 +289,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
if (isAborted(options.signal)) {
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return err(new HopperCancelledError());
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
}
|
||||
this.#active = { target: parsed.value, client };
|
||||
return ok(parsed.value);
|
||||
@@ -144,10 +311,48 @@ export class BinarySession implements BinarySessionPort {
|
||||
/** Describe the active binary session. */
|
||||
status(): JsonValue {
|
||||
const target = this.#active?.target;
|
||||
const provider = {
|
||||
id: this.#providerIdentity.id,
|
||||
name: this.#providerIdentity.name,
|
||||
version: this.#providerIdentity.version,
|
||||
};
|
||||
const capabilities =
|
||||
this.#capabilities === undefined
|
||||
? []
|
||||
: [...this.#capabilities.values()]
|
||||
.sort((left, right) =>
|
||||
left.operation.localeCompare(right.operation),
|
||||
)
|
||||
.map((descriptor) => ({
|
||||
operation: descriptor.operation,
|
||||
available: descriptor.available,
|
||||
reason: descriptor.reason,
|
||||
input_contract_version: descriptor.inputContractVersion,
|
||||
output_contract_version: descriptor.outputContractVersion,
|
||||
pagination: descriptor.pagination,
|
||||
exhaustive: descriptor.exhaustive,
|
||||
effects: {
|
||||
mutates_artifact: descriptor.effects.mutatesArtifact,
|
||||
launches_process: descriptor.effects.launchesProcess,
|
||||
may_show_ui: descriptor.effects.mayShowUi,
|
||||
may_access_network: descriptor.effects.mayAccessNetwork,
|
||||
may_write_filesystem: descriptor.effects.mayWriteFilesystem,
|
||||
changes_permissions: descriptor.effects.changesPermissions,
|
||||
requires_root: descriptor.effects.requiresRoot,
|
||||
},
|
||||
limits: {
|
||||
max_results: descriptor.limits.maxResults,
|
||||
max_payload_bytes: descriptor.limits.maxPayloadBytes,
|
||||
timeout_ms: descriptor.limits.timeoutMs,
|
||||
},
|
||||
limitations: [...descriptor.limitations],
|
||||
}));
|
||||
return target === undefined
|
||||
? { open: false }
|
||||
? { open: false, provider, capabilities }
|
||||
: {
|
||||
open: true,
|
||||
provider,
|
||||
capabilities,
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
format: target.format,
|
||||
@@ -167,12 +372,21 @@ export class BinarySession implements BinarySessionPort {
|
||||
* entering until the transition has settled.
|
||||
*/
|
||||
async execute(
|
||||
name: string,
|
||||
name: Parameters<AnalysisOperationPort["execute"]>[0],
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
): Promise<Result<JsonValue, AnalysisError>> {
|
||||
const transitioned = await this.#waitForTransition(options?.signal);
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const transitioned = await this.#waitForTransition(name, options?.signal);
|
||||
if (!transitioned.ok) return transitioned;
|
||||
const capability = this.#capabilities?.get(name);
|
||||
if (this.#capabilities !== undefined && capability?.available !== true)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
this.#providerIdentity.id,
|
||||
name,
|
||||
capability?.reason ?? "operation is not declared by this provider",
|
||||
),
|
||||
);
|
||||
const active = this.#active;
|
||||
if (active === undefined) return err(new NoBinaryOpenError());
|
||||
const call = active.client.execute(name, arguments_, options);
|
||||
@@ -210,29 +424,35 @@ export class BinarySession implements BinarySessionPort {
|
||||
}
|
||||
|
||||
async #waitForTransition(
|
||||
operation: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<undefined, HopperCancelledError>> {
|
||||
if (signal?.aborted === true) return err(new HopperCancelledError());
|
||||
): Promise<Result<undefined, AnalysisCancelledError>> {
|
||||
if (signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
if (signal === undefined) {
|
||||
await this.#transition;
|
||||
return ok(undefined);
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const onAbort = (): void => {
|
||||
resolve(err(new HopperCancelledError()));
|
||||
resolve(err(new AnalysisCancelledError(operation)));
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
this.#transition.then(
|
||||
() => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(
|
||||
signal.aborted ? err(new HopperCancelledError()) : ok(undefined),
|
||||
signal.aborted
|
||||
? err(new AnalysisCancelledError(operation))
|
||||
: ok(undefined),
|
||||
);
|
||||
},
|
||||
() => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(
|
||||
signal.aborted ? err(new HopperCancelledError()) : ok(undefined),
|
||||
signal.aborted
|
||||
? err(new AnalysisCancelledError(operation))
|
||||
: ok(undefined),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -240,5 +460,41 @@ export class BinarySession implements BinarySessionPort {
|
||||
}
|
||||
}
|
||||
|
||||
const unknownMutationEvidence = (
|
||||
target: BinaryTarget | undefined,
|
||||
input: RecordUnknownInput,
|
||||
): Evidence =>
|
||||
createEvidence(target, REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "record_unknown",
|
||||
parameters: {
|
||||
domain: input.domain,
|
||||
severity: input.severity,
|
||||
},
|
||||
result: {
|
||||
action: "record",
|
||||
question: input.question,
|
||||
required_authority: input.required_authority,
|
||||
required_confidence: input.required_confidence,
|
||||
},
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: unknownEvidenceLinks(input),
|
||||
limitations: [
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
|
||||
const unknownEvidenceLinks = (
|
||||
input: RecordUnknownInput | UpdateUnknownInput,
|
||||
): string[] =>
|
||||
[
|
||||
...input.supporting_evidence_ids,
|
||||
...input.contradicting_evidence_ids,
|
||||
...("resolution" in input && input.resolution !== null
|
||||
? input.resolution.evidence_ids
|
||||
: []),
|
||||
].filter((id, index, values) => values.indexOf(id) === index);
|
||||
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { ProviderSelectionError } from "../domain/errors.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
|
||||
const compositeIdentity = (
|
||||
providers: readonly AnalysisProvider[],
|
||||
): ProviderIdentity => ({
|
||||
id: `composite:${providers
|
||||
.map((provider) => provider.identity().id)
|
||||
.sort()
|
||||
.join("+")}`,
|
||||
name: "REA composite analysis provider",
|
||||
version: null,
|
||||
});
|
||||
|
||||
/** Deterministically route disjoint operations without eagerly starting children. */
|
||||
export class CompositeProvider implements AnalysisProvider {
|
||||
readonly #identity: ProviderIdentity;
|
||||
readonly #capabilities: readonly CapabilityDescriptor[];
|
||||
readonly #providerByOperation: ReadonlyMap<string, AnalysisProvider>;
|
||||
|
||||
constructor(readonly providers: readonly AnalysisProvider[]) {
|
||||
if (providers.length === 0)
|
||||
throw new RangeError("CompositeProvider requires at least one provider");
|
||||
this.#identity = Object.freeze(compositeIdentity(providers));
|
||||
const routes = new Map<string, AnalysisProvider>();
|
||||
const capabilities: CapabilityDescriptor[] = [];
|
||||
for (const provider of providers) {
|
||||
for (const descriptor of provider.capabilities()) {
|
||||
if (routes.has(descriptor.operation))
|
||||
throw new TypeError(
|
||||
`Multiple providers declare operation ${descriptor.operation}`,
|
||||
);
|
||||
routes.set(descriptor.operation, provider);
|
||||
capabilities.push(descriptor);
|
||||
}
|
||||
}
|
||||
this.#providerByOperation = routes;
|
||||
this.#capabilities = Object.freeze(
|
||||
capabilities.sort(
|
||||
(left, right) =>
|
||||
left.operation.localeCompare(right.operation) ||
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
return this.#identity;
|
||||
}
|
||||
|
||||
capabilities(): readonly CapabilityDescriptor[] {
|
||||
return this.#capabilities;
|
||||
}
|
||||
|
||||
createClient(target: BinaryTarget): AnalysisClient {
|
||||
const clients = new Map<AnalysisProvider, AnalysisClient>();
|
||||
const clientFor = (provider: AnalysisProvider): AnalysisClient => {
|
||||
const existing = clients.get(provider);
|
||||
if (existing !== undefined) return existing;
|
||||
const created = provider.createClient(target);
|
||||
clients.set(provider, created);
|
||||
return created;
|
||||
};
|
||||
return {
|
||||
execute: (operation, parameters, options) => {
|
||||
if (operation === "health")
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
result: null,
|
||||
rawResult: null,
|
||||
provider: this.#identity,
|
||||
limitations: [],
|
||||
locations: [],
|
||||
subject: null,
|
||||
}),
|
||||
);
|
||||
const provider = this.#providerByOperation.get(operation);
|
||||
return provider === undefined
|
||||
? Promise.resolve(err(new ProviderSelectionError(operation)))
|
||||
: clientFor(provider).execute(operation, parameters, options);
|
||||
},
|
||||
close: async () => {
|
||||
await Promise.allSettled(
|
||||
[...clients.values()].map(async (client) => client.close()),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,15 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { createBinarySession } from "./runtime.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
|
||||
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
|
||||
|
||||
const WORKFLOW_PROVIDER = {
|
||||
id: "rea-workflow",
|
||||
name: "REA composed investigation workflow",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Open one binary, execute one tool, and always release the bridge session.
|
||||
@@ -14,6 +23,25 @@ export const runDirectAnalysis = async (
|
||||
tool: "binary_overview" | "procedure_pseudo_code",
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => runAnalysis(path, tool, arguments_, logger);
|
||||
|
||||
/** Execute one provider-native semantic operation with atomic provenance. */
|
||||
export const runProviderAnalysis = async (
|
||||
path: string,
|
||||
tool: NativeToolName | ArtifactToolName,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => runAnalysis(path, tool, arguments_, logger);
|
||||
|
||||
const runAnalysis = async (
|
||||
path: string,
|
||||
tool:
|
||||
| NativeToolName
|
||||
| ArtifactToolName
|
||||
| "binary_overview"
|
||||
| "procedure_pseudo_code",
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger,
|
||||
): Promise<JsonValue> => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
@@ -23,13 +51,32 @@ export const runDirectAnalysis = async (
|
||||
const opened = await session.open(path);
|
||||
if (!opened.ok)
|
||||
return { error: opened.error._tag, message: opened.error.message };
|
||||
if (tool === "binary_overview") {
|
||||
const result = await new EnhancedTools(session).execute(tool, arguments_);
|
||||
return result.ok
|
||||
? createEvidence(opened.value, WORKFLOW_PROVIDER, {
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
confidence: "derived",
|
||||
limitations: ["Derived by an REA composed workflow."],
|
||||
})
|
||||
: { error: result.error._tag, message: result.error.message };
|
||||
}
|
||||
const result = await session.execute(tool, arguments_);
|
||||
return result.ok
|
||||
? createEvidence(opened.value, session.providerIdentity(), {
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
})
|
||||
? createEvidence(
|
||||
result.value.subject ?? opened.value,
|
||||
result.value.provider,
|
||||
{
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value.result,
|
||||
rawResult: result.value.rawResult,
|
||||
limitations: result.value.limitations,
|
||||
locations: result.value.locations,
|
||||
},
|
||||
)
|
||||
: { error: result.error._tag, message: result.error.message };
|
||||
} finally {
|
||||
await session.close();
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import { AnalysisProtocolError, type AnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
parseDocuments,
|
||||
parseFunctionDossier,
|
||||
@@ -384,12 +391,18 @@ export class EnhancedTools {
|
||||
if (!xrefs.ok) return xrefs;
|
||||
if (!Array.isArray(xrefs.value))
|
||||
return err(
|
||||
new AnalysisProtocolError("xrefs returned a non-array result"),
|
||||
new AnalysisOutputError(
|
||||
"xrefs",
|
||||
"provider returned a non-array result",
|
||||
),
|
||||
);
|
||||
for (const source of xrefs.value) {
|
||||
if (typeof source !== "string")
|
||||
return err(
|
||||
new AnalysisProtocolError("xrefs returned a non-address value"),
|
||||
new AnalysisOutputError(
|
||||
"xrefs",
|
||||
"provider returned a non-address value",
|
||||
),
|
||||
);
|
||||
if (operations >= operationBudget) {
|
||||
residual.add(
|
||||
@@ -444,8 +457,9 @@ export class EnhancedTools {
|
||||
}
|
||||
if (page.value.nextOffset <= offset) {
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
`${tool} returned a non-advancing pagination offset`,
|
||||
new AnalysisOutputError(
|
||||
tool,
|
||||
"provider returned a non-advancing pagination offset",
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -453,23 +467,24 @@ export class EnhancedTools {
|
||||
}
|
||||
}
|
||||
|
||||
#call(
|
||||
name: string,
|
||||
async #call(
|
||||
name: AnalysisOperation,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<JsonValue, AnalysisError>> {
|
||||
return this.analysis.execute(
|
||||
const execution = await this.analysis.execute(
|
||||
name,
|
||||
arguments_,
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
return execution.ok ? ok(execution.value.result) : execution;
|
||||
}
|
||||
}
|
||||
|
||||
const invalidInput = (name: EnhancedToolName, cause: Error): EnhancedResult =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new AnalysisProtocolError(`Invalid ${name} input after MCP validation`, {
|
||||
new AnalysisInputError(name, {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type {
|
||||
EvidenceFilePolicy,
|
||||
EvidenceBundle,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { EvidenceLedger } from "./EvidenceLedger.js";
|
||||
import {
|
||||
readEvidenceBundle,
|
||||
writeEvidenceBundle,
|
||||
} from "./EvidenceBundleFiles.js";
|
||||
|
||||
/** Validate and merge one bundle using the same bounded ledger as MCP. */
|
||||
export const importEvidenceBundleCommand = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const loaded = await readEvidenceBundle(path, policy);
|
||||
if (!loaded.ok) return loaded;
|
||||
const ledger = createLedger();
|
||||
const imported = ledger.import(loaded.value);
|
||||
return imported.ok
|
||||
? ok({ imported: imported.value, total: ledger.export().records.length })
|
||||
: imported;
|
||||
};
|
||||
|
||||
/** Validate a source bundle and atomically export canonical bytes. */
|
||||
export const exportEvidenceBundleCommand = async (
|
||||
sourcePath: string,
|
||||
outputPath: string,
|
||||
overwrite: boolean,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const loaded = await readEvidenceBundle(sourcePath, policy);
|
||||
if (!loaded.ok) return loaded;
|
||||
return projectWrite(
|
||||
loaded.value,
|
||||
await writeEvidenceBundle(loaded.value, outputPath, overwrite, policy),
|
||||
);
|
||||
};
|
||||
|
||||
const createLedger = (): EvidenceLedger =>
|
||||
new EvidenceLedger({ maxRecords: 10_000, maxBytes: 64 * 1024 * 1024 });
|
||||
|
||||
const projectWrite = (
|
||||
bundle: EvidenceBundle,
|
||||
written: Awaited<ReturnType<typeof writeEvidenceBundle>>,
|
||||
): Result<JsonValue, AnalysisError> =>
|
||||
written.ok
|
||||
? ok({
|
||||
path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
records: bundle.records.length,
|
||||
})
|
||||
: err(written.error);
|
||||
@@ -0,0 +1,159 @@
|
||||
import { lstat, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import {
|
||||
parseEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
type EvidenceBundle,
|
||||
type EvidenceFilePolicy,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import { EvidenceFileError, EvidenceIntegrityError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
type EvidenceWriteFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
|
||||
/** Read and validate a bounded evidence bundle inside an approved root. */
|
||||
export const readEvidenceBundle = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new EvidenceFileError("read", "disabled"));
|
||||
try {
|
||||
const canonicalPath = await realpath(resolve(path));
|
||||
if (!(await isApproved(canonicalPath, policy.roots)))
|
||||
return err(new EvidenceFileError("read", "outside-root"));
|
||||
const stats = await lstat(canonicalPath);
|
||||
if (!stats.isFile()) return err(new EvidenceFileError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
const encoded = await readFile(canonicalPath);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "invalid-json", { cause }));
|
||||
}
|
||||
const limits = validateJsonLimits(decoded, policy);
|
||||
if (!limits.ok) return limits;
|
||||
try {
|
||||
return ok(parseEvidenceBundle(decoded));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomically write deterministic evidence JSON inside an approved root. */
|
||||
export const writeEvidenceBundle = async (
|
||||
bundle: EvidenceBundle,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly path: string; readonly bytes: number },
|
||||
EvidenceWriteFailure
|
||||
>
|
||||
> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new EvidenceFileError("write", "disabled"));
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = serializeEvidenceBundle(bundle);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new EvidenceFileError("write", "too-large"));
|
||||
try {
|
||||
const canonicalParent = await realpath(dirname(resolve(path)));
|
||||
const destination = resolve(canonicalParent, basename(resolve(path)));
|
||||
if (!(await isApproved(destination, policy.roots)))
|
||||
return err(new EvidenceFileError("write", "outside-root"));
|
||||
const existing = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (existing !== undefined) {
|
||||
if (!overwrite) return err(new EvidenceFileError("write", "exists"));
|
||||
if (!existing.isFile() || existing.isSymbolicLink())
|
||||
return err(new EvidenceFileError("write", "not-file"));
|
||||
}
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: destination, bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("write", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const isApproved = async (
|
||||
candidate: string,
|
||||
roots: readonly string[],
|
||||
): Promise<boolean> => {
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
const relation = relative(root, candidate);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const validateJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Result<null, EvidenceFileError> => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT";
|
||||
@@ -1,68 +1,392 @@
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
evidenceBundleSchema,
|
||||
parseEvidenceBundle,
|
||||
type EvidenceBundle,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
UnknownRegistryError,
|
||||
} from "../domain/errors.js";
|
||||
import { parseEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
updateResidualUnknown,
|
||||
type RecordUnknownInput,
|
||||
type ResidualUnknown,
|
||||
type UnknownStatus,
|
||||
type UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
export interface EvidenceLedgerLimits {
|
||||
readonly maxRecords: number;
|
||||
readonly maxBytes: number;
|
||||
}
|
||||
|
||||
type EvidenceLedgerFailure = EvidenceIntegrityError | EvidenceLimitError;
|
||||
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
|
||||
type ImportResult = Result<number, EvidenceLedgerFailure>;
|
||||
|
||||
/** Bounded, session-owned set of immutable evidence records. */
|
||||
export class EvidenceLedger {
|
||||
readonly #records = new Map<string, Evidence>();
|
||||
readonly #unknownRevisions = new Map<string, ResidualUnknown>();
|
||||
readonly #unknownHeads = new Map<string, ResidualUnknown>();
|
||||
#bytes = 0;
|
||||
|
||||
constructor(private readonly limits: EvidenceLedgerLimits) {
|
||||
if (!Number.isSafeInteger(limits.maxRecords) || limits.maxRecords < 1)
|
||||
throw new RangeError("maxRecords must be a positive safe integer");
|
||||
if (!Number.isSafeInteger(limits.maxBytes) || limits.maxBytes < 1)
|
||||
throw new RangeError("maxBytes must be a positive safe integer");
|
||||
}
|
||||
|
||||
/** Record evidence idempotently; conflicting content is rejected. */
|
||||
record(input: Evidence): "added" | "duplicate" {
|
||||
const evidence = parseEvidence(input);
|
||||
record(input: Evidence): RecordResult {
|
||||
let evidence: Evidence;
|
||||
try {
|
||||
evidence = parseEvidence(input);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence record validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
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";
|
||||
return recordsAgree(existing, evidence)
|
||||
? ok("duplicate")
|
||||
: err(new EvidenceIntegrityError("Conflicting evidence record"));
|
||||
}
|
||||
if (this.#records.size >= this.limits.maxRecords)
|
||||
throw new RangeError("Evidence ledger record limit exceeded");
|
||||
return err(new EvidenceLimitError("records", this.limits.maxRecords));
|
||||
const bytes = serializedBytes(evidence);
|
||||
if (this.#bytes + bytes > this.limits.maxBytes)
|
||||
return err(new EvidenceLimitError("bytes", this.limits.maxBytes));
|
||||
this.#records.set(evidence.evidence_id, evidence);
|
||||
return "added";
|
||||
this.#bytes += bytes;
|
||||
return ok("added");
|
||||
}
|
||||
|
||||
/** Validate an entire bundle before atomically merging its records. */
|
||||
import(input: unknown): number {
|
||||
const bundle = evidenceBundleSchema.parse(input);
|
||||
import(input: unknown): ImportResult {
|
||||
let bundle: EvidenceBundle;
|
||||
try {
|
||||
bundle = parseEvidenceBundle(input);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const pending = new Map(this.#records);
|
||||
for (const unparsed of bundle.records) {
|
||||
const evidence = parseEvidence(unparsed);
|
||||
for (const evidence of bundle.records) {
|
||||
const existing = pending.get(evidence.evidence_id);
|
||||
if (existing !== undefined && !recordsAgree(existing, evidence))
|
||||
throw new Error(`Conflicting evidence record: ${evidence.evidence_id}`);
|
||||
return err(new EvidenceIntegrityError("Conflicting evidence record"));
|
||||
pending.set(evidence.evidence_id, evidence);
|
||||
}
|
||||
if (pending.size > this.limits.maxRecords)
|
||||
throw new RangeError("Evidence ledger record limit exceeded");
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
for (const unknown of bundle.unknowns) {
|
||||
const key = unknownRevisionKey(unknown);
|
||||
const existing = pendingUnknowns.get(key);
|
||||
if (
|
||||
existing !== undefined &&
|
||||
existing.revision_digest !== unknown.revision_digest
|
||||
)
|
||||
return err(new EvidenceIntegrityError("Conflicting unknown revision"));
|
||||
pendingUnknowns.set(key, unknown);
|
||||
}
|
||||
const checked = this.#validateCandidate(pending, pendingUnknowns);
|
||||
if (!checked.ok) {
|
||||
if (checked.error instanceof UnknownRegistryError)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Evidence bundle unknown registry failed",
|
||||
{
|
||||
cause: checked.error,
|
||||
},
|
||||
),
|
||||
);
|
||||
return err(checked.error);
|
||||
}
|
||||
const added = pending.size - this.#records.size;
|
||||
this.#records.clear();
|
||||
for (const [id, evidence] of pending) this.#records.set(id, evidence);
|
||||
return added;
|
||||
this.#commit(pending, pendingUnknowns, checked.value);
|
||||
return ok(added);
|
||||
}
|
||||
|
||||
/** Export records in deterministic, semantically irrelevant ID order. */
|
||||
export(): EvidenceBundle {
|
||||
return createEvidenceBundle([...this.#records.values()]);
|
||||
return createEvidenceBundle(
|
||||
[...this.#records.values()],
|
||||
[...this.#unknownRevisions.values()],
|
||||
);
|
||||
}
|
||||
|
||||
/** Check whether one immutable Evidence ID is present in this ledger. */
|
||||
has(evidenceId: string): boolean {
|
||||
return this.#records.has(evidenceId);
|
||||
}
|
||||
|
||||
/** Return a detached immutable Evidence value by semantic ID. */
|
||||
get(evidenceId: string): Evidence | undefined {
|
||||
const evidence = this.#records.get(evidenceId);
|
||||
return evidence === undefined ? undefined : structuredClone(evidence);
|
||||
}
|
||||
|
||||
/** Create one approved unknown and atomically append its mutation evidence. */
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
mutationEvidence: Evidence,
|
||||
): Result<
|
||||
ResidualUnknown,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
let parsedMutation: Evidence;
|
||||
try {
|
||||
parsedMutation = parseEvidence(mutationEvidence);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
let unknown: ResidualUnknown;
|
||||
try {
|
||||
unknown = createResidualUnknown(
|
||||
input,
|
||||
parsedMutation.evidence_id,
|
||||
parsedMutation.subject?.digest.sha256 ?? null,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("invalid-transition", { cause }));
|
||||
}
|
||||
if (this.#unknownHeads.has(unknown.unknown_id))
|
||||
return err(new UnknownRegistryError("already-exists"));
|
||||
return this.#appendUnknown(unknown, parsedMutation);
|
||||
}
|
||||
|
||||
/** Atomically record derived Evidence and an approved residual unknown. */
|
||||
recordWithUnknown(
|
||||
evidenceInput: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
mutationInput: Evidence,
|
||||
): Result<
|
||||
ResidualUnknown | null,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
let evidence: Evidence;
|
||||
let mutation: Evidence;
|
||||
try {
|
||||
evidence = parseEvidence(evidenceInput);
|
||||
mutation = parseEvidence(mutationInput);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Atomic Evidence validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const existingEvidence = this.#records.get(evidence.evidence_id);
|
||||
if (
|
||||
existingEvidence !== undefined &&
|
||||
!recordsAgree(existingEvidence, evidence)
|
||||
)
|
||||
return err(new EvidenceIntegrityError("Conflicting evidence record"));
|
||||
let unknown: ResidualUnknown;
|
||||
try {
|
||||
unknown = createResidualUnknown(
|
||||
input,
|
||||
mutation.evidence_id,
|
||||
mutation.subject?.digest.sha256 ?? null,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("invalid-transition", { cause }));
|
||||
}
|
||||
const pendingRecords = new Map(this.#records);
|
||||
pendingRecords.set(evidence.evidence_id, evidence);
|
||||
const existingUnknown = this.#unknownHeads.get(unknown.unknown_id);
|
||||
if (existingUnknown !== undefined) {
|
||||
if (
|
||||
existingUnknown.revision !== 1 ||
|
||||
existingUnknown.revision_digest !== unknown.revision_digest
|
||||
)
|
||||
return err(new UnknownRegistryError("already-exists"));
|
||||
const checked = this.#validateCandidate(
|
||||
pendingRecords,
|
||||
this.#unknownRevisions,
|
||||
);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, this.#unknownRevisions, checked.value);
|
||||
return ok(null);
|
||||
}
|
||||
pendingRecords.set(mutation.evidence_id, mutation);
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
pendingUnknowns.set(unknownRevisionKey(unknown), unknown);
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(unknown);
|
||||
}
|
||||
|
||||
/** Apply one approved full-state update using optimistic revision matching. */
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
mutationEvidence: Evidence,
|
||||
): Result<
|
||||
ResidualUnknown,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
const current = this.#unknownHeads.get(input.unknown_id);
|
||||
if (current === undefined)
|
||||
return err(new UnknownRegistryError("not-found"));
|
||||
if (current.revision !== input.expected_revision)
|
||||
return err(new UnknownRegistryError("revision-conflict"));
|
||||
let unknown: ResidualUnknown;
|
||||
try {
|
||||
unknown = updateResidualUnknown(
|
||||
current,
|
||||
input,
|
||||
mutationEvidence.evidence_id,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("invalid-transition", { cause }));
|
||||
}
|
||||
return this.#appendUnknown(unknown, mutationEvidence);
|
||||
}
|
||||
|
||||
/** Query current heads in stable ID order. */
|
||||
listUnknowns(
|
||||
filters: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
} = {},
|
||||
): ResidualUnknown[] {
|
||||
return [...this.#unknownHeads.values()]
|
||||
.filter(
|
||||
(unknown) =>
|
||||
(filters.status === undefined || unknown.status === filters.status) &&
|
||||
(filters.severity === undefined ||
|
||||
unknown.severity === filters.severity) &&
|
||||
(filters.domain === undefined || unknown.domain === filters.domain),
|
||||
)
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id));
|
||||
}
|
||||
|
||||
/** Return current resolution validity; imported invalid states are rejected. */
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
> {
|
||||
const unknown = this.#unknownHeads.get(unknownId);
|
||||
if (unknown === undefined)
|
||||
return err(new UnknownRegistryError("not-found"));
|
||||
return ok({
|
||||
valid: unknown.status === "resolved",
|
||||
truthVerified: unknown.resolution?.disposition === "verified",
|
||||
unknown,
|
||||
});
|
||||
}
|
||||
|
||||
/** Clear records when the owning session closes. */
|
||||
clear(): void {
|
||||
this.#records.clear();
|
||||
this.#unknownRevisions.clear();
|
||||
this.#unknownHeads.clear();
|
||||
this.#bytes = 0;
|
||||
}
|
||||
|
||||
#appendUnknown(
|
||||
unknown: ResidualUnknown,
|
||||
mutationEvidenceInput: Evidence,
|
||||
): Result<
|
||||
ResidualUnknown,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
let mutationEvidence: Evidence;
|
||||
try {
|
||||
mutationEvidence = parseEvidence(mutationEvidenceInput);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const pendingRecords = new Map(this.#records);
|
||||
pendingRecords.set(mutationEvidence.evidence_id, mutationEvidence);
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
pendingUnknowns.set(unknownRevisionKey(unknown), unknown);
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(unknown);
|
||||
}
|
||||
|
||||
#validateCandidate(
|
||||
records: ReadonlyMap<string, Evidence>,
|
||||
unknowns: ReadonlyMap<string, ResidualUnknown>,
|
||||
): Result<
|
||||
number,
|
||||
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
|
||||
> {
|
||||
if (records.size + unknowns.size > this.limits.maxRecords)
|
||||
return err(new EvidenceLimitError("records", this.limits.maxRecords));
|
||||
const bytes =
|
||||
[...records.values()].reduce(
|
||||
(total, evidence) => total + serializedBytes(evidence),
|
||||
0,
|
||||
) +
|
||||
[...unknowns.values()].reduce(
|
||||
(total, unknown) => total + serializedBytes(unknown),
|
||||
0,
|
||||
);
|
||||
if (bytes > this.limits.maxBytes)
|
||||
return err(new EvidenceLimitError("bytes", this.limits.maxBytes));
|
||||
try {
|
||||
parseEvidenceBundle(
|
||||
createEvidenceBundle([...records.values()], [...unknowns.values()]),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("integrity", { cause }));
|
||||
}
|
||||
return ok(bytes);
|
||||
}
|
||||
|
||||
#commit(
|
||||
records: ReadonlyMap<string, Evidence>,
|
||||
unknowns: ReadonlyMap<string, ResidualUnknown>,
|
||||
bytes: number,
|
||||
): void {
|
||||
this.#records.clear();
|
||||
for (const [id, evidence] of records) this.#records.set(id, evidence);
|
||||
this.#unknownRevisions.clear();
|
||||
this.#unknownHeads.clear();
|
||||
for (const [key, unknown] of unknowns) {
|
||||
this.#unknownRevisions.set(key, unknown);
|
||||
const head = this.#unknownHeads.get(unknown.unknown_id);
|
||||
if (head === undefined || head.revision < unknown.revision)
|
||||
this.#unknownHeads.set(unknown.unknown_id, unknown);
|
||||
}
|
||||
this.#bytes = bytes;
|
||||
}
|
||||
}
|
||||
|
||||
const serializedBytes = (value: Evidence | ResidualUnknown): number =>
|
||||
Buffer.byteLength(JSON.stringify(value), "utf8");
|
||||
|
||||
const unknownRevisionKey = (unknown: ResidualUnknown): string =>
|
||||
`${unknown.unknown_id}:${String(unknown.revision)}`;
|
||||
|
||||
const recordsAgree = (left: Evidence, right: Evidence): boolean =>
|
||||
JSON.stringify(withoutLocalPath(left)) ===
|
||||
JSON.stringify(withoutLocalPath(right));
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { lstat, open, readdir, readlink } from "node:fs/promises";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import type { FileState, ProcessScenario } from "../domain/processCapture.js";
|
||||
|
||||
export interface SnapshotResult {
|
||||
readonly files: readonly FileState[];
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
|
||||
|
||||
const hashFile = async (
|
||||
path: string,
|
||||
maxBytes: number,
|
||||
): Promise<string | null> => {
|
||||
const handle = await open(
|
||||
path,
|
||||
fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0),
|
||||
);
|
||||
try {
|
||||
const stats = await handle.stat();
|
||||
if (!stats.isFile() || stats.size > maxBytes) return null;
|
||||
return createHash("sha256")
|
||||
.update(await handle.readFile())
|
||||
.digest("hex");
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Capture bounded, root-aliased filesystem state without following symlinks. */
|
||||
export const snapshotRoots = async (
|
||||
scenario: ProcessScenario,
|
||||
): Promise<SnapshotResult> => {
|
||||
const entries: FileState[] = [];
|
||||
let remainingBytes = scenario.limits.file_bytes;
|
||||
let truncated = false;
|
||||
const visit = async (
|
||||
root: string,
|
||||
rootAlias: string,
|
||||
path: string,
|
||||
depth: number,
|
||||
): Promise<void> => {
|
||||
if (
|
||||
entries.length >= scenario.limits.files ||
|
||||
depth > scenario.limits.filesystem_depth
|
||||
) {
|
||||
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()) {
|
||||
const target = resolve(dirname(path), await readlink(path));
|
||||
const safeTarget = isWithin(target, root)
|
||||
? relative(root, target) || "."
|
||||
: "<outside-declared-root>";
|
||||
if (safeTarget === "<outside-declared-root>") truncated = true;
|
||||
entries.push({
|
||||
path: `${rootAlias}:${relativePath}`,
|
||||
type: "symlink",
|
||||
mode: stats.mode,
|
||||
size: stats.size,
|
||||
sha256: null,
|
||||
symlink_target: safeTarget,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (stats.isFile()) {
|
||||
const sha256 =
|
||||
remainingBytes >= stats.size
|
||||
? await hashFile(path, remainingBytes)
|
||||
: null;
|
||||
remainingBytes -= sha256 === null ? 0 : stats.size;
|
||||
if (sha256 === null) truncated = true;
|
||||
entries.push({
|
||||
path: `${rootAlias}:${relativePath}`,
|
||||
type: "file",
|
||||
mode: stats.mode,
|
||||
size: stats.size,
|
||||
sha256,
|
||||
symlink_target: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const type = stats.isDirectory() ? "directory" : "other";
|
||||
entries.push({
|
||||
path: `${rootAlias}:${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, rootAlias, join(path, child), depth + 1);
|
||||
};
|
||||
for (const [index, root] of scenario.filesystem_roots.entries())
|
||||
await visit(root, `root_${String(index)}`, root, 0);
|
||||
return { files: entries, truncated };
|
||||
};
|
||||
@@ -1,4 +1,9 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from "node:http";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
import type {
|
||||
ProcessScenario,
|
||||
@@ -10,46 +15,203 @@ export interface LoopbackReplay {
|
||||
readonly httpUrl: string;
|
||||
readonly websocketUrl: string;
|
||||
readonly events: ProtocolEvent[];
|
||||
readonly truncated: boolean;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
const closeServer = async (server: Server): Promise<void> =>
|
||||
new Promise((resolveClose, rejectClose) => {
|
||||
server.close((error) =>
|
||||
error === undefined ? resolveClose() : rejectClose(error),
|
||||
);
|
||||
});
|
||||
class ReplayRecorder {
|
||||
readonly events: ProtocolEvent[] = [];
|
||||
readonly started = Date.now();
|
||||
truncated = false;
|
||||
|
||||
/** 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) => {
|
||||
constructor(readonly scenario: ProcessScenario) {}
|
||||
|
||||
atMs(): number {
|
||||
return (
|
||||
Math.floor(
|
||||
(Date.now() - this.started) /
|
||||
this.scenario.normalization.time_bucket_ms,
|
||||
) * this.scenario.normalization.time_bucket_ms
|
||||
);
|
||||
}
|
||||
|
||||
record(event: Omit<ProtocolEvent, "sequence">): void {
|
||||
if (this.events.length < this.scenario.limits.protocol_events)
|
||||
this.events.push({ sequence: this.events.length, ...event });
|
||||
else this.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
const readRequestBody = async (
|
||||
request: IncomingMessage,
|
||||
limit: number,
|
||||
): Promise<string | undefined> => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
for await (const chunk of request) {
|
||||
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
bytes += value.byteLength;
|
||||
if (bytes > limit) return undefined;
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
};
|
||||
|
||||
const createHttpHandler = (
|
||||
recorder: ReplayRecorder,
|
||||
): ((request: IncomingMessage, response: ServerResponse) => Promise<void>) => {
|
||||
const calls = new Map<number, number>();
|
||||
return async (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,
|
||||
const body = await readRequestBody(
|
||||
request,
|
||||
recorder.scenario.limits.protocol_body_bytes,
|
||||
);
|
||||
response.statusCode = route?.status ?? 404;
|
||||
const body = route?.body ?? "";
|
||||
response.end(body);
|
||||
record({
|
||||
if (body === undefined) {
|
||||
recorder.truncated = true;
|
||||
response.statusCode = 413;
|
||||
response.end();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method,
|
||||
path,
|
||||
data: "<body-over-limit>",
|
||||
outcome: "unmatched",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const index = recorder.scenario.replay.http.findIndex((route) => {
|
||||
if (route.method !== method || route.path !== path) return false;
|
||||
if (route.request_body !== undefined && route.request_body !== body)
|
||||
return false;
|
||||
return Object.entries(route.request_headers).every(
|
||||
([name, value]) => request.headers[name.toLowerCase()] === value,
|
||||
);
|
||||
});
|
||||
const route = recorder.scenario.replay.http[index];
|
||||
const used = index < 0 ? 0 : (calls.get(index) ?? 0);
|
||||
const outcome =
|
||||
route === undefined
|
||||
? "unmatched"
|
||||
: used >= route.max_calls
|
||||
? "script_exhausted"
|
||||
: "matched";
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method,
|
||||
path,
|
||||
data: body.length === 0 ? "" : "<redacted-request-body>",
|
||||
outcome,
|
||||
});
|
||||
if (route === undefined || outcome === "script_exhausted") {
|
||||
response.statusCode = route === undefined ? 404 : 409;
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
calls.set(index, used + 1);
|
||||
if (route.delay_ms > 0)
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, route.delay_ms),
|
||||
);
|
||||
if (route.disconnect) {
|
||||
response.destroy();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method,
|
||||
path,
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
});
|
||||
return;
|
||||
}
|
||||
response.statusCode = route.status;
|
||||
for (const [name, value] of Object.entries(route.response_headers))
|
||||
response.setHeader(name, value);
|
||||
response.end(route.body);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "http",
|
||||
direction: "response",
|
||||
method,
|
||||
path,
|
||||
data: body,
|
||||
data: route.body,
|
||||
outcome: "matched",
|
||||
});
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
const sendWebSocketScript = async (
|
||||
client: WebSocket,
|
||||
connection: number,
|
||||
recorder: ReplayRecorder,
|
||||
): Promise<void> => {
|
||||
const scripts = recorder.scenario.replay.websocket_connections;
|
||||
const script = scripts[connection - 1];
|
||||
if (scripts.length > 0 && script === undefined) {
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "script_exhausted",
|
||||
});
|
||||
client.terminate();
|
||||
return;
|
||||
}
|
||||
const messages =
|
||||
script?.messages ??
|
||||
recorder.scenario.replay.websocket_messages.map((data) => ({
|
||||
data,
|
||||
delay_ms: 0,
|
||||
}));
|
||||
for (const message of messages) {
|
||||
if (message.delay_ms > 0)
|
||||
await new Promise((resolveDelay) =>
|
||||
setTimeout(resolveDelay, message.delay_ms),
|
||||
);
|
||||
if (client.readyState !== 1) return;
|
||||
client.send(message.data);
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: message.data,
|
||||
outcome: "matched",
|
||||
});
|
||||
}
|
||||
if (script?.disconnect_after === true) {
|
||||
client.close();
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "",
|
||||
outcome: "disconnected",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const createWebSocketReplay = (
|
||||
server: Server,
|
||||
recorder: ReplayRecorder,
|
||||
): WebSocketServer => {
|
||||
let connections = 0;
|
||||
const websocket = new WebSocketServer({
|
||||
noServer: true,
|
||||
maxPayload: 1_000_000,
|
||||
maxPayload: recorder.scenario.limits.protocol_body_bytes,
|
||||
clientTracking: true,
|
||||
});
|
||||
server.on("upgrade", (request, socket, head) => {
|
||||
@@ -62,27 +224,30 @@ export const startLoopbackReplay = async (
|
||||
);
|
||||
});
|
||||
websocket.on("connection", (client: WebSocket) => {
|
||||
connections += 1;
|
||||
if (connections > recorder.scenario.limits.connections) {
|
||||
recorder.truncated = true;
|
||||
client.terminate();
|
||||
return;
|
||||
}
|
||||
client.on("error", () => undefined);
|
||||
client.on("message", (value) =>
|
||||
record({
|
||||
recorder.record({
|
||||
at_ms: recorder.atMs(),
|
||||
protocol: "websocket",
|
||||
direction: "received",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: value.toString(),
|
||||
outcome: "matched",
|
||||
}),
|
||||
);
|
||||
for (const message of scenario.replay.websocket_messages) {
|
||||
client.send(message);
|
||||
record({
|
||||
protocol: "websocket",
|
||||
direction: "sent",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: message,
|
||||
});
|
||||
}
|
||||
void sendWebSocketScript(client, connections, recorder);
|
||||
});
|
||||
return websocket;
|
||||
};
|
||||
|
||||
const listen = async (server: Server): Promise<number> => {
|
||||
await new Promise<void>((resolveListen, rejectListen) => {
|
||||
server.once("error", rejectListen);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
@@ -91,14 +256,39 @@ export const startLoopbackReplay = async (
|
||||
});
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string") {
|
||||
await closeServer(server);
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("loopback replay did not acquire a TCP port");
|
||||
return address.port;
|
||||
};
|
||||
|
||||
const closeServer = (server: Server): Promise<void> =>
|
||||
new Promise((resolveClose, rejectClose) => {
|
||||
server.close((error) =>
|
||||
error === undefined ? resolveClose() : rejectClose(error),
|
||||
);
|
||||
});
|
||||
|
||||
/** Start bounded HTTP and WebSocket replay endpoints on IPv4 loopback only. */
|
||||
export const startLoopbackReplay = async (
|
||||
scenario: ProcessScenario,
|
||||
): Promise<LoopbackReplay> => {
|
||||
const recorder = new ReplayRecorder(scenario);
|
||||
const server = createServer(createHttpHandler(recorder));
|
||||
const websocket = createWebSocketReplay(server, recorder);
|
||||
let port: number;
|
||||
try {
|
||||
port = await listen(server);
|
||||
} catch (cause: unknown) {
|
||||
await closeServer(server).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
httpUrl: `http://127.0.0.1:${String(address.port)}`,
|
||||
websocketUrl: `ws://127.0.0.1:${String(address.port)}/ws`,
|
||||
events,
|
||||
httpUrl: `http://127.0.0.1:${String(port)}`,
|
||||
websocketUrl: `ws://127.0.0.1:${String(port)}/ws`,
|
||||
events: recorder.events,
|
||||
get truncated() {
|
||||
return recorder.truncated;
|
||||
},
|
||||
async close() {
|
||||
for (const client of websocket.clients) client.terminate();
|
||||
await new Promise<void>((resolveClose) =>
|
||||
|
||||
+236
-252
@@ -1,17 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
readdir,
|
||||
readFile,
|
||||
readlink,
|
||||
realpath,
|
||||
rm,
|
||||
} from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, 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 { join } from "node:path";
|
||||
import { spawn, type IPty } from "node-pty";
|
||||
import type {
|
||||
FileState,
|
||||
@@ -25,8 +15,14 @@ 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);
|
||||
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
|
||||
import { startProcessSampler } from "./ProcessSampling.js";
|
||||
import { snapshotRoots, type SnapshotResult } from "./FilesystemSnapshot.js";
|
||||
import {
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessText,
|
||||
redactProtocolEvents,
|
||||
} from "./ProcessNormalization.js";
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
@@ -66,6 +62,11 @@ export class ProcessCaptureError extends AnalysisError {
|
||||
readonly _tag = "ProcessCaptureError";
|
||||
}
|
||||
|
||||
const assertNotCancelled = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ProcessCaptureError("process capture was cancelled");
|
||||
};
|
||||
|
||||
/** Runtime availability of the native PTY adapter on this host. */
|
||||
export type ProcessCaptureCapability =
|
||||
| { readonly available: true; readonly backend: "node-pty" }
|
||||
@@ -103,129 +104,17 @@ export const probeProcessCaptureCapability =
|
||||
}
|
||||
};
|
||||
|
||||
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,
|
||||
runId: string,
|
||||
): Record<string, string> => {
|
||||
const environment: Record<string, string> = {
|
||||
...scenario.environment,
|
||||
HOME: home,
|
||||
TERM: "xterm-256color",
|
||||
...scenario.environment,
|
||||
REA_PROCESS_RUN_ID: runId,
|
||||
};
|
||||
for (const name of scenario.inherit_environment) {
|
||||
const value = process.env[name];
|
||||
@@ -236,29 +125,6 @@ const makeEnvironment = (
|
||||
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,
|
||||
@@ -276,6 +142,24 @@ const scheduleScenarioEvents = (
|
||||
}
|
||||
};
|
||||
|
||||
const startScenarioEvents = (
|
||||
scenario: ProcessScenario,
|
||||
getTerminal: () => IPty | undefined,
|
||||
timers: Set<NodeJS.Timeout>,
|
||||
): (() => void) => {
|
||||
let started = false;
|
||||
return () => {
|
||||
if (started) return;
|
||||
started = true;
|
||||
scheduleScenarioEvents(scenario, getTerminal, timers);
|
||||
};
|
||||
};
|
||||
|
||||
const eventsRequireReadiness = (scenario: ProcessScenario): boolean =>
|
||||
scenario.events.some(
|
||||
(event) => event.type === "input" || event.type === "resize",
|
||||
);
|
||||
|
||||
interface TerminalExitOptions {
|
||||
readonly terminal: IPty;
|
||||
readonly scenario: ProcessScenario;
|
||||
@@ -287,7 +171,11 @@ interface TerminalExitOptions {
|
||||
|
||||
interface CaptureResultOptions {
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly exit: { readonly exitCode: number; readonly signal?: number };
|
||||
readonly exit: {
|
||||
readonly exitCode: number;
|
||||
readonly signal?: number;
|
||||
readonly reason: "exited" | "timeout" | "idle_timeout";
|
||||
};
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly before: SnapshotResult;
|
||||
@@ -297,56 +185,40 @@ interface CaptureResultOptions {
|
||||
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 classifyFilesystemEffects = (
|
||||
before: readonly FileState[],
|
||||
after: readonly FileState[],
|
||||
): ProcessCapture["filesystem_effects"] => {
|
||||
const beforeByPath = new Map(before.map((file) => [file.path, file]));
|
||||
const afterByPath = new Map(after.map((file) => [file.path, file]));
|
||||
const paths = [
|
||||
...new Set([...beforeByPath.keys(), ...afterByPath.keys()]),
|
||||
].sort();
|
||||
return paths.map((path) => {
|
||||
const beforeFile = beforeByPath.get(path) ?? null;
|
||||
const afterFile = afterByPath.get(path) ?? null;
|
||||
const status =
|
||||
beforeFile === null
|
||||
? "created"
|
||||
: afterFile === null
|
||||
? "deleted"
|
||||
: JSON.stringify(beforeFile) === JSON.stringify(afterFile)
|
||||
? "unchanged"
|
||||
: "modified";
|
||||
return { path, status, before: beforeFile, after: afterFile };
|
||||
});
|
||||
};
|
||||
|
||||
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,
|
||||
schema_version: 2,
|
||||
normalization: options.scenario.normalization,
|
||||
frames: options.frames,
|
||||
exit: {
|
||||
code: options.exit.exitCode < 0 ? null : options.exit.exitCode,
|
||||
signal: options.exit.signal ?? null,
|
||||
reason: options.exit.reason,
|
||||
},
|
||||
process_samples: normalizeSamples(
|
||||
process_samples: normalizeProcessSamples(
|
||||
options.samples,
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
@@ -357,12 +229,30 @@ const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
|
||||
),
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
filesystem_effects: classifyFilesystemEffects(
|
||||
options.before.files,
|
||||
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.",
|
||||
],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "process",
|
||||
reason: "Process trees are sampled and may omit short-lived descendants.",
|
||||
},
|
||||
{
|
||||
scope: "network",
|
||||
reason: "External network isolation is not enforced by this adapter.",
|
||||
},
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
});
|
||||
|
||||
const awaitTerminalExit = async ({
|
||||
@@ -372,21 +262,117 @@ const awaitTerminalExit = async ({
|
||||
lastOutput,
|
||||
signal,
|
||||
timers,
|
||||
}: TerminalExitOptions): Promise<{ exitCode: number; signal?: number }> =>
|
||||
}: TerminalExitOptions): Promise<{
|
||||
exitCode: number;
|
||||
signal?: number;
|
||||
reason: "exited" | "timeout" | "idle_timeout" | "cancelled";
|
||||
}> =>
|
||||
new Promise((resolveExit) => {
|
||||
terminal.onExit(resolveExit);
|
||||
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
|
||||
terminal.onExit((exit) => resolveExit({ ...exit, reason }));
|
||||
const timeout = setInterval(() => {
|
||||
if (
|
||||
Date.now() - started >= scenario.timeout_ms ||
|
||||
Date.now() - lastOutput() >= scenario.idle_timeout_ms ||
|
||||
signal?.aborted === true
|
||||
) {
|
||||
if (signal?.aborted === true) {
|
||||
reason = "cancelled";
|
||||
terminal.kill("SIGKILL");
|
||||
} else if (Date.now() - started >= scenario.timeout_ms) {
|
||||
reason = "timeout";
|
||||
terminal.kill("SIGKILL");
|
||||
} else if (Date.now() - lastOutput() >= scenario.idle_timeout_ms) {
|
||||
reason = "idle_timeout";
|
||||
terminal.kill("SIGKILL");
|
||||
}
|
||||
}, 20);
|
||||
timers.add(timeout);
|
||||
});
|
||||
|
||||
const releaseProcessResources = async (options: {
|
||||
readonly timers: ReadonlySet<NodeJS.Timeout>;
|
||||
readonly replay: LoopbackReplay | undefined;
|
||||
readonly terminal: IPty | undefined;
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
}): Promise<string | undefined> => {
|
||||
for (const timer of options.timers) clearTimeout(timer);
|
||||
let failure: string | undefined;
|
||||
try {
|
||||
await options.replay?.close();
|
||||
} catch {
|
||||
failure = "loopback replay cleanup failed";
|
||||
}
|
||||
if (options.terminal !== undefined && process.platform !== "win32") {
|
||||
const cleaned = await cleanupOwnedProcessGroup({
|
||||
runId: options.runId,
|
||||
leaderPid: options.terminal.pid,
|
||||
processGroupId: options.terminal.pid,
|
||||
});
|
||||
if (!cleaned.cleaned) failure ??= cleaned.reason;
|
||||
}
|
||||
try {
|
||||
await rm(options.temporaryRoot, { recursive: true, force: true });
|
||||
} catch {
|
||||
failure ??= "temporary process root cleanup failed";
|
||||
}
|
||||
return failure;
|
||||
};
|
||||
|
||||
const captureTerminalFrames = (options: {
|
||||
readonly terminal: IPty;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly frames: TerminalFrame[];
|
||||
readonly started: number;
|
||||
readonly temporaryRoot: string;
|
||||
readonly onOutput: () => void;
|
||||
readonly onFirstOutput: () => void;
|
||||
}): (() => boolean) => {
|
||||
let outputBytes = 0;
|
||||
let truncated = false;
|
||||
options.terminal.onData((data) => {
|
||||
options.onFirstOutput();
|
||||
options.onOutput();
|
||||
const bytes = Buffer.byteLength(data);
|
||||
if (
|
||||
options.frames.length >= options.scenario.limits.frames ||
|
||||
outputBytes + bytes > options.scenario.limits.output_bytes
|
||||
) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
outputBytes += bytes;
|
||||
options.frames.push({
|
||||
sequence: options.frames.length,
|
||||
at_ms:
|
||||
Math.floor(
|
||||
(Date.now() - options.started) /
|
||||
options.scenario.normalization.time_bucket_ms,
|
||||
) * options.scenario.normalization.time_bucket_ms,
|
||||
data: normalizeProcessText(
|
||||
data,
|
||||
options.scenario,
|
||||
options.temporaryRoot,
|
||||
options.terminal.pid,
|
||||
),
|
||||
});
|
||||
});
|
||||
return () => truncated;
|
||||
};
|
||||
|
||||
const resolveProcessResult = (
|
||||
capture: ProcessCapture | undefined,
|
||||
executionFailure: unknown,
|
||||
cleanupFailure: string | undefined,
|
||||
): ProcessCapture => {
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ProcessCaptureError(cleanupFailure);
|
||||
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
|
||||
if (executionFailure !== undefined)
|
||||
throw new ProcessCaptureError("process capture failed", {
|
||||
cause: executionFailure,
|
||||
});
|
||||
if (capture === undefined)
|
||||
throw new ProcessCaptureError("process capture produced no result");
|
||||
return capture;
|
||||
};
|
||||
|
||||
/** Execute one authorized scenario and return bounded observations. */
|
||||
const runProcessScenario = async (
|
||||
scenario: ProcessScenario,
|
||||
@@ -396,68 +382,54 @@ const runProcessScenario = async (
|
||||
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");
|
||||
assertNotCancelled(signal);
|
||||
|
||||
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
|
||||
const runId = randomUUID();
|
||||
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;
|
||||
let started = 0;
|
||||
let lastOutput = 0;
|
||||
const timers = new Set<NodeJS.Timeout>();
|
||||
let capture: ProcessCapture | undefined;
|
||||
let executionFailure: unknown;
|
||||
let framesTruncated = (): boolean => false;
|
||||
let stopSampler: () => Promise<void> = async () => undefined;
|
||||
|
||||
try {
|
||||
replay = await startLoopbackReplay(scenario);
|
||||
started = Date.now();
|
||||
lastOutput = started;
|
||||
terminal = spawn(scenario.executable, [...scenario.arguments], {
|
||||
cwd: scenario.working_directory,
|
||||
env: makeEnvironment(scenario, home, replay),
|
||||
env: makeEnvironment(scenario, home, replay, runId),
|
||||
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,
|
||||
),
|
||||
});
|
||||
const startEvents = startScenarioEvents(scenario, () => terminal, timers);
|
||||
if (!eventsRequireReadiness(scenario)) startEvents();
|
||||
framesTruncated = captureTerminalFrames({
|
||||
terminal,
|
||||
scenario,
|
||||
frames,
|
||||
started,
|
||||
temporaryRoot,
|
||||
onOutput: () => (lastOutput = Date.now()),
|
||||
onFirstOutput: startEvents,
|
||||
});
|
||||
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);
|
||||
stopSampler = startProcessSampler(
|
||||
terminal.pid,
|
||||
started,
|
||||
scenario.limits.processes,
|
||||
samples,
|
||||
);
|
||||
const exit = await awaitTerminalExit({
|
||||
terminal,
|
||||
scenario,
|
||||
@@ -466,15 +438,22 @@ const runProcessScenario = async (
|
||||
signal,
|
||||
timers,
|
||||
});
|
||||
const exitReason = exit.reason;
|
||||
await stopSampler();
|
||||
if (exitReason === "cancelled")
|
||||
throw new ProcessCaptureError("process capture was cancelled");
|
||||
await new Promise((resolveSettle) =>
|
||||
setTimeout(resolveSettle, scenario.settle_ms),
|
||||
);
|
||||
const after = await snapshotRoots(scenario);
|
||||
truncated ||=
|
||||
after.truncated || samples.length >= scenario.limits.processes;
|
||||
return buildCaptureResult({
|
||||
after.truncated ||
|
||||
replay.truncated ||
|
||||
framesTruncated() ||
|
||||
samples.length >= scenario.limits.processes;
|
||||
capture = buildCaptureResult({
|
||||
frames,
|
||||
exit,
|
||||
exit: { ...exit, reason: exitReason },
|
||||
samples,
|
||||
replay,
|
||||
before,
|
||||
@@ -485,12 +464,17 @@ const runProcessScenario = async (
|
||||
});
|
||||
} 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 });
|
||||
executionFailure = cause;
|
||||
}
|
||||
await stopSampler();
|
||||
const cleanupFailure = await releaseProcessResources({
|
||||
timers,
|
||||
replay,
|
||||
terminal,
|
||||
runId,
|
||||
temporaryRoot,
|
||||
});
|
||||
return resolveProcessResult(capture, executionFailure, cleanupFailure);
|
||||
};
|
||||
|
||||
/** Execute one scenario through a typed expected-failure channel. */
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import type {
|
||||
ProcessCapture,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
|
||||
/** Normalize and redact one terminal/protocol payload under scenario rules. */
|
||||
export const normalizeProcessText = (
|
||||
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>");
|
||||
normalized = normalized.replaceAll(
|
||||
scenario.working_directory,
|
||||
"<working-directory>",
|
||||
);
|
||||
normalized = normalized.replaceAll(scenario.executable, "<executable>");
|
||||
for (const [index, root] of scenario.filesystem_roots.entries())
|
||||
normalized = normalized.replaceAll(
|
||||
root,
|
||||
`<filesystem-root-${String(index)}>`,
|
||||
);
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
export const normalizeProcessSamples = (
|
||||
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: normalizeProcessText(
|
||||
sample.command,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
rootPid,
|
||||
),
|
||||
}));
|
||||
};
|
||||
|
||||
export const redactProtocolEvents = (
|
||||
events: readonly ProcessCapture["protocol_events"][number][],
|
||||
scenario: ProcessScenario,
|
||||
): readonly ProcessCapture["protocol_events"][number][] =>
|
||||
events.map((event) => ({
|
||||
...event,
|
||||
data: normalizeProcessText(event.data, scenario, "<no-temporary-root>", -1),
|
||||
}));
|
||||
@@ -0,0 +1,115 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export interface OwnedProcessGroup {
|
||||
readonly runId: string;
|
||||
readonly leaderPid: number;
|
||||
readonly processGroupId: number;
|
||||
}
|
||||
|
||||
interface ProcessGroupMember {
|
||||
readonly pid: number;
|
||||
readonly parentPid: number;
|
||||
readonly processGroupId: number;
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
export interface ProcessOwnershipHost {
|
||||
listMembers(processGroupId: number): Promise<readonly ProcessGroupMember[]>;
|
||||
environment(pid: number): Promise<Readonly<Record<string, string>>>;
|
||||
signalGroup(processGroupId: number, signal: NodeJS.Signals): void;
|
||||
}
|
||||
|
||||
export type ProcessCleanupResult =
|
||||
| { readonly cleaned: true; readonly signaled: boolean }
|
||||
| { readonly cleaned: false; readonly reason: string };
|
||||
|
||||
const parseEnvironment = (value: string): Readonly<Record<string, string>> =>
|
||||
Object.fromEntries(
|
||||
value
|
||||
.split("\0")
|
||||
.filter((entry) => entry.includes("="))
|
||||
.map((entry) => {
|
||||
const separator = entry.indexOf("=");
|
||||
return [entry.slice(0, separator), entry.slice(separator + 1)];
|
||||
}),
|
||||
);
|
||||
|
||||
const systemHost: ProcessOwnershipHost = {
|
||||
async listMembers(processGroupId) {
|
||||
if (process.platform === "win32") return [];
|
||||
const { stdout } = await execFileAsync("ps", [
|
||||
"-axo",
|
||||
"pid=,ppid=,pgid=,command=",
|
||||
]);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => /\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)/u.exec(line))
|
||||
.filter((match): match is RegExpExecArray => match !== null)
|
||||
.map((match) => ({
|
||||
pid: Number(match[1]),
|
||||
parentPid: Number(match[2]),
|
||||
processGroupId: Number(match[3]),
|
||||
command: match[4] ?? "",
|
||||
}))
|
||||
.filter((member) => member.processGroupId === processGroupId);
|
||||
},
|
||||
async environment(pid) {
|
||||
if (process.platform === "linux") {
|
||||
return parseEnvironment(await readFile(`/proc/${pid}/environ`, "utf8"));
|
||||
}
|
||||
const { stdout } = await execFileAsync("ps", ["eww", "-p", String(pid)]);
|
||||
const environment: Record<string, string> = {};
|
||||
for (const match of stdout.matchAll(
|
||||
/(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=([^\s]*)/gu,
|
||||
))
|
||||
environment[match[1]!] = match[2] ?? "";
|
||||
return environment;
|
||||
},
|
||||
signalGroup(processGroupId, signal) {
|
||||
process.kill(-processGroupId, signal);
|
||||
},
|
||||
};
|
||||
|
||||
/** Verify run-token ownership before signaling a POSIX process group. */
|
||||
export const cleanupOwnedProcessGroup = async (
|
||||
ownership: OwnedProcessGroup,
|
||||
host: ProcessOwnershipHost = systemHost,
|
||||
): Promise<ProcessCleanupResult> => {
|
||||
let members: readonly ProcessGroupMember[];
|
||||
try {
|
||||
members = await host.listMembers(ownership.processGroupId);
|
||||
} catch {
|
||||
return { cleaned: false, reason: "process group could not be inspected" };
|
||||
}
|
||||
if (members.length === 0) return { cleaned: true, signaled: false };
|
||||
for (const member of members) {
|
||||
let environment: Readonly<Record<string, string>>;
|
||||
try {
|
||||
environment = await host.environment(member.pid);
|
||||
} catch {
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "process ownership could not be revalidated",
|
||||
};
|
||||
}
|
||||
if (environment.REA_PROCESS_RUN_ID !== ownership.runId) {
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "process group contains an unowned or PID-reused process",
|
||||
};
|
||||
}
|
||||
}
|
||||
try {
|
||||
host.signalGroup(ownership.processGroupId, "SIGKILL");
|
||||
} catch (cause: unknown) {
|
||||
const code =
|
||||
cause instanceof Error && "code" in cause ? cause.code : undefined;
|
||||
if (code !== "ESRCH")
|
||||
return { cleaned: false, reason: "owned process group signal failed" };
|
||||
}
|
||||
return { cleaned: true, signaled: true };
|
||||
};
|
||||
@@ -0,0 +1,350 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import type { ProcessSample } from "../domain/processCapture.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const PROC_READ_CONCURRENCY = 64;
|
||||
|
||||
interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly parent_pid: number;
|
||||
readonly command: string;
|
||||
readonly startTime: string | undefined;
|
||||
}
|
||||
|
||||
interface ProcessNode extends ProcessRow {
|
||||
readonly children: readonly number[];
|
||||
}
|
||||
|
||||
interface SampleProcessContext {
|
||||
readonly rootPid: number;
|
||||
readonly elapsedMs: number;
|
||||
readonly limit: number;
|
||||
readonly sampledPids: Set<number>;
|
||||
readonly identities: Map<number, string>;
|
||||
readonly signal: AbortSignal;
|
||||
}
|
||||
|
||||
const parseProcStat = (
|
||||
identifier: string,
|
||||
stat: string,
|
||||
): ProcessRow | undefined => {
|
||||
const commandEnd = stat.lastIndexOf(")");
|
||||
if (commandEnd < 0) return undefined;
|
||||
const fields = stat
|
||||
.slice(commandEnd + 2)
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
const pid = Number(identifier);
|
||||
const parentPid = Number(fields[1]);
|
||||
const startTime = fields[19];
|
||||
if (
|
||||
!Number.isSafeInteger(pid) ||
|
||||
pid <= 0 ||
|
||||
!Number.isSafeInteger(parentPid) ||
|
||||
parentPid < 0 ||
|
||||
startTime === undefined ||
|
||||
!/^\d+$/.test(startTime)
|
||||
)
|
||||
return undefined;
|
||||
return {
|
||||
pid,
|
||||
parent_pid: parentPid,
|
||||
command: "",
|
||||
startTime,
|
||||
};
|
||||
};
|
||||
|
||||
const readProcessStat = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<ProcessRow | undefined> => {
|
||||
try {
|
||||
const stat = await readFile(`/proc/${String(pid)}/stat`, {
|
||||
encoding: "utf8",
|
||||
signal,
|
||||
});
|
||||
return parseProcStat(String(pid), stat);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const readProcessCommand = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<Buffer | undefined> => {
|
||||
try {
|
||||
return await readFile(`/proc/${String(pid)}/cmdline`, { signal });
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const readLinuxChildren = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<readonly number[] | undefined> => {
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(`/proc/${String(pid)}/task/${String(pid)}/children`, {
|
||||
encoding: "utf8",
|
||||
signal,
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
return text
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((value) => /^\d+$/.test(value))
|
||||
.map(Number)
|
||||
.filter((child) => Number.isSafeInteger(child) && child > 0);
|
||||
};
|
||||
|
||||
const inspectProcess = async (
|
||||
pid: number,
|
||||
expectedParent: number | undefined,
|
||||
signal: AbortSignal,
|
||||
identities: Map<number, string>,
|
||||
): Promise<ProcessNode | undefined> => {
|
||||
const before = await readProcessStat(pid, signal);
|
||||
if (before === undefined || before.startTime === undefined) return undefined;
|
||||
|
||||
const existing = identities.get(pid);
|
||||
if (existing !== undefined && existing !== before.startTime) return undefined;
|
||||
if (expectedParent !== undefined && before.parent_pid !== expectedParent)
|
||||
return undefined;
|
||||
|
||||
const [commandBuffer, children] = await Promise.all([
|
||||
readProcessCommand(pid, signal),
|
||||
readLinuxChildren(pid, signal),
|
||||
]);
|
||||
|
||||
const after = await readProcessStat(pid, signal);
|
||||
if (after === undefined || after.startTime === undefined) return undefined;
|
||||
if (
|
||||
before.startTime !== after.startTime ||
|
||||
before.parent_pid !== after.parent_pid
|
||||
)
|
||||
return undefined;
|
||||
if (expectedParent !== undefined && after.parent_pid !== expectedParent)
|
||||
return undefined;
|
||||
|
||||
const command =
|
||||
commandBuffer === undefined
|
||||
? ""
|
||||
: commandBuffer.toString().replaceAll("\0", " ").trim();
|
||||
|
||||
return {
|
||||
pid: before.pid,
|
||||
parent_pid: before.parent_pid,
|
||||
startTime: before.startTime,
|
||||
command,
|
||||
children: children ?? [],
|
||||
};
|
||||
};
|
||||
|
||||
const sampleLinux = async (
|
||||
context: SampleProcessContext,
|
||||
): Promise<readonly ProcessRow[]> => {
|
||||
const { rootPid, limit, signal, sampledPids, identities } = context;
|
||||
if (limit <= 0) return [];
|
||||
|
||||
const rootStat = await readProcessStat(rootPid, signal);
|
||||
if (rootStat === undefined) return [];
|
||||
const rootChildren = await readLinuxChildren(rootPid, signal);
|
||||
if (rootChildren === undefined) return samplePs(context);
|
||||
|
||||
const rows: ProcessRow[] = [];
|
||||
const visited = new Set<number>([rootPid]);
|
||||
let level: Array<{
|
||||
readonly pid: number;
|
||||
readonly expectedParent: number | undefined;
|
||||
}> = [{ pid: rootPid, expectedParent: undefined }];
|
||||
|
||||
while (level.length > 0 && rows.length < limit) {
|
||||
const batchSize = Math.min(level.length, PROC_READ_CONCURRENCY);
|
||||
const batch = level.slice(0, batchSize);
|
||||
level = level.slice(batchSize);
|
||||
|
||||
const batchResults = await Promise.all(
|
||||
batch.map((item) =>
|
||||
inspectProcess(item.pid, item.expectedParent, signal, identities),
|
||||
),
|
||||
);
|
||||
|
||||
const nextLevel: typeof batch = [];
|
||||
for (const node of batchResults) {
|
||||
if (node === undefined) continue;
|
||||
|
||||
if (!sampledPids.has(node.pid)) {
|
||||
if (rows.length >= limit) break;
|
||||
rows.push(node);
|
||||
}
|
||||
if (rows.length >= limit) break;
|
||||
|
||||
for (const child of node.children) {
|
||||
if (visited.has(child)) continue;
|
||||
visited.add(child);
|
||||
nextLevel.push({ pid: child, expectedParent: node.pid });
|
||||
}
|
||||
if (rows.length >= limit) break;
|
||||
}
|
||||
|
||||
level.push(...nextLevel);
|
||||
}
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
const readPsRows = async (
|
||||
signal: AbortSignal,
|
||||
): Promise<readonly ProcessRow[]> => {
|
||||
const { stdout } = await execFileAsync(
|
||||
"ps",
|
||||
["-axo", "pid=,ppid=,command="],
|
||||
{ signal },
|
||||
);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => /\s*(\d+)\s+(\d+)\s+(.*)/u.exec(line))
|
||||
.filter((match): match is RegExpExecArray => match !== null)
|
||||
.map((match) => ({
|
||||
pid: Number(match[1]),
|
||||
parent_pid: Number(match[2]),
|
||||
command: match[3] ?? "",
|
||||
startTime: undefined,
|
||||
}))
|
||||
.filter(
|
||||
(row) =>
|
||||
Number.isSafeInteger(row.pid) &&
|
||||
row.pid > 0 &&
|
||||
Number.isSafeInteger(row.parent_pid) &&
|
||||
row.parent_pid >= 0,
|
||||
)
|
||||
.sort((left, right) => left.pid - right.pid);
|
||||
};
|
||||
|
||||
const samplePs = async (
|
||||
context: SampleProcessContext,
|
||||
): Promise<readonly ProcessRow[]> => {
|
||||
const { rootPid, limit, signal, sampledPids } = context;
|
||||
if (limit <= 0) return [];
|
||||
|
||||
const rows = await readPsRows(signal);
|
||||
const rowByPid = new Map(rows.map((row) => [row.pid, row]));
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const siblings = childrenByParent.get(row.parent_pid) ?? [];
|
||||
siblings.push(row);
|
||||
childrenByParent.set(row.parent_pid, siblings);
|
||||
}
|
||||
|
||||
const result: ProcessRow[] = [];
|
||||
const visited = new Set<number>();
|
||||
const queue: number[] = [rootPid];
|
||||
let index = 0;
|
||||
|
||||
while (index < queue.length && result.length < limit) {
|
||||
const pid = queue[index];
|
||||
if (pid === undefined) break;
|
||||
index += 1;
|
||||
if (visited.has(pid)) continue;
|
||||
visited.add(pid);
|
||||
|
||||
const row = rowByPid.get(pid);
|
||||
if (row !== undefined && !sampledPids.has(row.pid)) {
|
||||
result.push(row);
|
||||
}
|
||||
if (result.length >= limit) break;
|
||||
|
||||
for (const child of childrenByParent.get(pid) ?? []) {
|
||||
if (!visited.has(child.pid)) queue.push(child.pid);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const sampleProcesses = async (
|
||||
context: SampleProcessContext,
|
||||
): Promise<readonly ProcessSample[]> => {
|
||||
if (process.platform === "win32" || context.limit <= 0) return [];
|
||||
|
||||
const rows =
|
||||
process.platform === "linux"
|
||||
? await sampleLinux(context)
|
||||
: await samplePs(context);
|
||||
|
||||
const { elapsedMs, sampledPids, identities } = context;
|
||||
const samples: ProcessSample[] = [];
|
||||
for (const row of rows) {
|
||||
if (sampledPids.has(row.pid)) continue;
|
||||
if (row.startTime !== undefined) {
|
||||
const existing = identities.get(row.pid);
|
||||
if (existing !== undefined && existing !== row.startTime) continue;
|
||||
identities.set(row.pid, row.startTime);
|
||||
}
|
||||
samples.push({
|
||||
at_ms: elapsedMs,
|
||||
pid: row.pid,
|
||||
parent_pid: row.parent_pid,
|
||||
command: row.command,
|
||||
});
|
||||
}
|
||||
return samples;
|
||||
};
|
||||
|
||||
/** Start bounded process-tree sampling and expose an awaited stop. */
|
||||
export const startProcessSampler = (
|
||||
rootPid: number,
|
||||
started: number,
|
||||
limit: number,
|
||||
samples: ProcessSample[],
|
||||
): (() => Promise<void>) => {
|
||||
const identities = new Map<number, string>();
|
||||
const sampledPids = new Set<number>(samples.map(({ pid }) => pid));
|
||||
let pending: Promise<void> | undefined;
|
||||
let stopped = false;
|
||||
let abortCurrent: (() => void) | undefined;
|
||||
|
||||
const sample = (): void => {
|
||||
if (stopped || pending !== undefined || sampledPids.size >= limit) return;
|
||||
|
||||
const controller = new AbortController();
|
||||
abortCurrent = () => controller.abort();
|
||||
pending = sampleProcesses({
|
||||
rootPid,
|
||||
elapsedMs: Date.now() - started,
|
||||
limit: limit - sampledPids.size,
|
||||
sampledPids,
|
||||
identities,
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((values) => {
|
||||
for (const value of values) {
|
||||
if (sampledPids.size >= limit) break;
|
||||
if (sampledPids.has(value.pid)) continue;
|
||||
sampledPids.add(value.pid);
|
||||
samples.push(value);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
abortCurrent = undefined;
|
||||
pending = undefined;
|
||||
});
|
||||
};
|
||||
|
||||
const timer = setInterval(sample, 50);
|
||||
sample();
|
||||
|
||||
return async () => {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
abortCurrent?.();
|
||||
await pending;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const addressSchema = z.string().regex(/^0x[0-9a-f]+$/iu);
|
||||
const identitySchema = z.object({ address: addressSchema, name: z.string() });
|
||||
const collectionSchema = z.object({
|
||||
items: z.array(z.unknown()),
|
||||
total: z.number().int().min(0).nullable(),
|
||||
returned: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
});
|
||||
|
||||
/** Extract a real address from the provider's exact procedure page. */
|
||||
export const firstProcedureAddress = (input: unknown): string => {
|
||||
const page = z
|
||||
.object({
|
||||
items: z.array(z.object({ address: addressSchema })).min(1),
|
||||
offset: z.number().int().min(0),
|
||||
limit: z.number().int().min(1),
|
||||
total: z.number().int().min(1),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
})
|
||||
.parse(input);
|
||||
const first = page.items[0];
|
||||
if (first === undefined) throw new TypeError("Procedure page was empty");
|
||||
return first.address;
|
||||
};
|
||||
|
||||
/** Reject empty and success-shaped embedded decompilation failures. */
|
||||
export const requirePseudocode = (
|
||||
input: unknown,
|
||||
operation: string,
|
||||
): string => {
|
||||
if (typeof input !== "string" || input.trim().length === 0)
|
||||
throw new TypeError(`${operation} returned empty pseudocode`);
|
||||
if (input === "No output" || input.startsWith("Error:"))
|
||||
throw new TypeError(`${operation} returned an embedded failure: ${input}`);
|
||||
return input;
|
||||
};
|
||||
|
||||
/** Validate an exact bounded Hopper function dossier semantically. */
|
||||
export const requireFunctionDossier = (
|
||||
input: unknown,
|
||||
expectedAddress: string,
|
||||
): Record<string, unknown> => {
|
||||
const value = objectValue(
|
||||
input,
|
||||
"analyze_function returned no function dossier",
|
||||
);
|
||||
const procedure = identitySchema.parse(value.procedure);
|
||||
if (procedure.address !== expectedAddress)
|
||||
throw new TypeError("analyze_function returned the wrong procedure");
|
||||
if (procedure.name.trim().length === 0)
|
||||
throw new TypeError("analyze_function omitted the procedure name");
|
||||
validatePseudocodeBounds(value.pseudocode);
|
||||
for (const field of COLLECTION_FIELDS)
|
||||
validateCollection(value[field], field);
|
||||
for (const field of ["callers", "callees"] as const)
|
||||
z.array(identitySchema).parse(collectionSchema.parse(value[field]).items);
|
||||
validateBlocks(collectionSchema.parse(value.basic_blocks).items);
|
||||
validateInstructionScan(value.instruction_scan);
|
||||
return value;
|
||||
};
|
||||
|
||||
/** Require every relationship to be an actual hexadecimal address. */
|
||||
export const requireAddressArray = (
|
||||
input: unknown,
|
||||
operation: string,
|
||||
): string[] => {
|
||||
const parsed = z.array(addressSchema).parse(input);
|
||||
if (parsed.some((address) => address.length === 0))
|
||||
throw new TypeError(`${operation} returned an invalid address list`);
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const COLLECTION_FIELDS = [
|
||||
"comments",
|
||||
"callers",
|
||||
"callees",
|
||||
"incoming_references",
|
||||
"outgoing_references",
|
||||
"referenced_strings",
|
||||
"referenced_names",
|
||||
"basic_blocks",
|
||||
] as const;
|
||||
|
||||
const validatePseudocodeBounds = (input: unknown): void => {
|
||||
const pseudocode = z
|
||||
.object({
|
||||
text: z.string(),
|
||||
returned_chars: z.number().int().min(0),
|
||||
total_chars: z.number().int().min(0),
|
||||
})
|
||||
.parse(input);
|
||||
const text = requirePseudocode(pseudocode.text, "analyze_function");
|
||||
if (
|
||||
pseudocode.returned_chars !== [...text].length ||
|
||||
pseudocode.total_chars < pseudocode.returned_chars
|
||||
)
|
||||
throw new TypeError(
|
||||
"analyze_function returned inconsistent pseudocode bounds",
|
||||
);
|
||||
};
|
||||
|
||||
const validateCollection = (input: unknown, field: string): void => {
|
||||
const collection = collectionSchema.parse(input);
|
||||
if (collection.returned !== collection.items.length)
|
||||
throw new TypeError(`analyze_function returned an invalid ${field} result`);
|
||||
};
|
||||
|
||||
const validateBlocks = (items: readonly unknown[]): void => {
|
||||
for (const block of items)
|
||||
if (!Array.isArray(objectValue(block, "Invalid basic block").successors))
|
||||
throw new TypeError("analyze_function omitted CFG successor evidence");
|
||||
};
|
||||
|
||||
const validateInstructionScan = (input: unknown): void => {
|
||||
const scan = z
|
||||
.object({ scanned: z.number().int().min(0), truncated: z.boolean() })
|
||||
.parse(input);
|
||||
if (scan.scanned === 0 && !scan.truncated)
|
||||
throw new TypeError(
|
||||
"analyze_function omitted instruction scan limitations",
|
||||
);
|
||||
};
|
||||
|
||||
const objectValue = (
|
||||
input: unknown,
|
||||
message: string,
|
||||
): Record<string, unknown> => {
|
||||
const parsed = z.record(z.string(), z.unknown()).safeParse(input);
|
||||
if (!parsed.success) throw new TypeError(message);
|
||||
return parsed.data;
|
||||
};
|
||||
@@ -0,0 +1,260 @@
|
||||
import { isSecretLikePath } from "../domain/referenceSourceClassification.js";
|
||||
import {
|
||||
createHistoricalSourceGraph,
|
||||
type HistoricalSourceGraph,
|
||||
type HistoricalSourceGraphInput,
|
||||
} from "../domain/referenceSourceGraph.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { readReferenceSource } from "../reference/ReferenceSourceReader.js";
|
||||
import { parseReferenceSourceEntries } from "./ReferenceSourceImportEntries.js";
|
||||
import { readReferenceSourceVcs } from "./ReferenceSourceVcsAdapter.js";
|
||||
import {
|
||||
type ReferenceSourceImportError,
|
||||
type ReferenceSourceImportOptions,
|
||||
} from "./ReferenceSourceImportTypes.js";
|
||||
import { prepareReferenceSourceImport } from "./ReferenceSourceImportPolicy.js";
|
||||
|
||||
export type {
|
||||
ReferenceSourceImportError,
|
||||
ReferenceSourceImportOptions,
|
||||
} from "./ReferenceSourceImportTypes.js";
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number => {
|
||||
const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);
|
||||
const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);
|
||||
const length = Math.min(leftPoints.length, rightPoints.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);
|
||||
if (difference !== 0) return difference;
|
||||
}
|
||||
return leftPoints.length - rightPoints.length;
|
||||
};
|
||||
|
||||
const byCodePoint = (left: string, right: string): number =>
|
||||
compareCodePoints(left, right);
|
||||
|
||||
const failure = (
|
||||
code: ReferenceSourceImportError["code"],
|
||||
message: string,
|
||||
): ReferenceSourceImportError => ({
|
||||
tag: "reference-source-import",
|
||||
code,
|
||||
message,
|
||||
});
|
||||
|
||||
const cancelled = (): ReferenceSourceImportError =>
|
||||
failure("cancelled", "Reference source import cancelled");
|
||||
|
||||
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
|
||||
|
||||
const relationshipKey = (
|
||||
relationship: HistoricalSourceGraphInput["relationships"][number],
|
||||
): string =>
|
||||
`${relationship.from_path}\u0000${relationship.to}\u0000${relationship.kind}\u0000${relationship.resolution}\u0000${relationship.parse_state}`;
|
||||
|
||||
const deduplicateRelationships = (
|
||||
relationships: HistoricalSourceGraphInput["relationships"],
|
||||
): HistoricalSourceGraphInput["relationships"] => {
|
||||
const seen = new Set<string>();
|
||||
const result: HistoricalSourceGraphInput["relationships"] = [];
|
||||
for (const relationship of relationships) {
|
||||
const key = relationshipKey(relationship);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
result.push(relationship);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const buildProvenance = (
|
||||
options: ReferenceSourceImportOptions,
|
||||
): HistoricalSourceGraphInput["provenance"] => ({
|
||||
importer: options.importer ?? "rea-reference-source-import",
|
||||
importer_version: options.importerVersion ?? null,
|
||||
caller: options.caller,
|
||||
});
|
||||
|
||||
const deriveLanguages = (
|
||||
entries: HistoricalSourceGraphInput["entries"],
|
||||
): string[] =>
|
||||
[
|
||||
...new Set(
|
||||
entries.flatMap((entry) =>
|
||||
entry.kind === "file" && entry.language !== null
|
||||
? [entry.language]
|
||||
: [],
|
||||
),
|
||||
),
|
||||
].sort(byCodePoint);
|
||||
|
||||
const deriveManifests = (
|
||||
entries: HistoricalSourceGraphInput["entries"],
|
||||
): string[] =>
|
||||
entries
|
||||
.flatMap((entry) =>
|
||||
entry.kind === "file" && entry.classifications.includes("manifest")
|
||||
? [entry.path]
|
||||
: [],
|
||||
)
|
||||
.sort(byCodePoint);
|
||||
|
||||
const deriveInventoryState = (
|
||||
input: Pick<
|
||||
HistoricalSourceGraphInput,
|
||||
| "entries"
|
||||
| "relationships"
|
||||
| "parse_failures"
|
||||
| "exclusions"
|
||||
| "limitations"
|
||||
>,
|
||||
): "complete" | "partial" | "unknown" => {
|
||||
if (input.limitations.length > 0) return "partial";
|
||||
if (input.exclusions.length > 0) return "partial";
|
||||
if (input.parse_failures.length > 0) return "partial";
|
||||
const partialEntry = input.entries.some(
|
||||
(entry) =>
|
||||
entry.limitations.length > 0 ||
|
||||
(entry.kind === "file" && entry.content_state !== "hashed") ||
|
||||
(entry.kind === "directory" && entry.tree_state !== "enumerated") ||
|
||||
(entry.kind === "symlink" && entry.target_state !== "internal"),
|
||||
);
|
||||
if (partialEntry) return "partial";
|
||||
const partialRelationship = input.relationships.some(
|
||||
({ parse_state, resolution }) =>
|
||||
parse_state !== "parsed" ||
|
||||
["unresolved", "unknown"].includes(resolution),
|
||||
);
|
||||
if (partialRelationship) return "partial";
|
||||
return "complete";
|
||||
};
|
||||
|
||||
const sortAndLimit = (
|
||||
exclusions: HistoricalSourceGraphInput["exclusions"],
|
||||
maxExclusions: number,
|
||||
): HistoricalSourceGraphInput["exclusions"] => {
|
||||
const sorted = [...exclusions].sort((left, right) => {
|
||||
const byPath = byCodePoint(left.path, right.path);
|
||||
if (byPath !== 0) return byPath;
|
||||
return byCodePoint(left.reason, right.reason);
|
||||
});
|
||||
if (sorted.length <= maxExclusions) return sorted;
|
||||
return sorted.slice(0, maxExclusions);
|
||||
};
|
||||
|
||||
/**
|
||||
* Import a reference source directory into a committed historical source graph.
|
||||
*
|
||||
* The import is deterministic, parallel-safe, and never executes source, hooks,
|
||||
* git subprocesses, or network requests. Secret-like paths are redacted before
|
||||
* they are committed to the graph.
|
||||
*/
|
||||
export const importReferenceSource = async (
|
||||
options: ReferenceSourceImportOptions,
|
||||
): Promise<Result<HistoricalSourceGraph, ReferenceSourceImportError>> => {
|
||||
if (isAborted(options.signal)) return err(cancelled());
|
||||
const prepared = await prepareReferenceSourceImport(options);
|
||||
if (!prepared.ok) return prepared;
|
||||
const { ignored, limits, root, secrets } = prepared.value;
|
||||
if (isAborted(options.signal)) return err(cancelled());
|
||||
|
||||
const exclusions: HistoricalSourceGraphInput["exclusions"] = [];
|
||||
const shouldExclude = (path: string): boolean => {
|
||||
if (isSecretLikePath(path) || secrets.ignores(path)) {
|
||||
exclusions.push({ path, reason: "configured-secret" });
|
||||
return true;
|
||||
}
|
||||
if (ignored.ignores(path)) {
|
||||
exclusions.push({ path, reason: "caller-excluded" });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const [readResult, vcs] = await Promise.all([
|
||||
readReferenceSource(root, limits, {
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
shouldExclude,
|
||||
}),
|
||||
readReferenceSourceVcs(root),
|
||||
]);
|
||||
|
||||
if (!readResult.ok) {
|
||||
const error = readResult.error;
|
||||
if (error.code === "cancelled") return err(cancelled());
|
||||
return err(
|
||||
failure(
|
||||
error.code === "invalid-limits" ? "invalid-limits" : "io",
|
||||
error.message,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (isAborted(options.signal)) return err(cancelled());
|
||||
|
||||
const read = readResult.value;
|
||||
const filePaths = new Set(
|
||||
read.entries
|
||||
.filter((entry) => entry.status === "read" && entry.kind === "file")
|
||||
.map((entry) => entry.path),
|
||||
);
|
||||
|
||||
const { entries, relationships, parseFailures, limitations } =
|
||||
parseReferenceSourceEntries(read, filePaths, options.signal);
|
||||
|
||||
if (isAborted(options.signal)) return err(cancelled());
|
||||
|
||||
const uniqueRelationships = deduplicateRelationships(relationships);
|
||||
const uniqueFailures = [...parseFailures]
|
||||
.sort((left, right) => {
|
||||
const byPath = byCodePoint(left.path, right.path);
|
||||
if (byPath !== 0) return byPath;
|
||||
return byCodePoint(left.parser, right.parser);
|
||||
})
|
||||
.filter((value, index, array) => {
|
||||
if (index === 0) return true;
|
||||
const previous = array[index - 1];
|
||||
if (previous === undefined) return true;
|
||||
return value.path !== previous.path || value.parser !== previous.parser;
|
||||
});
|
||||
|
||||
const sortedEntries = [...entries].sort((left, right) =>
|
||||
byCodePoint(left.path, right.path),
|
||||
);
|
||||
const sortedExclusions = sortAndLimit(exclusions, limits.maxEntries);
|
||||
const sortedLimitations = [...limitations].sort(byCodePoint);
|
||||
|
||||
const input: HistoricalSourceGraphInput = {
|
||||
schema: "HistoricalSourceGraph/v1",
|
||||
authority: "historical-reference",
|
||||
root_alias: "$REFERENCE_ROOT",
|
||||
inventory_state: deriveInventoryState({
|
||||
entries: sortedEntries,
|
||||
relationships: uniqueRelationships,
|
||||
parse_failures: uniqueFailures,
|
||||
exclusions: sortedExclusions,
|
||||
limitations: sortedLimitations,
|
||||
}),
|
||||
entries: sortedEntries,
|
||||
relationships: uniqueRelationships.sort((left, right) =>
|
||||
byCodePoint(relationshipKey(left), relationshipKey(right)),
|
||||
),
|
||||
parse_failures: uniqueFailures,
|
||||
exclusions: sortedExclusions,
|
||||
languages: deriveLanguages(sortedEntries),
|
||||
manifests: deriveManifests(sortedEntries),
|
||||
vcs,
|
||||
provenance: buildProvenance(options),
|
||||
limitations: sortedLimitations,
|
||||
};
|
||||
|
||||
try {
|
||||
return ok(createHistoricalSourceGraph(input));
|
||||
} catch (error) {
|
||||
return err(
|
||||
failure(
|
||||
"parse",
|
||||
error instanceof Error ? error.message : "Graph failed validation",
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,166 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { posix } from "node:path";
|
||||
|
||||
import {
|
||||
classifyReferenceSourcePath,
|
||||
detectReferenceSourceLanguage,
|
||||
} from "../domain/referenceSourceClassification.js";
|
||||
import type { HistoricalSourceGraphInput } from "../domain/referenceSourceGraph.js";
|
||||
import { parseReferenceSourceImports } from "../domain/referenceSourceImportParsing.js";
|
||||
import type {
|
||||
ReferenceSourceEntry,
|
||||
ReferenceSourceRead,
|
||||
} from "../reference/ReferenceSourceReader.js";
|
||||
import { PARSEABLE_REFERENCE_SOURCE_LANGUAGES } from "./ReferenceSourceImportTypes.js";
|
||||
|
||||
export interface ParsedReferenceSourceEntries {
|
||||
readonly entries: HistoricalSourceGraphInput["entries"];
|
||||
readonly relationships: HistoricalSourceGraphInput["relationships"];
|
||||
readonly parseFailures: HistoricalSourceGraphInput["parse_failures"];
|
||||
readonly limitations: string[];
|
||||
}
|
||||
|
||||
const hashBytes = (bytes: Uint8Array): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
const failedEntry = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
|
||||
): HistoricalSourceGraphInput["entries"][number] => {
|
||||
const classifications = classifyReferenceSourcePath(entry.path);
|
||||
if (entry.kind === "directory")
|
||||
return {
|
||||
path: entry.path,
|
||||
kind: "directory",
|
||||
classifications,
|
||||
tree_state: entry.code === "limit" ? "partial" : "unreadable",
|
||||
limitations: [entry.message],
|
||||
};
|
||||
if (entry.kind === "symlink")
|
||||
return {
|
||||
path: entry.path,
|
||||
kind: "symlink",
|
||||
target: "<unreadable>",
|
||||
target_state: "unreadable",
|
||||
classifications,
|
||||
limitations: [entry.message],
|
||||
};
|
||||
return {
|
||||
path: entry.path,
|
||||
kind: "file",
|
||||
sha256: null,
|
||||
size: entry.size ?? null,
|
||||
language: null,
|
||||
classifications: entry.kind === "file" ? classifications : ["unknown"],
|
||||
content_state: entry.code === "limit" ? "too-large" : "unreadable",
|
||||
limitations: [entry.message],
|
||||
};
|
||||
};
|
||||
|
||||
const resolveInternalSpecifier = (
|
||||
fromPath: string,
|
||||
specifier: string,
|
||||
filePaths: ReadonlySet<string>,
|
||||
): { to: string; resolution: "internal" | "unresolved" } => {
|
||||
const normalized = posix.normalize(
|
||||
posix.join(posix.dirname(fromPath), specifier),
|
||||
);
|
||||
if (normalized.startsWith("../") || normalized === "..")
|
||||
return { to: normalized, resolution: "unresolved" };
|
||||
const suffixes = ["", ".ts", ".js", ".mjs", ".cjs", ".tsx", ".jsx"];
|
||||
const candidates = suffixes.flatMap((suffix) => [
|
||||
`${normalized}${suffix}`,
|
||||
`${normalized}/index${suffix}`,
|
||||
]);
|
||||
const match = candidates.find((candidate) => filePaths.has(candidate));
|
||||
return match === undefined
|
||||
? { to: normalized, resolution: "unresolved" }
|
||||
: { to: match, resolution: "internal" };
|
||||
};
|
||||
|
||||
const appendFile = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>,
|
||||
filePaths: ReadonlySet<string>,
|
||||
output: ParsedReferenceSourceEntries,
|
||||
): void => {
|
||||
const language = detectReferenceSourceLanguage(entry.path);
|
||||
output.entries.push({
|
||||
path: entry.path,
|
||||
kind: "file",
|
||||
sha256: hashBytes(entry.bytes),
|
||||
size: entry.size,
|
||||
language,
|
||||
classifications: classifyReferenceSourcePath(entry.path),
|
||||
content_state: "hashed",
|
||||
limitations: [],
|
||||
});
|
||||
if (language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language))
|
||||
return;
|
||||
const parsed = parseReferenceSourceImports(entry.path, entry.bytes, language);
|
||||
for (const relationship of parsed.relationships) {
|
||||
if (relationship.resolution !== "internal") {
|
||||
output.relationships.push(relationship);
|
||||
continue;
|
||||
}
|
||||
const resolved = resolveInternalSpecifier(
|
||||
relationship.from_path,
|
||||
relationship.to,
|
||||
filePaths,
|
||||
);
|
||||
output.relationships.push({
|
||||
...relationship,
|
||||
to: resolved.to,
|
||||
resolution: resolved.resolution,
|
||||
});
|
||||
}
|
||||
output.parseFailures.push(...parsed.parse_failures);
|
||||
};
|
||||
|
||||
const appendReadEntry = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "read" }>,
|
||||
filePaths: ReadonlySet<string>,
|
||||
output: ParsedReferenceSourceEntries,
|
||||
): void => {
|
||||
if (entry.kind === "file") {
|
||||
appendFile(entry, filePaths, output);
|
||||
return;
|
||||
}
|
||||
const classifications = classifyReferenceSourcePath(entry.path);
|
||||
if (entry.kind === "directory") {
|
||||
output.entries.push({
|
||||
path: entry.path,
|
||||
kind: "directory",
|
||||
classifications,
|
||||
tree_state: "enumerated",
|
||||
limitations: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
output.entries.push({
|
||||
path: entry.path,
|
||||
kind: "symlink",
|
||||
target: entry.target,
|
||||
target_state: entry.targetState,
|
||||
classifications,
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
/** Convert bounded reader observations into graph entries and parsed edges. */
|
||||
export const parseReferenceSourceEntries = (
|
||||
read: ReferenceSourceRead,
|
||||
filePaths: ReadonlySet<string>,
|
||||
signal?: AbortSignal,
|
||||
): ParsedReferenceSourceEntries => {
|
||||
const output: ParsedReferenceSourceEntries = {
|
||||
entries: [],
|
||||
relationships: [],
|
||||
parseFailures: [],
|
||||
limitations: [...read.limitations],
|
||||
};
|
||||
for (const entry of read.entries) {
|
||||
if (signal?.aborted === true) break;
|
||||
if (entry.status === "failed") output.entries.push(failedEntry(entry));
|
||||
else appendReadEntry(entry, filePaths, output);
|
||||
}
|
||||
return output;
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
import { readFile, realpath, stat } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import ignore from "ignore";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ReferenceSourceLimits } from "../reference/ReferenceSourceReader.js";
|
||||
import { withinRoot } from "../reference/ReferenceSourceReaderPaths.js";
|
||||
import {
|
||||
DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS,
|
||||
DEFAULT_REFERENCE_SOURCE_LIMITS,
|
||||
type ReferenceSourceImportError,
|
||||
type ReferenceSourceImportOptions,
|
||||
} from "./ReferenceSourceImportTypes.js";
|
||||
|
||||
/** Validated, authorized inputs ready for filesystem traversal. */
|
||||
export interface PreparedReferenceSourceImport {
|
||||
readonly root: string;
|
||||
readonly limits: ReferenceSourceLimits;
|
||||
readonly ignored: ReturnType<typeof ignore>;
|
||||
readonly secrets: ReturnType<typeof ignore>;
|
||||
}
|
||||
|
||||
const failure = (
|
||||
code: ReferenceSourceImportError["code"],
|
||||
message: string,
|
||||
): ReferenceSourceImportError => ({
|
||||
tag: "reference-source-import",
|
||||
code,
|
||||
message,
|
||||
});
|
||||
|
||||
const validLimits = (limits: ReferenceSourceLimits): boolean =>
|
||||
Object.values(limits).every(
|
||||
(value) => Number.isSafeInteger(value) && value > 0,
|
||||
);
|
||||
|
||||
const maximumLimits = (
|
||||
options: ReferenceSourceImportOptions,
|
||||
): ReferenceSourceLimits => ({
|
||||
maxBytes: options.policy.maxBytes,
|
||||
maxEntries: options.policy.maxEntries,
|
||||
maxDepth: options.policy.maxDepth,
|
||||
maxPathBytes: options.policy.maxPathBytes,
|
||||
});
|
||||
|
||||
const clampLimits = (
|
||||
requested: ReferenceSourceLimits,
|
||||
maximum: ReferenceSourceLimits,
|
||||
): ReferenceSourceLimits => ({
|
||||
maxBytes: Math.min(requested.maxBytes, maximum.maxBytes),
|
||||
maxEntries: Math.min(requested.maxEntries, maximum.maxEntries),
|
||||
maxDepth: Math.min(requested.maxDepth, maximum.maxDepth),
|
||||
maxPathBytes: Math.min(requested.maxPathBytes, maximum.maxPathBytes),
|
||||
});
|
||||
|
||||
const authorizeRoot = async (
|
||||
requestedRoot: string,
|
||||
approvedRoots: readonly string[],
|
||||
): Promise<Result<string, ReferenceSourceImportError>> => {
|
||||
if (approvedRoots.length === 0)
|
||||
return err(failure("policy", "No approved reference source roots"));
|
||||
try {
|
||||
if (!(await stat(requestedRoot)).isDirectory())
|
||||
return err(
|
||||
failure("invalid-root", "Reference source root is not a directory"),
|
||||
);
|
||||
const canonicalRoot = await realpath(resolve(requestedRoot));
|
||||
for (const approvedRoot of approvedRoots) {
|
||||
const canonicalApproved = await realpath(resolve(approvedRoot));
|
||||
if (withinRoot(canonicalApproved, canonicalRoot))
|
||||
return ok(canonicalRoot);
|
||||
}
|
||||
return err(
|
||||
failure("policy", "Reference source root is outside approved roots"),
|
||||
);
|
||||
} catch {
|
||||
return err(
|
||||
failure("invalid-root", "Reference source root could not be resolved"),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const buildIgnored = async (
|
||||
root: string,
|
||||
excludePaths: readonly string[],
|
||||
): Promise<ReturnType<typeof ignore>> => {
|
||||
const ignored = ignore();
|
||||
try {
|
||||
ignored.add(await readFile(join(root, ".gitignore"), "utf8"));
|
||||
} catch {
|
||||
// Missing or unreadable ignore file does not authorize broader access.
|
||||
}
|
||||
ignored.add([...DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS]);
|
||||
for (const path of excludePaths) {
|
||||
ignored.add(path);
|
||||
ignored.add(`${path}/`);
|
||||
}
|
||||
return ignored;
|
||||
};
|
||||
|
||||
/** Validate limits, authorize root, and build non-executing path filters. */
|
||||
export const prepareReferenceSourceImport = async (
|
||||
options: ReferenceSourceImportOptions,
|
||||
): Promise<
|
||||
Result<PreparedReferenceSourceImport, ReferenceSourceImportError>
|
||||
> => {
|
||||
const requested = options.limits ?? DEFAULT_REFERENCE_SOURCE_LIMITS;
|
||||
const maximum = maximumLimits(options);
|
||||
if (!validLimits(requested) || !validLimits(maximum))
|
||||
return err(
|
||||
failure("invalid-limits", "Import limits must be positive integers"),
|
||||
);
|
||||
const root = await authorizeRoot(options.root, options.policy.roots);
|
||||
if (!root.ok) return root;
|
||||
return ok({
|
||||
root: root.value,
|
||||
limits: clampLimits(requested, maximum),
|
||||
ignored: await buildIgnored(root.value, options.excludePaths ?? []),
|
||||
secrets: ignore().add([...options.policy.secretPatterns]),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
|
||||
import type { ReferenceSourceLimits } from "../reference/ReferenceSourceReader.js";
|
||||
|
||||
/** Typed expected failure returned by historical-source imports. */
|
||||
export interface ReferenceSourceImportError {
|
||||
readonly tag: "reference-source-import";
|
||||
readonly code:
|
||||
| "cancelled"
|
||||
| "invalid-limits"
|
||||
| "invalid-root"
|
||||
| "io"
|
||||
| "parse"
|
||||
| "policy"
|
||||
| "limit";
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Bounded import request paired with mandatory operator policy. */
|
||||
export interface ReferenceSourceImportOptions {
|
||||
readonly root: string;
|
||||
readonly limits?: ReferenceSourceLimits;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly caller: string;
|
||||
readonly policy: ReferenceSourcePolicy;
|
||||
readonly importer?: string;
|
||||
readonly importerVersion?: string | null;
|
||||
readonly excludePaths?: readonly string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS = [
|
||||
".git/",
|
||||
".git/hooks/",
|
||||
"node_modules/",
|
||||
"dist/",
|
||||
"build/",
|
||||
"coverage/",
|
||||
"htmlcov/",
|
||||
".coverage",
|
||||
"*.log",
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_REFERENCE_SOURCE_LIMITS: ReferenceSourceLimits = {
|
||||
maxBytes: 16 * 1024 * 1024,
|
||||
maxEntries: 10_000,
|
||||
maxDepth: 32,
|
||||
maxPathBytes: 4_096,
|
||||
};
|
||||
|
||||
export const PARSEABLE_REFERENCE_SOURCE_LANGUAGES: ReadonlySet<string> =
|
||||
new Set(["JavaScript", "TypeScript", "JSX", "TSX"]);
|
||||
@@ -0,0 +1,55 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
import { log, statusMatrix } from "isomorphic-git";
|
||||
|
||||
export type ReferenceSourceVcsInfo =
|
||||
| { readonly kind: "git"; readonly head: string; readonly dirty: boolean }
|
||||
| { readonly kind: "none"; readonly head: null; readonly dirty: null }
|
||||
| { readonly kind: "unknown"; readonly head: null; readonly dirty: null };
|
||||
|
||||
/**
|
||||
* Read Git metadata for a directory using isomorphic-git.
|
||||
*
|
||||
* No git subprocess or network is used; only the local `.git` object store is read.
|
||||
*/
|
||||
export const readReferenceSourceVcs = async (
|
||||
root: string,
|
||||
): Promise<ReferenceSourceVcsInfo> => {
|
||||
try {
|
||||
const commits = await log({
|
||||
fs,
|
||||
dir: root,
|
||||
ref: "HEAD",
|
||||
depth: 1,
|
||||
cache: {},
|
||||
});
|
||||
if (commits.length === 0)
|
||||
return { kind: "unknown", head: null, dirty: null };
|
||||
|
||||
const head = commits[0]?.oid;
|
||||
if (head === undefined) return { kind: "unknown", head: null, dirty: null };
|
||||
|
||||
let dirty = false;
|
||||
try {
|
||||
const matrix = await statusMatrix({
|
||||
fs,
|
||||
dir: root,
|
||||
ref: head,
|
||||
cache: {},
|
||||
});
|
||||
for (const row of matrix) {
|
||||
const [, headStatus, workdirStatus, stageStatus] = row;
|
||||
if (headStatus !== 1 || workdirStatus !== 1 || stageStatus !== 1) {
|
||||
dirty = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
return { kind: "git", head, dirty };
|
||||
} catch {
|
||||
return { kind: "none", head: null, dirty: null };
|
||||
}
|
||||
};
|
||||
@@ -12,6 +12,7 @@ import { dirname, join } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { z } from "zod";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { runDoctor, systemDoctorHost } from "./Doctor.js";
|
||||
@@ -267,7 +268,8 @@ export const configureJsonClient = async (
|
||||
};
|
||||
};
|
||||
|
||||
const installCanonicalSkill = async (
|
||||
/** Transactionally install or upgrade the versioned canonical REA skill. */
|
||||
export const installCanonicalSkill = async (
|
||||
home: string,
|
||||
): Promise<"installed" | "unchanged" | "failed"> => {
|
||||
const destination = join(
|
||||
@@ -276,6 +278,8 @@ const installCanonicalSkill = async (
|
||||
PRODUCT_IDENTITY.skillName,
|
||||
"SKILL.md",
|
||||
);
|
||||
const backup = `${destination}.rea.backup`;
|
||||
let original: string | undefined;
|
||||
try {
|
||||
const content = await readFile(
|
||||
new URL(
|
||||
@@ -284,16 +288,32 @@ const installCanonicalSkill = async (
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
if (
|
||||
(await readFile(destination, "utf8").catch(() => undefined)) === content
|
||||
)
|
||||
return "unchanged";
|
||||
original = await readFile(destination, "utf8").catch(() => undefined);
|
||||
if (original === content) return "unchanged";
|
||||
await mkdir(dirname(destination), { recursive: true });
|
||||
await writeFile(destination, content, { encoding: "utf8", mode: 0o600 });
|
||||
return (await readFile(destination, "utf8")) === content
|
||||
? "installed"
|
||||
: "failed";
|
||||
if (original !== undefined)
|
||||
await writeFileAtomic(backup, original, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
await writeFileAtomic(destination, content, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
if ((await readFile(destination, "utf8")) !== content)
|
||||
throw new Error("skill readback mismatch");
|
||||
return "installed";
|
||||
} catch {
|
||||
try {
|
||||
if (original === undefined) await rm(destination, { force: true });
|
||||
else
|
||||
await writeFileAtomic(destination, original, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
} catch {
|
||||
// The backup remains beside the skill for explicit operator recovery.
|
||||
}
|
||||
return "failed";
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { AppConfig } from "../config.js";
|
||||
import { BinarySession } from "./BinarySession.js";
|
||||
import { HopperProvider } from "../hopper/HopperProvider.js";
|
||||
import { NativeMacOSProvider } from "../native/NativeMacOSProvider.js";
|
||||
import { ArtifactProvider } from "../artifacts/ArtifactProvider.js";
|
||||
import { CompositeProvider } from "./CompositeProvider.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
|
||||
/**
|
||||
@@ -12,5 +15,11 @@ export const createBinarySession = (
|
||||
config: AppConfig,
|
||||
logger: Logger = silentLogger,
|
||||
): BinarySession => {
|
||||
return new BinarySession(new HopperProvider(config, logger));
|
||||
return new BinarySession(
|
||||
new CompositeProvider([
|
||||
new ArtifactProvider(),
|
||||
new NativeMacOSProvider(),
|
||||
new HopperProvider(config, logger),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user