chore: merge main into feat/pkg-inventory
Resolve conflicts against main: - Inventory moved to src/artifacts/inventory (#1032); point the xar and cpio reader imports at their new relative paths. - README.md: take main's simplified English README, which no longer lists individual package formats. PKG coverage stays documented in the skill reference and docs/testing.md. - Skill: the references gain the PKG paragraph, so the version moves to 29 (main already uses 28). - Regenerate the product catalog, conformance manifest, skill digest and package metadata. The MCP tool catalog is now built rather than committed (#997), so it is removed here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -316,6 +316,7 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
],
|
||||
cwd: root.path,
|
||||
hostEnvironment: this.environment,
|
||||
signal,
|
||||
},
|
||||
this.launcher,
|
||||
);
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { compareDirectoryChildNames } from "./ArtifactGraphConstruction.js";
|
||||
|
||||
const tiedNames = ["a.txt", "a\u200b.txt", "a\u200c.txt", "a\u200d.txt"];
|
||||
|
||||
describe("directory child-name ordering", () => {
|
||||
it("orders the tied subset lexically with reflexivity and antisymmetry", () => {
|
||||
for (const left of tiedNames) {
|
||||
expect(compareDirectoryChildNames(left, left)).toBe(0);
|
||||
for (const right of tiedNames) {
|
||||
expect(left.localeCompare(right)).toBe(0);
|
||||
const compared = compareDirectoryChildNames(left, right);
|
||||
const lexical = left < right ? -1 : left > right ? 1 : 0;
|
||||
expect(compared).toBe(lexical);
|
||||
expect(compared + compareDirectoryChildNames(right, left)).toBe(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("is transitive across the tied subset", () => {
|
||||
for (const first of tiedNames)
|
||||
for (const second of tiedNames)
|
||||
for (const third of tiedNames)
|
||||
if (
|
||||
compareDirectoryChildNames(first, second) <= 0 &&
|
||||
compareDirectoryChildNames(second, third) <= 0
|
||||
)
|
||||
expect(
|
||||
compareDirectoryChildNames(first, third),
|
||||
).toBeLessThanOrEqual(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a.txt", "b.txt"],
|
||||
["z.txt", "ä.txt"],
|
||||
["Z", "a"],
|
||||
["a/data.txt", "b/data.txt"],
|
||||
])("preserves the current non-tied collation for %s / %s", (left, right) => {
|
||||
const collated = left.localeCompare(right);
|
||||
expect(collated).not.toBe(0);
|
||||
expect(compareDirectoryChildNames(left, right)).toBe(collated);
|
||||
expect(compareDirectoryChildNames(right, left)).toBe(
|
||||
right.localeCompare(left),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveArtifactIntegrityPolicy } from "./ArtifactInventory/policy.js";
|
||||
|
||||
describe("artifact inventory policy resolution", () => {
|
||||
it("preserves the selected integrity behavior without disabling verification", () => {
|
||||
expect(resolveArtifactIntegrityPolicy({ mode: "fail" })).toEqual({
|
||||
mode: "fail",
|
||||
});
|
||||
expect(
|
||||
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }),
|
||||
).toEqual({ mode: "record-and-continue" });
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import {
|
||||
scanCanonicalArtifactInventory,
|
||||
type ArtifactInventoryOptions,
|
||||
type ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory.js";
|
||||
|
||||
/** Resolve, authorize, and scan one artifact without a second path resolution. */
|
||||
export const scanAuthorizedArtifactInventory = async (
|
||||
inputPath: string,
|
||||
options: ArtifactInventoryOptions = {},
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const path = await realpath(inputPath);
|
||||
return scanCanonicalArtifactInventory(path, options);
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { toolAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
|
||||
describe("capability inventory contract", () => {
|
||||
it("produces valid availability and rejects contradictory states", () => {
|
||||
const inventory = buildCapabilityInventory(
|
||||
{ open: false, capabilities: [] },
|
||||
{
|
||||
processCaptureEnabled: false,
|
||||
},
|
||||
);
|
||||
const unavailable = inventory.find(({ available }) => !available);
|
||||
expect(unavailable).toBeDefined();
|
||||
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
|
||||
expect(
|
||||
toolAvailability.safeParse({ ...unavailable, available: true }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
toolAvailability.safeParse({
|
||||
...unavailable,
|
||||
available: false,
|
||||
reason: "available",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { toolAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
|
||||
it("reports module syntax and native resolution availability separately", () => {
|
||||
@@ -249,6 +250,23 @@ describe("capability inventory: caller guidance", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the public availability schema consistent with generated states", () => {
|
||||
const inventory = buildCapabilityInventory(status(), enabledPolicy);
|
||||
const unavailable = inventory.find(({ available }) => !available);
|
||||
expect(unavailable).toBeDefined();
|
||||
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
|
||||
expect(
|
||||
toolAvailability.safeParse({ ...unavailable, available: true }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
toolAvailability.safeParse({
|
||||
...unavailable,
|
||||
available: false,
|
||||
reason: "available",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not require interactive elicitation for process capture", () => {
|
||||
const withoutElicitation = buildCapabilityInventory(
|
||||
status(),
|
||||
|
||||
@@ -5,6 +5,8 @@ import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import { executeFunctionAnalysisEvidence } from "./FunctionAnalysisEvidence.js";
|
||||
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
|
||||
import type { BinarySession } from "./binary/BinarySession.js";
|
||||
import type { SessionProviderRoute } from "./binary/SessionProviderRouter.js";
|
||||
import type { ResolvedSessionOpen } from "./binary/BinarySessionOpen.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
@@ -28,10 +30,17 @@ import {
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotMatchesTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
committedProviderSchema,
|
||||
type AnalysisProfileCommitment,
|
||||
} from "../domain/analysisProfile.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type { AnalysisExecution } from "./AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
@@ -194,7 +203,42 @@ const runAnalysis = async (
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
const { snapshot } = prepared.value;
|
||||
const opened = await session.open(path, {
|
||||
let resolvedTarget: ResolvedSessionOpen | undefined;
|
||||
if (snapshot !== undefined && prepared.value.target !== undefined) {
|
||||
const preview = await session.previewTarget(prepared.value.target, {
|
||||
signal,
|
||||
snapshot,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
});
|
||||
if (!preview.ok) return cliError(preview.error);
|
||||
resolvedTarget = preview.value;
|
||||
const route = preview.value.route;
|
||||
const bindingProfile = route.profile ?? undefined;
|
||||
const evidenceProfile = analysisProfileForRoute(route, tool);
|
||||
if (
|
||||
bindingProfile !== undefined &&
|
||||
evidenceProfile !== undefined &&
|
||||
allowsSnapshotReplay(route, tool)
|
||||
) {
|
||||
const cached = snapshotEvidenceForQuery(snapshot, {
|
||||
target: preview.value.target,
|
||||
bindingProfile,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider: isWorkflowEvidenceTool(tool)
|
||||
? REA_WORKFLOW_PROVIDER
|
||||
: providerIdentityForRoute(route, tool),
|
||||
evidenceProfile,
|
||||
});
|
||||
if (cached !== undefined) return cached;
|
||||
}
|
||||
}
|
||||
const openOptions = {
|
||||
signal,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
@@ -203,26 +247,13 @@ const runAnalysis = async (
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
});
|
||||
};
|
||||
const opened =
|
||||
resolvedTarget === undefined
|
||||
? await session.open(path, openOptions)
|
||||
: await session.openResolvedTarget(resolvedTarget, openOptions);
|
||||
if (!opened.ok) return cliError(opened.error);
|
||||
const evidenceProfile = analysisProfileForEvidence(session, tool);
|
||||
const bindingProfile = session.analysisProfile();
|
||||
if (
|
||||
canReplayDirectTool(session, tool) &&
|
||||
snapshot !== undefined &&
|
||||
evidenceProfile !== undefined &&
|
||||
bindingProfile !== undefined
|
||||
) {
|
||||
const cached = snapshotEvidenceForQuery(snapshot, {
|
||||
target: opened.value,
|
||||
bindingProfile,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider: replayProviderFor(session, tool),
|
||||
evidenceProfile,
|
||||
});
|
||||
if (cached !== undefined) return cached;
|
||||
}
|
||||
const { output, evidence } = await executeAnalysisTool({
|
||||
session,
|
||||
openedTarget: opened.value,
|
||||
@@ -232,6 +263,41 @@ const runAnalysis = async (
|
||||
evidenceProfile,
|
||||
});
|
||||
if (evidence !== undefined) session.recordEvidence(evidence);
|
||||
if (
|
||||
isWorkflowEvidenceTool(tool) &&
|
||||
tool !== "trace_native_ui_action" &&
|
||||
snapshotPath !== undefined &&
|
||||
evidence !== undefined &&
|
||||
"analysis_profile" in evidence &&
|
||||
session.allowsSnapshotReplay(tool)
|
||||
) {
|
||||
const recorded = session.recordWorkflowSnapshot({
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
execution: {
|
||||
result: evidence.normalized_result,
|
||||
rawResult: evidence.raw_result,
|
||||
provider: committedProviderSchema.parse(evidence.provider),
|
||||
analysisProfile: analysisProfileSchema.parse(
|
||||
evidence.analysis_profile,
|
||||
),
|
||||
limitations: evidence.limitations,
|
||||
locations: evidence.locations,
|
||||
subject:
|
||||
evidence.subject === null
|
||||
? null
|
||||
: {
|
||||
path: evidence.subject.local_path,
|
||||
sha256: evidence.subject.digest.sha256,
|
||||
format: evidence.subject.format,
|
||||
...(evidence.subject.architecture === null
|
||||
? {}
|
||||
: { architecture: evidence.subject.architecture }),
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!recorded.ok) return cliError(recorded.error);
|
||||
}
|
||||
if (
|
||||
tool !== "trace_native_ui_action" &&
|
||||
snapshotPath !== undefined &&
|
||||
@@ -252,12 +318,6 @@ const runAnalysis = async (
|
||||
}
|
||||
};
|
||||
|
||||
const canReplayDirectTool = (
|
||||
session: BinarySession,
|
||||
tool: Parameters<typeof runAnalysis>[2],
|
||||
): boolean =>
|
||||
tool !== "trace_native_ui_action" && session.allowsSnapshotReplay(tool);
|
||||
|
||||
const executeAnalysisTool = async (input: {
|
||||
readonly session: BinarySession;
|
||||
readonly openedTarget: BinaryTarget;
|
||||
@@ -353,7 +413,10 @@ const prepareSnapshot = async (options: {
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly snapshotPath: string | undefined;
|
||||
}): Promise<
|
||||
Result<{ readonly snapshot?: AnalysisSnapshot }, AnalysisError>
|
||||
Result<
|
||||
{ readonly snapshot?: AnalysisSnapshot; readonly target?: BinaryTarget },
|
||||
AnalysisError
|
||||
>
|
||||
> => {
|
||||
const { path, snapshotPath } = options;
|
||||
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
|
||||
@@ -374,20 +437,52 @@ const prepareSnapshot = async (options: {
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
),
|
||||
);
|
||||
return ok({ snapshot: loaded.value });
|
||||
return ok({ snapshot: loaded.value, target: target.value });
|
||||
};
|
||||
|
||||
const replayProviderFor = (
|
||||
session: BinarySession,
|
||||
const allowsSnapshotReplay = (
|
||||
route: SessionProviderRoute,
|
||||
tool:
|
||||
| NativeToolName
|
||||
| ArtifactAnalysisOperation
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool,
|
||||
) =>
|
||||
isWorkflowEvidenceTool(tool)
|
||||
? REA_WORKFLOW_PROVIDER
|
||||
: session.providerIdentity(tool);
|
||||
): boolean => {
|
||||
if (tool === "trace_native_ui_action") return false;
|
||||
const descriptor = route.capabilities?.get(tool);
|
||||
return descriptor === undefined
|
||||
? ![...(route.capabilities?.values() ?? [])].some(
|
||||
({ cachePolicy }) => cachePolicy === "live",
|
||||
)
|
||||
: descriptor.cachePolicy !== "live";
|
||||
};
|
||||
|
||||
const analysisProfileForRoute = (
|
||||
route: SessionProviderRoute,
|
||||
tool:
|
||||
| NativeToolName
|
||||
| ArtifactAnalysisOperation
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool,
|
||||
): AnalysisProfileCommitment | undefined => {
|
||||
const profile = route.profile;
|
||||
if (profile === null || profile === undefined) return undefined;
|
||||
if (isWorkflowEvidenceTool(tool)) return workflowAnalysisProfile(profile);
|
||||
const provider = providerIdentityForRoute(route, tool);
|
||||
return provider.id === profile.provider.id ? profile : undefined;
|
||||
};
|
||||
|
||||
/** Mirror BinarySession.providerIdentity for a route not opened yet. */
|
||||
const providerIdentityForRoute = (
|
||||
route: SessionProviderRoute,
|
||||
operation: string,
|
||||
): ProviderIdentity => {
|
||||
const selected =
|
||||
route.capabilities?.get(operation)?.provider ?? route.identity;
|
||||
return route.profile?.provider.id === selected.id
|
||||
? route.profile.provider
|
||||
: selected;
|
||||
};
|
||||
|
||||
const analysisProfileForEvidence = (
|
||||
session: BinarySession,
|
||||
|
||||
@@ -22,7 +22,7 @@ describe("doctor", () => {
|
||||
),
|
||||
).toEqual({
|
||||
node: `Install ${SUPPORTED_NODE_VERSION_PROSE}.`,
|
||||
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
|
||||
target: "Supply a readable local app or program path.",
|
||||
});
|
||||
|
||||
@@ -115,7 +115,7 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
|
||||
: `${linuxDistribution.id} ${linuxDistribution.versionId ?? "unknown"}`);
|
||||
return check("host", supported, detail, {
|
||||
remediation:
|
||||
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
classification: "unsupported_host",
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ok } from "../domain/result.js";
|
||||
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
|
||||
|
||||
describe("literal feature tracing", () => {
|
||||
it("returns matched procedure and string facts with references", async () => {
|
||||
const result = await traceLiteralFeature(
|
||||
async (name) => {
|
||||
if (name === "search_strings")
|
||||
return ok([{ address: "0x1000", value: "launch feature" }]);
|
||||
if (name === "search_procedures")
|
||||
return ok([{ address: "0x2000", value: "launchFeature" }]);
|
||||
if (name === "xrefs") return ok([]);
|
||||
if (name === "resolve_containing_procedure") return ok(null);
|
||||
throw new Error(`Unexpected analysis call: ${name}`);
|
||||
},
|
||||
{ query: "launch feature", case_sensitive: false },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
matches: [
|
||||
{ type: "string", address: "0x1000", value: "launch feature" },
|
||||
{ type: "procedure", address: "0x2000", value: "launchFeature" },
|
||||
],
|
||||
references: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
EvidenceIntegrityError,
|
||||
} from "../domain/evidenceErrors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
import { parseProcessCapture } from "../domain/process/processCapture.js";
|
||||
import { readJsonFile, writeTextFile } from "./JsonFiles.js";
|
||||
|
||||
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
|
||||
@@ -59,6 +59,7 @@ describe("Linux Hopper host classification", () => {
|
||||
['ID=ubuntu\nVERSION_ID="24.04"\n', "deb"],
|
||||
["ID=fedora\nVERSION_ID=41\n", "rpm"],
|
||||
["ID=arch\n", "arch"],
|
||||
["ID=cachyos\nID_LIKE=arch\n", "arch"],
|
||||
] as const)("accepts an official Hopper distribution", (document, family) => {
|
||||
expect(parseLinuxDistribution(document)).toMatchObject({
|
||||
packageFamily: family,
|
||||
@@ -88,6 +89,8 @@ describe("Linux Hopper host classification", () => {
|
||||
'ID=ubuntu\nVERSION_ID="22.04"\n',
|
||||
"ID=fedora\nVERSION_ID=40\n",
|
||||
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
|
||||
"ID=manjaro\nID_LIKE=arch\n",
|
||||
"ID=garuda\nID_LIKE=arch\n",
|
||||
])("rejects unsupported vendor/version combinations", (document) => {
|
||||
expect(parseLinuxDistribution(document).supported).toBe(false);
|
||||
});
|
||||
|
||||
@@ -150,6 +150,7 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
|
||||
const supported =
|
||||
packageFamily !== undefined &&
|
||||
(id === "arch" ||
|
||||
id === "cachyos" ||
|
||||
(id === "ubuntu" && versionAtLeast(versionId, 24)) ||
|
||||
(id === "fedora" && versionAtLeast(versionId, 41)));
|
||||
const identity = {
|
||||
|
||||
@@ -1,479 +0,0 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { IPty } from "@lydell/node-pty";
|
||||
|
||||
import type {
|
||||
FilesystemCheckpoint,
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessSample,
|
||||
ProcessSettlement,
|
||||
ProcessScenario,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
RecordProcessCaptureEvent,
|
||||
TerminalFrame,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
} from "../domain/processCapture.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import type { SnapshotResult } from "./FilesystemSnapshot.js";
|
||||
import { snapshotRoots } from "./FilesystemSnapshot.js";
|
||||
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
|
||||
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
||||
import { observeOwnedProcessGroup } from "../process/ProcessOwnershipObservation.js";
|
||||
import { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js";
|
||||
import {
|
||||
normalizeProcessElapsedTime,
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessText,
|
||||
} from "./ProcessNormalization.js";
|
||||
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import { scheduleProcessInterval, type ProcessTimer } from "./ProcessTimer.js";
|
||||
|
||||
interface TerminalExitOptions {
|
||||
readonly terminal: IPty;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly started: number;
|
||||
readonly lastOutput: () => number;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly timers: Set<ProcessTimer>;
|
||||
readonly interactions: InteractionEvent[];
|
||||
readonly dispatchedEventIndexes: ReadonlySet<number>;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}
|
||||
|
||||
interface CaptureResultOptions {
|
||||
readonly frames: readonly TerminalFrame[];
|
||||
readonly exit: {
|
||||
readonly exitCode: number;
|
||||
readonly signal?: number;
|
||||
readonly reason: "exited" | "timeout" | "idle_timeout";
|
||||
};
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly before: SnapshotResult;
|
||||
readonly after: SnapshotResult;
|
||||
readonly truncated: boolean;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly rootPid: number;
|
||||
readonly samplingPartial: boolean;
|
||||
readonly renderedFrames: UnverifiedProcessCapture["rendered_frames"];
|
||||
readonly interactions: readonly InteractionEvent[];
|
||||
readonly checkpoints: readonly FilesystemCheckpoint[];
|
||||
readonly settlement: ObservedProcessSettlement;
|
||||
readonly manifest: UnverifiedProcessCapture["manifest"];
|
||||
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
|
||||
}
|
||||
|
||||
/** Settlement observation before process-resource cleanup has completed. */
|
||||
export type ObservedProcessSettlement =
|
||||
| Pick<
|
||||
Extract<ProcessSettlement, { readonly state: "quiesced" }>,
|
||||
"state" | "elapsed_ms"
|
||||
>
|
||||
| Pick<
|
||||
Exclude<ProcessSettlement, { readonly state: "quiesced" }>,
|
||||
"state" | "elapsed_ms"
|
||||
>;
|
||||
|
||||
/** Capture observations before owned-resource cleanup has been verified. */
|
||||
export type PendingProcessCapture = Omit<
|
||||
UnverifiedProcessCapture,
|
||||
"cleanup" | "settlement"
|
||||
> & {
|
||||
readonly settlement: ObservedProcessSettlement;
|
||||
};
|
||||
|
||||
/** Wait for trailing PTY callbacks before the capture becomes immutable. */
|
||||
export const settleProcessCaptureJournal = async (
|
||||
journal: readonly ProcessCaptureEventJournalEntry[],
|
||||
quietMs = 25,
|
||||
maxWaitMs = 500,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + maxWaitMs;
|
||||
let observed = journal.length;
|
||||
let lastChangeAt = Date.now();
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 4));
|
||||
if (journal.length !== observed) {
|
||||
observed = journal.length;
|
||||
lastChangeAt = Date.now();
|
||||
} else if (Date.now() - lastChangeAt >= quietMs) return;
|
||||
}
|
||||
};
|
||||
|
||||
export const buildCaptureResult = (
|
||||
options: CaptureResultOptions,
|
||||
): PendingProcessCapture => {
|
||||
const hasSensitiveScriptedInput = options.scenario.events.some(
|
||||
(event) => event.type === "input" && event.sensitive,
|
||||
);
|
||||
const sensitiveInputUnknown =
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.";
|
||||
const filesystemObservationUnknown =
|
||||
"No filesystem observation paths were selected; filesystem effects remain unknown.";
|
||||
const hasFilesystemObservations =
|
||||
options.scenario.filesystem_observation_paths.length > 0;
|
||||
return {
|
||||
manifest: options.manifest,
|
||||
normalization: options.scenario.normalization,
|
||||
frames: options.frames,
|
||||
rendered_frames: options.renderedFrames,
|
||||
interaction_events: options.interactions,
|
||||
exit: {
|
||||
code:
|
||||
options.exit.reason === "exited" && options.exit.exitCode >= 0
|
||||
? options.exit.exitCode
|
||||
: null,
|
||||
signal: options.exit.signal ?? null,
|
||||
reason: options.exit.reason,
|
||||
},
|
||||
settlement: options.settlement,
|
||||
process_samples: normalizeProcessSamples(
|
||||
options.samples,
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
),
|
||||
filesystem_checkpoints: options.checkpoints,
|
||||
event_journal: options.eventJournal,
|
||||
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.",
|
||||
...(options.samplingPartial
|
||||
? ["Process-tree sampling ended with an incomplete observation."]
|
||||
: []),
|
||||
"Filesystem observations are before/after snapshots, not syscall traces.",
|
||||
"Inherited host environment variables are not recorded and may affect results.",
|
||||
...(!hasFilesystemObservations ? [filesystemObservationUnknown] : []),
|
||||
...(hasSensitiveScriptedInput ? [sensitiveInputUnknown] : []),
|
||||
],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "process",
|
||||
reason:
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
},
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
{
|
||||
scope: "network",
|
||||
reason: "Network activity is not observed by this capture.",
|
||||
},
|
||||
...(!hasFilesystemObservations
|
||||
? [
|
||||
{
|
||||
scope: "filesystem" as const,
|
||||
reason: filesystemObservationUnknown,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasSensitiveScriptedInput
|
||||
? [{ scope: "interaction" as const, reason: sensitiveInputUnknown }]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const hashFile = async (path: string): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
export const createRunManifest = async (
|
||||
scenario: ProcessScenario,
|
||||
startedAt: Date,
|
||||
completedAt: Date,
|
||||
host: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly architecture: NodeJS.Architecture;
|
||||
} = {
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
},
|
||||
): Promise<UnverifiedProcessCapture["manifest"]> => {
|
||||
const executableSha256 = await hashFile(scenario.executable);
|
||||
const scenarioCommitment = processScenarioCommitment(
|
||||
scenario,
|
||||
executableSha256,
|
||||
);
|
||||
const comparisonContract = processComparisonContract(scenario);
|
||||
return {
|
||||
rea_version: PRODUCT_IDENTITY.packageVersion,
|
||||
provider_version: PROCESS_PROVIDER.version,
|
||||
platform: host.platform,
|
||||
architecture: host.architecture,
|
||||
pty_backend: "node-pty",
|
||||
started_at: startedAt.toISOString(),
|
||||
completed_at: completedAt.toISOString(),
|
||||
scenario: scenarioCommitment,
|
||||
comparison_contract: comparisonContract,
|
||||
full_scenario_sha256: digestProcessCommitment(scenarioCommitment),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: executableSha256,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
};
|
||||
};
|
||||
|
||||
export const observeSettlement = async (
|
||||
runId: string,
|
||||
processGroupIds: readonly number[],
|
||||
settleMs: number,
|
||||
recordEvent: RecordProcessCaptureEvent = () => undefined,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Promise<ObservedProcessSettlement> => {
|
||||
if (platform === "win32") {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "unverifiable", elapsed_ms: 0 };
|
||||
}
|
||||
const started = Date.now();
|
||||
let consecutiveEmpty = 0;
|
||||
let deadlineReached = false;
|
||||
while (!deadlineReached) {
|
||||
const observations = await Promise.all(
|
||||
[...new Set(processGroupIds)].map((processGroupId) =>
|
||||
observeOwnedProcessGroup({
|
||||
runId,
|
||||
leaderPid: processGroupId,
|
||||
processGroupId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (observations.some(({ state }) => state === "unverifiable")) {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "unverifiable", elapsed_ms: Date.now() - started };
|
||||
}
|
||||
if (observations.every(({ state }) => state === "empty")) {
|
||||
consecutiveEmpty += 1;
|
||||
if (consecutiveEmpty >= 2) {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "quiesced", elapsed_ms: Date.now() - started };
|
||||
}
|
||||
} else consecutiveEmpty = 0;
|
||||
deadlineReached = Date.now() - started >= settleMs;
|
||||
if (deadlineReached) break;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "alive_at_deadline", elapsed_ms: Date.now() - started };
|
||||
};
|
||||
|
||||
export const awaitTerminalExit = async ({
|
||||
terminal,
|
||||
scenario,
|
||||
started,
|
||||
lastOutput,
|
||||
signal,
|
||||
timers,
|
||||
interactions,
|
||||
dispatchedEventIndexes,
|
||||
recordEvent,
|
||||
}: TerminalExitOptions): Promise<{
|
||||
exitCode: number;
|
||||
signal?: number;
|
||||
reason: "exited" | "timeout" | "idle_timeout" | "cancelled";
|
||||
}> =>
|
||||
new Promise((resolveExit) => {
|
||||
// The kill caused by a deadline is observed later as an ordinary PTY exit.
|
||||
// Keep the initiating lifecycle reason so comparisons distinguish a target
|
||||
// exit from harness-owned timeout, idle-timeout, and cancellation cleanup.
|
||||
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
|
||||
terminal.onExit((exit) => {
|
||||
recordEvent("lifecycle", 0);
|
||||
for (const [eventIndex, event] of scenario.events.entries()) {
|
||||
if (dispatchedEventIndexes.has(eventIndex)) continue;
|
||||
const sequence = interactions.length;
|
||||
interactions.push({
|
||||
sequence,
|
||||
scheduled_at_ms: event.at_ms,
|
||||
dispatched_at_ms: Math.max(0, Date.now() - started),
|
||||
type: event.type,
|
||||
data:
|
||||
event.type === "input"
|
||||
? "<not-dispatched>"
|
||||
: event.type === "resize"
|
||||
? `${String(event.columns)}x${String(event.rows)}`
|
||||
: event.signal,
|
||||
outcome: "target_exited",
|
||||
});
|
||||
recordEvent("interaction_events", sequence);
|
||||
}
|
||||
for (const timer of timers) {
|
||||
timer.cancel();
|
||||
}
|
||||
timers.clear();
|
||||
resolveExit({ ...exit, reason });
|
||||
});
|
||||
const timeout = scheduleProcessInterval(() => {
|
||||
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);
|
||||
});
|
||||
|
||||
/** Host operations used when releasing one captured process run. */
|
||||
export interface ProcessCaptureCleanupHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly cleanupProcessGroup: typeof cleanupOwnedProcessGroup;
|
||||
readonly removeTemporaryRoot: (path: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const processCaptureCleanupHost: ProcessCaptureCleanupHost = {
|
||||
platform: process.platform,
|
||||
cleanupProcessGroup: cleanupOwnedProcessGroup,
|
||||
removeTemporaryRoot: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
export const releaseProcessResources = async (options: {
|
||||
readonly timers: ReadonlySet<ProcessTimer>;
|
||||
readonly terminal: IPty | undefined;
|
||||
readonly renderer: TerminalRenderer | undefined;
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
readonly capturedProcessGroupIds: readonly number[];
|
||||
readonly host?: ProcessCaptureCleanupHost;
|
||||
}): Promise<string | undefined> => {
|
||||
const host = options.host ?? processCaptureCleanupHost;
|
||||
for (const timer of options.timers) timer.cancel();
|
||||
let failure: string | undefined;
|
||||
try {
|
||||
await options.renderer?.dispose();
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
failure ??= "terminal renderer cleanup failed";
|
||||
}
|
||||
if (options.terminal !== undefined && host.platform !== "win32") {
|
||||
for (const processGroupId of new Set(options.capturedProcessGroupIds)) {
|
||||
const cleaned = await host.cleanupProcessGroup({
|
||||
runId: options.runId,
|
||||
leaderPid: processGroupId,
|
||||
processGroupId,
|
||||
});
|
||||
if (!cleaned.cleaned) failure ??= cleaned.reason;
|
||||
}
|
||||
}
|
||||
try {
|
||||
await host.removeTemporaryRoot(options.temporaryRoot);
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
failure ??= "temporary process root cleanup failed";
|
||||
}
|
||||
return failure;
|
||||
};
|
||||
|
||||
export const captureTerminalFrames = (options: {
|
||||
readonly terminal: IPty;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly frames: TerminalFrame[];
|
||||
readonly started: number;
|
||||
readonly temporaryRoot: string;
|
||||
readonly onOutput: () => void;
|
||||
readonly renderer: TerminalRenderer;
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}): (() => boolean) => {
|
||||
let outputBytes = 0;
|
||||
let truncated = false;
|
||||
options.terminal.onData((data) => {
|
||||
options.onOutput();
|
||||
const bytes = Buffer.byteLength(data);
|
||||
if (outputBytes + bytes > options.scenario.limits.output_bytes) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
outputBytes += bytes;
|
||||
const atMs = normalizeProcessElapsedTime(
|
||||
Date.now() - options.started,
|
||||
options.scenario.normalization.time_bucket_ms,
|
||||
);
|
||||
const normalized = normalizeProcessText(
|
||||
data,
|
||||
options.scenario,
|
||||
options.temporaryRoot,
|
||||
options.terminal.pid,
|
||||
);
|
||||
const sequence = options.frames.length;
|
||||
options.frames.push({
|
||||
sequence,
|
||||
at_ms: atMs,
|
||||
data: normalized,
|
||||
});
|
||||
options.renderer.write(data, atMs);
|
||||
options.recordEvent("frames", sequence);
|
||||
});
|
||||
return () => truncated;
|
||||
};
|
||||
|
||||
export const resolveProcessResult = (
|
||||
capture: ProcessCapture | undefined,
|
||||
executionFailure: unknown,
|
||||
cleanupFailure: string | undefined,
|
||||
): ProcessCapture => {
|
||||
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
|
||||
if (executionFailure !== undefined)
|
||||
throw new ProcessCaptureError("process capture failed", {
|
||||
cause: executionFailure,
|
||||
});
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ProcessCaptureError(cleanupFailure, {
|
||||
reason: "cleanup_incomplete",
|
||||
});
|
||||
if (capture === undefined)
|
||||
throw new ProcessCaptureError("process capture produced no result");
|
||||
return capture;
|
||||
};
|
||||
|
||||
export const prepareProcessCapture = async (
|
||||
scenario: ProcessScenario,
|
||||
signal: AbortSignal | undefined,
|
||||
host: ProcessPreparationHost = systemProcessPreparationHost,
|
||||
): Promise<{
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
readonly before: SnapshotResult;
|
||||
}> => {
|
||||
assertNotCancelled(signal);
|
||||
const before = await snapshotRoots(scenario, signal);
|
||||
const temporaryRoot = await host.createTemporaryRoot();
|
||||
try {
|
||||
const runId = randomUUID();
|
||||
return { temporaryRoot, runId, before };
|
||||
} catch (cause: unknown) {
|
||||
await host.cleanup(temporaryRoot);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Filesystem seam for allocating and cleaning a capture's temporary root. */
|
||||
export interface ProcessPreparationHost {
|
||||
createTemporaryRoot(): Promise<string>;
|
||||
cleanup(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemProcessPreparationHost: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => mkdtemp(join(tmpdir(), "rea-process-")),
|
||||
cleanup: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { emptyUnverifiedProcessCapture } from "../domain/processCapture.fixture.js";
|
||||
import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
import { parseProcessScenario } from "../domain/processScenario.js";
|
||||
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
|
||||
import { observeSettlement } from "./ProcessCaptureLifecycle.js";
|
||||
|
||||
it("stamps process Evidence from the capture manifest host", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
working_directory: process.cwd(),
|
||||
events: [],
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
platform: "linux",
|
||||
architecture: "arm64",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
createProcessCaptureEvidence(scenario, capture).environment,
|
||||
).toMatchObject({
|
||||
id: "linux-arm64",
|
||||
platform: "linux",
|
||||
architecture: "arm64",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the selected host platform for process settlement behavior", async () => {
|
||||
const events: string[] = [];
|
||||
const result = await observeSettlement(
|
||||
"run",
|
||||
[],
|
||||
0,
|
||||
(event) => events.push(event),
|
||||
"win32",
|
||||
);
|
||||
|
||||
expect(result).toEqual({ state: "unverifiable", elapsed_ms: 0 });
|
||||
expect(events).toEqual(["lifecycle"]);
|
||||
});
|
||||
@@ -1,132 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
|
||||
import { createRunManifest } from "./ProcessCaptureLifecycle.js";
|
||||
import { emptyUnverifiedProcessCapture } from "../domain/processCapture.fixture.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
parseProcessScenario,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
} from "../domain/processScenario.js";
|
||||
|
||||
const captureEvidenceForSensitiveInput = (data: string) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/echo",
|
||||
working_directory: "/tmp",
|
||||
events: [{ type: "input", at_ms: 0, data, sensitive: true }],
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const executableSha256 = "0".repeat(64);
|
||||
const scenarioProjection = processScenarioCommitment(
|
||||
scenario,
|
||||
executableSha256,
|
||||
);
|
||||
const comparisonContract = processComparisonContract(scenario);
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "interaction",
|
||||
reason:
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.",
|
||||
},
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
],
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
scenario: scenarioProjection,
|
||||
comparison_contract: comparisonContract,
|
||||
full_scenario_sha256: digestProcessCommitment(scenarioProjection),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: executableSha256,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
},
|
||||
});
|
||||
return createProcessCaptureEvidence(scenario, capture);
|
||||
};
|
||||
|
||||
const captureEvidenceForEnvironmentSecret = async (value: string) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/echo",
|
||||
working_directory: "/tmp",
|
||||
environment: { API_TOKEN: value },
|
||||
events: [{ type: "input", at_ms: 0, data: value }],
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const manifest = await createRunManifest(scenario, new Date(0), new Date(1));
|
||||
const scenarioManifest = {
|
||||
...manifest,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
};
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "observed-output" }],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
],
|
||||
manifest: scenarioManifest,
|
||||
});
|
||||
return createProcessCaptureEvidence(scenario, capture);
|
||||
};
|
||||
|
||||
it("does not persist sensitive scripted input in process capture Evidence", () => {
|
||||
const secret = "top-secret-input";
|
||||
const evidence = captureEvidenceForSensitiveInput(secret);
|
||||
const serialized = JSON.stringify(evidence);
|
||||
const manifest = evidence.normalized_result;
|
||||
|
||||
expect(JSON.stringify(manifest)).not.toContain(secret);
|
||||
expect(JSON.stringify(evidence.parameters)).not.toContain(secret);
|
||||
expect(serialized).not.toContain(secret);
|
||||
});
|
||||
|
||||
it("does not treat captures with different redacted inputs as equivalent", () => {
|
||||
const left = captureEvidenceForSensitiveInput("secret-left");
|
||||
const right = captureEvidenceForSensitiveInput("secret-right");
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(
|
||||
parseProcessCapture(left.normalized_result),
|
||||
parseProcessCapture(right.normalized_result),
|
||||
),
|
||||
).toMatchObject({ status: "unknown", interaction: "unknown" });
|
||||
});
|
||||
|
||||
it("preserves selected local environment and input values", async () => {
|
||||
const left = await captureEvidenceForEnvironmentSecret("secret-left");
|
||||
const right = await captureEvidenceForEnvironmentSecret("secret-right");
|
||||
const serialized = JSON.stringify(left);
|
||||
const leftCapture = parseProcessCapture(left.normalized_result);
|
||||
const rightCapture = parseProcessCapture(right.normalized_result);
|
||||
|
||||
expect(serialized).toContain("secret-left");
|
||||
expect(leftCapture.manifest.scenario).toMatchObject({
|
||||
environment: { API_TOKEN: "secret-left" },
|
||||
});
|
||||
expect(leftCapture.manifest.scenario).not.toHaveProperty("PATH");
|
||||
expect(leftCapture.manifest.comparison_contract_sha256).not.toBe(
|
||||
rightCapture.manifest.comparison_contract_sha256,
|
||||
);
|
||||
|
||||
const changedOutput = parseProcessCapture({
|
||||
...leftCapture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "different-output" }],
|
||||
});
|
||||
expect(compareProcessCaptures(leftCapture, changedOutput)).toMatchObject({
|
||||
status: "changed",
|
||||
terminal: "changed",
|
||||
});
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { processScenarioSchema } from "../domain/processScenario.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
|
||||
import { captureProcessScenario } from "./ProcessHarness.js";
|
||||
import { settleProcessCaptureJournal } from "./ProcessCaptureLifecycle.js";
|
||||
import { processCaptureSchema } from "../domain/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
|
||||
it("rejects legacy replay output instead of silently discarding it", () => {
|
||||
expect(
|
||||
processCaptureSchema.safeParse({
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
protocol_events: [],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("waits for terminal observations delivered after the exit callback", async () => {
|
||||
const journal: Array<{
|
||||
capture_order: number;
|
||||
collection: "frames";
|
||||
index: number;
|
||||
}> = [{ capture_order: 0, collection: "frames", index: 0 }];
|
||||
const lateFrame = new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
journal.push({ capture_order: 1, collection: "frames", index: 1 });
|
||||
resolve();
|
||||
}, 12);
|
||||
});
|
||||
|
||||
let settled = false;
|
||||
const wait = settleProcessCaptureJournal(journal, 20, 200).then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await lateFrame;
|
||||
expect(settled).toBe(false);
|
||||
await wait;
|
||||
|
||||
expect(journal).toHaveLength(2);
|
||||
expect(journal[1]).toMatchObject({ collection: "frames", index: 1 });
|
||||
});
|
||||
|
||||
it("fails closed on Windows before resolving or launching scenario paths", async () => {
|
||||
const scenario = processScenarioSchema.parse({
|
||||
executable: "Z:/missing/should-never-be-resolved.exe",
|
||||
working_directory: "Z:/missing/working-directory",
|
||||
});
|
||||
const result = await captureProcessScenario(scenario, undefined, "win32");
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected Windows ownership refusal");
|
||||
if (!(result.error instanceof AnalysisCapabilityUnavailableError))
|
||||
throw new Error("expected a capability-unavailable outcome");
|
||||
expect(result.error).toMatchObject({
|
||||
operation: "capture_process_scenario",
|
||||
reason: expect.stringContaining("Windows PTY process capture"),
|
||||
});
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
category: "unsupported_provider",
|
||||
message: expect.stringContaining("does not yet verify descendant cleanup"),
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
reason: result.error.reason,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { normalizeProcessSamples } from "./ProcessNormalization.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
type ProcessSample,
|
||||
} from "../domain/processCapture.js";
|
||||
|
||||
const rootPid = 41_010;
|
||||
const samples = Object.freeze(
|
||||
[
|
||||
{
|
||||
at_ms: 17,
|
||||
pid: rootPid,
|
||||
parent_pid: 40_000,
|
||||
process_group_id: rootPid,
|
||||
session_id: rootPid,
|
||||
command: " root 41010 ",
|
||||
},
|
||||
{
|
||||
at_ms: 28,
|
||||
pid: 42_020,
|
||||
parent_pid: rootPid,
|
||||
process_group_id: 43_030,
|
||||
session_id: 44_040,
|
||||
command: "child 42020 parent 41010 group 43030 session 44040",
|
||||
},
|
||||
{
|
||||
at_ms: 39,
|
||||
pid: 45_050,
|
||||
parent_pid: 42_020,
|
||||
process_group_id: 43_030,
|
||||
session_id: 44_040,
|
||||
command: "peer 45050 unrelated 145050",
|
||||
},
|
||||
{
|
||||
at_ms: 41,
|
||||
pid: 46_060,
|
||||
parent_pid: 0,
|
||||
process_group_id: null,
|
||||
session_id: 0,
|
||||
command: "unknown 46060",
|
||||
},
|
||||
{
|
||||
at_ms: 52,
|
||||
pid: 47_070,
|
||||
parent_pid: 0,
|
||||
process_group_id: 0,
|
||||
session_id: null,
|
||||
command: "unavailable 47070",
|
||||
},
|
||||
].map((sample) =>
|
||||
Object.freeze({ ...sample, runtime_metadata: "must not be serialized" }),
|
||||
),
|
||||
);
|
||||
|
||||
it.each([false, true, undefined])(
|
||||
"projects only declared sample fields without mutating inputs when pids is %s",
|
||||
(pids) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/usr/bin/node",
|
||||
...(pids === undefined ? {} : { normalization: { pids } }),
|
||||
});
|
||||
const before = JSON.stringify(samples);
|
||||
const normalized = normalizeProcessSamples(samples, scenario, rootPid);
|
||||
const identities =
|
||||
pids === false
|
||||
? [
|
||||
[rootPid, 40_000, rootPid, rootPid],
|
||||
[42_020, rootPid, 43_030, 44_040],
|
||||
[45_050, 42_020, 43_030, 44_040],
|
||||
[46_060, 0, null, 0],
|
||||
[47_070, 0, 0, null],
|
||||
]
|
||||
: [
|
||||
[1, 2, 1, 1],
|
||||
[3, 1, 4, 5],
|
||||
[6, 3, 4, 5],
|
||||
[7, 0, null, 0],
|
||||
[8, 0, 0, null],
|
||||
];
|
||||
const commands =
|
||||
pids === false
|
||||
? samples.map(({ command }) => command.trim())
|
||||
: [
|
||||
"root <pid>",
|
||||
"child <pid> parent <pid> group <pid> session <pid>",
|
||||
"peer <pid> unrelated 145050",
|
||||
"unknown <pid>",
|
||||
"unavailable <pid>",
|
||||
];
|
||||
|
||||
expect(scenario.normalization.pids).toBe(pids ?? true);
|
||||
expect(normalized).toEqual(
|
||||
identities.map(
|
||||
([pid, parent_pid, process_group_id, session_id], index) => ({
|
||||
at_ms: (index + 1) * 10,
|
||||
pid,
|
||||
parent_pid,
|
||||
process_group_id,
|
||||
session_id,
|
||||
command: commands[index],
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(normalized).not.toBe(samples);
|
||||
for (const [index, sample] of normalized.entries()) {
|
||||
expect(sample).not.toBe(samples[index]);
|
||||
expect(Object.keys(sample).sort()).toEqual(
|
||||
[
|
||||
"at_ms",
|
||||
"pid",
|
||||
"parent_pid",
|
||||
"process_group_id",
|
||||
"session_id",
|
||||
"command",
|
||||
].sort(),
|
||||
);
|
||||
}
|
||||
expect(JSON.stringify(samples)).toBe(before);
|
||||
},
|
||||
);
|
||||
|
||||
for (const pids of [false, true]) {
|
||||
for (const paths of [false, true]) {
|
||||
it.each([false, true])(
|
||||
`keeps time, patterns, paths=${String(paths)}, and ports=%s independent of pids=${String(pids)}`,
|
||||
(ports) => {
|
||||
const sample: ProcessSample = Object.freeze({
|
||||
at_ms: 29,
|
||||
pid: 42_020,
|
||||
parent_pid: rootPid,
|
||||
process_group_id: 43_030,
|
||||
session_id: 44_040,
|
||||
command:
|
||||
" /workspace/program child 42020 parent 41010 group 43030 session 44040 listen:8080 marker ",
|
||||
});
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/usr/bin/node",
|
||||
working_directory: "/workspace",
|
||||
normalization: {
|
||||
pids,
|
||||
paths,
|
||||
ports,
|
||||
time_bucket_ms: 25,
|
||||
patterns: [{ pattern: "marker", replacement: "selected" }],
|
||||
},
|
||||
});
|
||||
const normalized = normalizeProcessSamples([sample], scenario, rootPid);
|
||||
const directory = paths ? "<working-directory>" : "/workspace";
|
||||
const identifiers = pids
|
||||
? "child <pid> parent <pid> group <pid> session <pid>"
|
||||
: "child 42020 parent 41010 group 43030 session 44040";
|
||||
expect(normalized).toEqual([
|
||||
{
|
||||
at_ms: 25,
|
||||
pid: pids ? 2 : 42_020,
|
||||
parent_pid: pids ? 1 : rootPid,
|
||||
process_group_id: pids ? 3 : 43_030,
|
||||
session_id: pids ? 4 : 44_040,
|
||||
command: `${directory}/program ${identifiers} listen:${ports ? "<port>" : "8080"} selected`,
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,14 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { emptyUnverifiedProcessCapture } from "../domain/process/processCapture.fixture.js";
|
||||
import { parseProcessCapture } from "../domain/process/processCapture.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
parseProcessScenario,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
} from "../domain/process/processScenario.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
@@ -14,6 +22,7 @@ import {
|
||||
} from "../domain/javascript/javascriptApplicationGraph.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { createProcessCaptureEvidence } from "./process/ProcessEvidence.js";
|
||||
import { deriveReconstructionObligationCandidates } from "./ReconstructionObligationCandidates.js";
|
||||
|
||||
const applicationWithUnknowns = (keys: readonly string[]) => {
|
||||
@@ -105,30 +114,13 @@ const unknownLimitation = (graphId: string, nodeId: string): string =>
|
||||
`Application graph ${graphId} contains unresolved node ${nodeId}; reconstruction obligations remain unknown.`;
|
||||
|
||||
describe("reconstruction obligation candidates", () => {
|
||||
it("preserves admitted unknown application nodes as limitations", () => {
|
||||
const { graph, unknownNodes, generated } = applicationWithUnknowns([
|
||||
"unclassified-boundary",
|
||||
]);
|
||||
const unknownNode = unknownNodes[0];
|
||||
if (unknownNode === undefined) throw new Error("Expected one unknown node");
|
||||
|
||||
expect(generated.candidates.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
generated.candidates.some(
|
||||
({ target }) => target.application_node_id === unknownNode.node_id,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(generated.limitations).toEqual([
|
||||
unknownLimitation(graph.graph_id, unknownNode.node_id),
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits one deterministic limitation per unknown node", () => {
|
||||
it("preserves unresolved application nodes as deterministic limitations", () => {
|
||||
const { graph, unknownNodes, generated } = applicationWithUnknowns([
|
||||
"unclassified-first",
|
||||
"unclassified-second",
|
||||
]);
|
||||
|
||||
expect(generated.candidates.length).toBeGreaterThan(0);
|
||||
expect([...generated.limitations].sort()).toEqual(
|
||||
unknownNodes
|
||||
.map((node) => unknownLimitation(graph.graph_id, node.node_id))
|
||||
@@ -141,4 +133,41 @@ describe("reconstruction obligation candidates", () => {
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not bind an unknown process image to a packaged artifact obligation", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/path/whose-launch-identity-is-unknown",
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const scenarioProjection = processScenarioCommitment(scenario);
|
||||
const comparisonContract = processComparisonContract(scenario);
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
scenario: scenarioProjection,
|
||||
comparison_contract: comparisonContract,
|
||||
full_scenario_sha256: digestProcessCommitment(scenarioProjection),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
selected_executable_sha256: null,
|
||||
executable_sha256: null,
|
||||
executable_identity: {
|
||||
state: "unknown",
|
||||
reason: "Selected executable could not be inspected.",
|
||||
},
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
},
|
||||
});
|
||||
const evidence = createProcessCaptureEvidence(scenario, capture);
|
||||
const generated = deriveReconstructionObligationCandidates(
|
||||
createEvidenceBundle([evidence]),
|
||||
[],
|
||||
);
|
||||
|
||||
expect(generated.candidates).toEqual([]);
|
||||
expect(generated.limitations).toContain(
|
||||
`Process capture ${evidence.evidence_id} has no validated executable artifact identity; packaged-process lifecycle obligation was not bound to an artifact.`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
parseEvidenceBundle,
|
||||
type EvidenceBundle,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
import { parseProcessCapture } from "../domain/process/processCapture.js";
|
||||
import type {
|
||||
ReconstructionObligation,
|
||||
ReviewedReconstructionObligation,
|
||||
@@ -176,6 +176,12 @@ const deriveProcessCandidate = (
|
||||
]
|
||||
: []),
|
||||
];
|
||||
if (capture.manifest.executable_sha256 === null) {
|
||||
limitations.add(
|
||||
`Process capture ${evidence.evidence_id} has no validated executable artifact identity; packaged-process lifecycle obligation was not bound to an artifact.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
addCandidate(candidates, {
|
||||
obligation_id: obligationId(
|
||||
`process:${capture.manifest.executable_sha256}:${capture.manifest.full_scenario_sha256}`,
|
||||
|
||||
@@ -1,112 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
|
||||
import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../domain/processCapture.js";
|
||||
import {
|
||||
reconstructionObligationLedgerSchema,
|
||||
type ReconstructionObligationLedgerInput,
|
||||
type ReconstructionObligationLedger,
|
||||
type ReviewedReconstructionObligation,
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
|
||||
const proofEvidence = (id: string) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
|
||||
{
|
||||
predicateType: "rea.fixture-verification",
|
||||
operation: "run_fixture_verifier",
|
||||
parameters: { id },
|
||||
result: { passed: true },
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
},
|
||||
);
|
||||
|
||||
const processEvidence = () =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(
|
||||
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
|
||||
),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
});
|
||||
|
||||
const boundProofEvidence = (
|
||||
id: string,
|
||||
result: {
|
||||
readonly obligation_ids: readonly string[];
|
||||
readonly fixture_ids: readonly string[];
|
||||
readonly case_kinds: readonly string[];
|
||||
readonly verifier_ids: readonly string[];
|
||||
readonly claim_ids: readonly string[];
|
||||
},
|
||||
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
|
||||
) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
|
||||
{
|
||||
predicateType: "rea.reconstruction-proof",
|
||||
operation: "verify_reconstruction_obligations",
|
||||
parameters: {},
|
||||
result: {
|
||||
passed: true,
|
||||
obligation_ids: [...result.obligation_ids],
|
||||
fixture_ids: [...result.fixture_ids],
|
||||
case_kinds: [...result.case_kinds],
|
||||
verifier_ids: [...result.verifier_ids],
|
||||
claim_ids: [...result.claim_ids],
|
||||
},
|
||||
confidence: "observed",
|
||||
authority,
|
||||
},
|
||||
);
|
||||
|
||||
const request = (
|
||||
records: readonly Evidence[],
|
||||
overrides: Partial<ReconstructionObligationLedgerInput> = {},
|
||||
): ReconstructionObligationLedgerInput => ({
|
||||
evidence_bundle: createEvidenceBundle(records),
|
||||
reviewed_obligations: [],
|
||||
manifest: { bindings: [], contradictions: [] },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const build = (
|
||||
input: ReconstructionObligationLedgerInput,
|
||||
): ReconstructionObligationLedger => {
|
||||
const parsed = resolveReconstructionObligationLedgerRequest(input);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const result = buildReconstructionObligationLedgerEvidenceValidated(
|
||||
parsed.value,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return reconstructionObligationLedgerSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
const originalCases = (
|
||||
obligation: ReconstructionObligationLedger["obligations"][number],
|
||||
evidenceId: string,
|
||||
) =>
|
||||
obligation.required_case_kinds.map((caseKind) => ({
|
||||
kind: caseKind,
|
||||
evidence_id: evidenceId,
|
||||
location: `/normalized_result/cases/${caseKind}`,
|
||||
}));
|
||||
boundProofEvidence,
|
||||
build,
|
||||
originalCases,
|
||||
processEvidence,
|
||||
proofEvidence,
|
||||
request,
|
||||
reviewedObligation,
|
||||
} from "./ReconstructionObligationLedger.fixture.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import type { ReviewedReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
|
||||
describe("reconstruction obligation ledger", () => {
|
||||
it("does not authenticate packaged-process proof with generic replay evidence", () => {
|
||||
@@ -315,32 +219,3 @@ describe("reconstruction obligation ledger fail-closed behavior", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const reviewedObligation = (
|
||||
obligationId: string,
|
||||
evidenceId: string,
|
||||
): ReviewedReconstructionObligation => ({
|
||||
obligation_id: obligationId,
|
||||
obligation_version: 1,
|
||||
title: `Reviewed obligation ${obligationId}`,
|
||||
application_layer: "other",
|
||||
family: "reviewed",
|
||||
target: {
|
||||
artifact_sha256: null,
|
||||
application_node_id: null,
|
||||
semantic_node_id: null,
|
||||
location: `/reviewed/${obligationId}`,
|
||||
},
|
||||
required: true,
|
||||
required_case_kinds: ["positive"],
|
||||
required_original_authority: "static",
|
||||
required_fixture_authority: "unit",
|
||||
required_verifier_authority: "unit",
|
||||
requires_parser_type: false,
|
||||
dependency_obligation_ids: [],
|
||||
residual_unknown_ids: [],
|
||||
unavailable_authority: [],
|
||||
required_next_evidence: ["Bind an owner and verifier."],
|
||||
disposition: "active",
|
||||
review_evidence_ids: [evidenceId],
|
||||
});
|
||||
|
||||
@@ -1,141 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
|
||||
import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../domain/processCapture.js";
|
||||
import {
|
||||
reconstructionObligationLedgerSchema,
|
||||
type ReconstructionObligationLedgerInput,
|
||||
type ReconstructionObligationLedger,
|
||||
type ReviewedReconstructionObligation,
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
|
||||
const proofEvidence = (id: string) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
|
||||
{
|
||||
predicateType: "rea.fixture-verification",
|
||||
operation: "run_fixture_verifier",
|
||||
parameters: { id },
|
||||
result: { passed: true },
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
},
|
||||
);
|
||||
|
||||
const processEvidence = () =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(
|
||||
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
|
||||
),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
});
|
||||
|
||||
const boundProofEvidence = (
|
||||
id: string,
|
||||
result: {
|
||||
readonly obligation_ids: readonly string[];
|
||||
readonly fixture_ids: readonly string[];
|
||||
readonly case_kinds: readonly string[];
|
||||
readonly verifier_ids: readonly string[];
|
||||
readonly claim_ids: readonly string[];
|
||||
},
|
||||
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
|
||||
) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
|
||||
{
|
||||
predicateType: "rea.reconstruction-proof",
|
||||
operation: "verify_reconstruction_obligations",
|
||||
parameters: {},
|
||||
result: {
|
||||
passed: true,
|
||||
obligation_ids: [...result.obligation_ids],
|
||||
fixture_ids: [...result.fixture_ids],
|
||||
case_kinds: [...result.case_kinds],
|
||||
verifier_ids: [...result.verifier_ids],
|
||||
claim_ids: [...result.claim_ids],
|
||||
},
|
||||
confidence: "observed",
|
||||
authority,
|
||||
},
|
||||
);
|
||||
|
||||
const request = (
|
||||
records: readonly Evidence[],
|
||||
overrides: Partial<ReconstructionObligationLedgerInput> = {},
|
||||
): ReconstructionObligationLedgerInput => ({
|
||||
evidence_bundle: createEvidenceBundle(records),
|
||||
reviewed_obligations: [],
|
||||
manifest: { bindings: [], contradictions: [] },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const build = (
|
||||
input: ReconstructionObligationLedgerInput,
|
||||
): ReconstructionObligationLedger => {
|
||||
const parsed = resolveReconstructionObligationLedgerRequest(input);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const result = buildReconstructionObligationLedgerEvidenceValidated(
|
||||
parsed.value,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return reconstructionObligationLedgerSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
const originalCases = (
|
||||
obligation: ReconstructionObligationLedger["obligations"][number],
|
||||
evidenceId: string,
|
||||
) =>
|
||||
obligation.required_case_kinds.map((caseKind) => ({
|
||||
kind: caseKind,
|
||||
evidence_id: evidenceId,
|
||||
location: `/normalized_result/cases/${caseKind}`,
|
||||
}));
|
||||
|
||||
const reviewedObligation = (
|
||||
obligationId: string,
|
||||
evidenceId: string,
|
||||
): ReviewedReconstructionObligation => ({
|
||||
obligation_id: obligationId,
|
||||
obligation_version: 1,
|
||||
title: `Reviewed obligation ${obligationId}`,
|
||||
application_layer: "other",
|
||||
family: "reviewed",
|
||||
target: {
|
||||
artifact_sha256: null,
|
||||
application_node_id: null,
|
||||
semantic_node_id: null,
|
||||
location: `/reviewed/${obligationId}`,
|
||||
},
|
||||
required: true,
|
||||
required_case_kinds: ["positive"],
|
||||
required_original_authority: "static",
|
||||
required_fixture_authority: "unit",
|
||||
required_verifier_authority: "unit",
|
||||
requires_parser_type: false,
|
||||
dependency_obligation_ids: [],
|
||||
residual_unknown_ids: [],
|
||||
unavailable_authority: [],
|
||||
required_next_evidence: ["Bind an owner and verifier."],
|
||||
disposition: "active",
|
||||
review_evidence_ids: [evidenceId],
|
||||
});
|
||||
boundProofEvidence,
|
||||
build,
|
||||
originalCases,
|
||||
processEvidence,
|
||||
proofEvidence,
|
||||
request,
|
||||
reviewedObligation,
|
||||
} from "./ReconstructionObligationLedger.fixture.js";
|
||||
|
||||
describe("reconstruction obligation ledger", () => {
|
||||
it("emits the complete deterministic ledger and closure identity", () => {
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { PROCESS_PROVIDER } from "./process/ProcessEvidence.js";
|
||||
import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/process/processCapture.fixture.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../domain/process/processCapture.js";
|
||||
import {
|
||||
reconstructionObligationLedgerSchema,
|
||||
type ReconstructionObligationLedgerInput,
|
||||
type ReconstructionObligationLedger,
|
||||
type ReviewedReconstructionObligation,
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
|
||||
/** Build controlled fixture Evidence used by reconstruction-ledger scenarios. */
|
||||
export const proofEvidence = (id: string) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
|
||||
{
|
||||
predicateType: "rea.fixture-verification",
|
||||
operation: "run_fixture_verifier",
|
||||
parameters: { id },
|
||||
result: { passed: true },
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
},
|
||||
);
|
||||
|
||||
/** Use the canonical empty process capture as a controlled Evidence example. */
|
||||
export const processEvidence = () =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(
|
||||
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
|
||||
),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
});
|
||||
|
||||
/** Build verifier Evidence bound to enumerated fixture and obligation identities. */
|
||||
export const boundProofEvidence = (
|
||||
id: string,
|
||||
result: {
|
||||
readonly obligation_ids: readonly string[];
|
||||
readonly fixture_ids: readonly string[];
|
||||
readonly case_kinds: readonly string[];
|
||||
readonly verifier_ids: readonly string[];
|
||||
readonly claim_ids: readonly string[];
|
||||
},
|
||||
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
|
||||
) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
|
||||
{
|
||||
predicateType: "rea.reconstruction-proof",
|
||||
operation: "verify_reconstruction_obligations",
|
||||
parameters: {},
|
||||
result: {
|
||||
passed: true,
|
||||
obligation_ids: [...result.obligation_ids],
|
||||
fixture_ids: [...result.fixture_ids],
|
||||
case_kinds: [...result.case_kinds],
|
||||
verifier_ids: [...result.verifier_ids],
|
||||
claim_ids: [...result.claim_ids],
|
||||
},
|
||||
confidence: "observed",
|
||||
authority,
|
||||
},
|
||||
);
|
||||
|
||||
/** Build a ledger request with empty reviewed input and manifest defaults. */
|
||||
export const request = (
|
||||
records: readonly Evidence[],
|
||||
overrides: Partial<ReconstructionObligationLedgerInput> = {},
|
||||
): ReconstructionObligationLedgerInput => ({
|
||||
evidence_bundle: createEvidenceBundle(records),
|
||||
reviewed_obligations: [],
|
||||
manifest: { bindings: [], contradictions: [] },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
/** Run request resolution, Evidence validation, and output parsing for a fixture. */
|
||||
export const build = (
|
||||
input: ReconstructionObligationLedgerInput,
|
||||
): ReconstructionObligationLedger => {
|
||||
const parsed = resolveReconstructionObligationLedgerRequest(input);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const result = buildReconstructionObligationLedgerEvidenceValidated(
|
||||
parsed.value,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return reconstructionObligationLedgerSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
/** Create provenance for each required case from one source Evidence record. */
|
||||
export const originalCases = (
|
||||
obligation: ReconstructionObligationLedger["obligations"][number],
|
||||
evidenceId: string,
|
||||
) =>
|
||||
obligation.required_case_kinds.map((caseKind) => ({
|
||||
kind: caseKind,
|
||||
evidence_id: evidenceId,
|
||||
location: `/normalized_result/cases/${caseKind}`,
|
||||
}));
|
||||
|
||||
/** Create a minimal reviewed obligation for ledger closure scenarios. */
|
||||
export const reviewedObligation = (
|
||||
obligationId: string,
|
||||
evidenceId: string,
|
||||
): ReviewedReconstructionObligation => ({
|
||||
obligation_id: obligationId,
|
||||
obligation_version: 1,
|
||||
title: `Reviewed obligation ${obligationId}`,
|
||||
application_layer: "other",
|
||||
family: "reviewed",
|
||||
target: {
|
||||
artifact_sha256: null,
|
||||
application_node_id: null,
|
||||
semantic_node_id: null,
|
||||
location: `/reviewed/${obligationId}`,
|
||||
},
|
||||
required: true,
|
||||
required_case_kinds: ["positive"],
|
||||
required_original_authority: "static",
|
||||
required_fixture_authority: "unit",
|
||||
required_verifier_authority: "unit",
|
||||
requires_parser_type: false,
|
||||
dependency_obligation_ids: [],
|
||||
residual_unknown_ids: [],
|
||||
unavailable_authority: [],
|
||||
required_next_evidence: ["Bind an owner and verifier."],
|
||||
disposition: "active",
|
||||
review_evidence_ids: [evidenceId],
|
||||
});
|
||||
@@ -165,15 +165,6 @@ describe("setup workflow lifecycle and provider planning", () => {
|
||||
remediation: null,
|
||||
},
|
||||
];
|
||||
host.productRegistrations = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/codex.toml",
|
||||
command: ["rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
];
|
||||
const progress: SetupProgressEvent[] = [];
|
||||
await runSetup(
|
||||
{ ...options(true), onProgress: (event) => progress.push(event) },
|
||||
|
||||
@@ -194,7 +194,7 @@ describe("setup scoped readiness", () => {
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.remediation).toBe(
|
||||
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
|
||||
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.",
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ export const hostRemediation = async (
|
||||
: undefined;
|
||||
}
|
||||
if ((await host.linuxDistribution())?.supported === true) return undefined;
|
||||
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.";
|
||||
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.";
|
||||
};
|
||||
|
||||
/** Production setup effects for Hopper, agent configuration, and the canonical skill directory. */
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
setupInstallFailure,
|
||||
type HopperInstallFailureReason,
|
||||
} from "./SetupInstallFailure.js";
|
||||
|
||||
describe("setup installer failure projection", () => {
|
||||
it.each([
|
||||
["unsupported_host", "unsupported_host"],
|
||||
["download", "download_failed"],
|
||||
["release_metadata", "download_failed"],
|
||||
["integrity", "integrity_mismatch"],
|
||||
[
|
||||
"authorization_or_package_manager",
|
||||
"authorization_or_package_manager_failed",
|
||||
],
|
||||
["launcher_missing", "launcher_missing"],
|
||||
["runtime_dependencies", "runtime_dependency_unavailable"],
|
||||
["unsupported_hopper_build", "unsupported_hopper_build"],
|
||||
["cancelled", "setup_cancelled"],
|
||||
["destination_exists", "destination_exists"],
|
||||
["mount", "mount_failed"],
|
||||
["bundle", "bundle_invalid"],
|
||||
["copy", "copy_failed"],
|
||||
] as const)("maps %s to %s", (reason, code) => {
|
||||
const result = setupInstallFailure(reason as HopperInstallFailureReason);
|
||||
expect(result).toMatchObject({ status: "failed", code });
|
||||
expect(result).toMatchObject({ remediation: expect.stringMatching(/\S/u) });
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { DoctorProviderInspection } from "./Doctor.js";
|
||||
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
|
||||
|
||||
const inspection = (
|
||||
overrides: Partial<DoctorProviderInspection> = {},
|
||||
): DoctorProviderInspection => ({
|
||||
id: "fixture",
|
||||
configured: true,
|
||||
available: false,
|
||||
providerVersion: "1",
|
||||
registrationEnvironment: {
|
||||
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
|
||||
},
|
||||
checks: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("provider registration settings", () => {
|
||||
it("retains valid published paths when runtime capabilities are unavailable", () => {
|
||||
expect(providerRegistrationEnvironment([inspection()])).toEqual({
|
||||
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not invent settings when the adapter cannot publish an installation", () => {
|
||||
expect(
|
||||
providerRegistrationEnvironment([
|
||||
inspection({ configured: false, registrationEnvironment: {} }),
|
||||
]),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps available-provider settings unchanged", () => {
|
||||
expect(
|
||||
providerRegistrationEnvironment([inspection({ available: true })]),
|
||||
).toEqual({ REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider" });
|
||||
});
|
||||
});
|
||||
@@ -1,144 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
open,
|
||||
readdir,
|
||||
rename,
|
||||
rm,
|
||||
rmdir,
|
||||
unlink,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
|
||||
/** One acquired store transaction lock with cleanup bound to its unique owner. */
|
||||
export interface StoreFileLock {
|
||||
readonly release: () => Promise<void>;
|
||||
}
|
||||
|
||||
class StoreFileLockOccupied extends Error {
|
||||
readonly code = "EEXIST";
|
||||
|
||||
constructor(cause?: unknown) {
|
||||
super("Store transaction lock is occupied", { cause });
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomically publish a populated directory so another owner cannot replace a live lock. */
|
||||
export const createStoreFileLock = async (
|
||||
path: string,
|
||||
): Promise<StoreFileLock> => {
|
||||
if (await exists(path)) throw new StoreFileLockOccupied();
|
||||
const staged = await mkdtemp(join(dirname(path), ".rea-store-lock-"));
|
||||
const owner = `owner-${randomUUID()}`;
|
||||
try {
|
||||
const handle = await open(join(staged, owner), "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
try {
|
||||
// Rename cannot replace a nonempty directory: the owner entry is present before publication.
|
||||
await rename(staged, path);
|
||||
} catch (cause: unknown) {
|
||||
if (await exists(path)) throw new StoreFileLockOccupied(cause);
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
release: async () => {
|
||||
await removeOwner(path, owner).catch((cause: unknown) => {
|
||||
// best-effort cleanup: lock release must not reject unhandled.
|
||||
void cause;
|
||||
});
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
await rm(staged, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
/** Recover a dead owner's directory lock or a legacy PID file; leave live and unknown owners intact. */
|
||||
export const removeStaleStoreFileLock = async (
|
||||
path: string,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
if (stats.isFile()) {
|
||||
if (!(await ownerIsDead(path))) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
}
|
||||
if (!stats.isDirectory()) return false;
|
||||
const entries = await readdir(path);
|
||||
if (entries.length === 0) {
|
||||
await rmdir(path);
|
||||
return true;
|
||||
}
|
||||
const owner = entries[0];
|
||||
if (
|
||||
entries.length !== 1 ||
|
||||
owner === undefined ||
|
||||
!/^owner-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(owner) ||
|
||||
!(await ownerIsDead(join(path, owner)))
|
||||
)
|
||||
return false;
|
||||
await removeOwner(path, owner);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: stale lock probing; failure means the lock stands.
|
||||
void cause;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const removeOwner = async (path: string, owner: string): Promise<void> => {
|
||||
// A successor has a different entry, so stale cleanup cannot make its directory empty.
|
||||
await unlink(join(path, owner));
|
||||
await rmdir(path);
|
||||
};
|
||||
|
||||
const ownerIsDead = async (path: string): Promise<boolean> => {
|
||||
const stats = await lstat(path);
|
||||
if (!stats.isFile() || stats.size > 32) return false;
|
||||
const handle = await open(path, "r");
|
||||
let bytes: Buffer | undefined;
|
||||
try {
|
||||
bytes = await readBoundedFileBytes(handle, 32);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
const encoded = bytes?.toString("utf8").trim();
|
||||
return (
|
||||
encoded !== undefined &&
|
||||
/^[1-9][0-9]{0,9}$/u.test(encoded) &&
|
||||
!processIsAlive(Number(encoded))
|
||||
);
|
||||
};
|
||||
|
||||
const exists = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
await lstat(path);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
if (errorCode(cause) === "ENOENT") return false;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type {
|
||||
InspectWebNetworkCaptureInput,
|
||||
WebNetworkCapture,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
/** Replaceable offline capture port; producer protocols remain in format adapters. */
|
||||
export interface WebNetworkCapturePort {
|
||||
inspect(
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { WebNetworkCaptureService } from "./WebNetworkCaptureService.js";
|
||||
import { historicalHar } from "../../tests/fixtures/historicalHar.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { parseEvidence } from "../domain/evidence.js";
|
||||
import {
|
||||
webNetworkCaptureSchema,
|
||||
type WebNetworkCapture,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
it.each(["REDACTED", "[", "]", "/capture.har"])(
|
||||
"excludes sensitive path text even when a replacement marker would collide: %s",
|
||||
async (literal) => {
|
||||
const report = fixture();
|
||||
report.artifact.path = `/capture.har/${literal}`;
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: report.artifact.path,
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject?.local_path).not.toContain(literal);
|
||||
expect(result.value.parameters.capture_path).not.toContain(literal);
|
||||
expect(
|
||||
result.value.locations.every(
|
||||
(location) =>
|
||||
location.kind !== "artifact-path" || !location.path.includes(literal),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps observed artifact identity when the entire sensitive path is excluded", async () => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["/", "[", "REDACTED"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toMatchObject({
|
||||
local_path: "",
|
||||
digest: { sha256: "a".repeat(64) },
|
||||
});
|
||||
expect(result.value.locations).toEqual([]);
|
||||
});
|
||||
|
||||
const fixture = (): WebNetworkCapture => ({
|
||||
decoder: { id: "test-historical-port", name: "test port", version: "1" },
|
||||
container: {
|
||||
reported: null,
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
records_pointer: "/log/entries",
|
||||
},
|
||||
total_records: 1,
|
||||
records: [
|
||||
{
|
||||
ordinal: 0,
|
||||
location: { kind: "json-pointer", pointer: "/log/entries/0" },
|
||||
reported: historicalHar().log.entries[0] ?? null,
|
||||
numeric_literals: [],
|
||||
binary_fields: [],
|
||||
redactions: [],
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
artifact: { path: "/capture.har", sha256: "a".repeat(64), bytes: 10 },
|
||||
format: "har",
|
||||
runtime_attribution: "unknown",
|
||||
limitations: ["historical fixture"],
|
||||
});
|
||||
|
||||
it.each(["a".repeat(64), "aaaa"])(
|
||||
"marks an explicitly sensitive artifact digest unknown without inventing another identity: %s",
|
||||
async (literal) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toBeNull();
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
artifact: { path: "/capture.har", sha256: null, bytes: 10 },
|
||||
});
|
||||
expect(result.value.parameters.capture_path).toBe("/capture.har");
|
||||
expect(result.value.locations).toEqual([
|
||||
{ kind: "artifact-path", path: "/capture.har" },
|
||||
]);
|
||||
expect(parseEvidence(result.value)).toEqual(result.value);
|
||||
},
|
||||
);
|
||||
|
||||
it("projects the unknown-subject explanation before generating its Evidence ID", async () => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["a"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toBeNull();
|
||||
expect(result.value.limitations.every((text) => !text.includes("a"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(parseEvidence(result.value)).toEqual(result.value);
|
||||
});
|
||||
|
||||
it("rejects an adapter omitting its original observed digest before caller projection", async () => {
|
||||
const report = fixture();
|
||||
report.artifact.sha256 = null;
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({ capture_path: report.artifact.path, format: "har" });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["producer"],
|
||||
["artifact"],
|
||||
["coordinates"],
|
||||
["producer", "REDACTED", "…"],
|
||||
["producer", "[", "]"],
|
||||
])(
|
||||
"excludes declared literals from all authored limitations: %j",
|
||||
async (...literals) => {
|
||||
const report = fixture();
|
||||
report.artifact.path = "/artifact/capture.har";
|
||||
report.limitations = [
|
||||
"Historical producer artifact coordinates are retained.",
|
||||
];
|
||||
const first = report.records[0];
|
||||
if (first === undefined) throw new Error("fixture missing record");
|
||||
first.limitations = ["This is producer-decoded artifact evidence."];
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: report.artifact.path,
|
||||
format: "har",
|
||||
sensitive_values: literals,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const projected = webNetworkCaptureSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
const texts = [
|
||||
result.value.limitations,
|
||||
projected.limitations,
|
||||
...projected.records.map((record) => record.limitations),
|
||||
].flat();
|
||||
for (const literal of literals)
|
||||
expect(texts.every((text) => !text.includes(literal))).toBe(true);
|
||||
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
|
||||
expect(projected.decoder).toEqual(report.decoder);
|
||||
expect(projected.records[0]?.reported).toEqual(first.reported);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps explicitly sensitive values out of Evidence parameters and preserves historical authority", async () => {
|
||||
const service = new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
});
|
||||
const result = await service.inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["explicit-private-value"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.parameters).toMatchObject({
|
||||
sensitive_value_count: 1,
|
||||
record_ordinals: [0],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("explicit-private-value");
|
||||
expect(result.value.authority).toBe("historical-reference");
|
||||
expect(result.value.provider).toEqual(fixture().decoder);
|
||||
});
|
||||
|
||||
it.each(["har", "ha"])(
|
||||
"omits a format parameter containing a declared sensitive literal: %s",
|
||||
async (literal) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.parameters).not.toHaveProperty("format");
|
||||
expect(JSON.stringify(result.value.parameters)).not.toContain(literal);
|
||||
expect(result.value.normalized_result).toMatchObject({ format: "har" });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ record_ordinals: [0, 0] },
|
||||
{ record_ordinals: [1] },
|
||||
{ capture_path: "relative.har" },
|
||||
])("rejects invalid caller selection %j", async (extra) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({ capture_path: "/capture.har", format: "har", ...extra });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
|
||||
it("rejects a port changing the artifact identity or producer ordinal sequence", async () => {
|
||||
const report = fixture();
|
||||
report.artifact.path = "/different.har";
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({ capture_path: "/capture.har", format: "har" });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
|
||||
it("applies an explicit sensitive path literal after verifying the selected artifact", async () => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["capture.har"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(JSON.stringify(result.value)).not.toContain("capture.har");
|
||||
expect(result.value.parameters.capture_path).toBe("");
|
||||
});
|
||||
|
||||
it.each(["log", "entries"])(
|
||||
"excludes a sensitive producer coordinate without inventing a replacement: %s",
|
||||
async (literal) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
container: { records_pointer: null },
|
||||
records: [
|
||||
{
|
||||
ordinal: 0,
|
||||
location: { kind: "unknown", reason: "explicit-sensitive-value" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain(literal);
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes an escaped sensitive sidecar coordinate while preserving its reported field", async () => {
|
||||
const report = fixture();
|
||||
report.container.reported = { "field/name": 42 };
|
||||
report.container.numeric_literals = [
|
||||
{ pointer: "/field~1name", producer_type: "json-number", literal: "42" },
|
||||
];
|
||||
report.container.redactions = [
|
||||
{ pointer: "/field~1name", reason: "explicit-sensitive-value" },
|
||||
];
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["~1"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
container: {
|
||||
reported: { "field/name": 42 },
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("~1");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ literal: "12345", input: { record_ordinals: [12345] } },
|
||||
{ literal: "Each", input: { record_ordinals: [0, 0] } },
|
||||
{ literal: "absolute", input: { capture_path: "relative.har" } },
|
||||
{ literal: "secret", input: { mysecret: true } },
|
||||
])(
|
||||
"excludes declared text from application-generated input errors: $literal",
|
||||
async ({ literal, input }) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
...input,
|
||||
});
|
||||
if (result.ok) throw new Error("Expected invalid selection");
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
expect(JSON.stringify(projectAnalysisError(result.error))).not.toContain(
|
||||
literal,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["12345", "67890", "234", "789"])(
|
||||
"excludes sensitive native byte-range coordinates: %s",
|
||||
async (literal) => {
|
||||
const report = fixture();
|
||||
report.format = "mitmproxy";
|
||||
report.artifact.path = "/capture.mitm";
|
||||
const record = report.records[0];
|
||||
if (record === undefined) throw new Error("record missing");
|
||||
record.location = { kind: "byte-range", offset: 12345, bytes: 67890 };
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: report.artifact.path,
|
||||
format: "mitmproxy",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
records: [
|
||||
{ location: { kind: "unknown", reason: "explicit-sensitive-value" } },
|
||||
],
|
||||
});
|
||||
expect(result.value.raw_result).toBeNull();
|
||||
expect(parseEvidence(result.value)).toEqual(result.value);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,202 @@
|
||||
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
|
||||
import { excludeCaptureCoordinates } from "../domain/webNetworkCaptureCoordinates.js";
|
||||
import { redactExplicitText } from "../domain/explicitSensitiveValues.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { WebNetworkCapturePort } from "./WebNetworkCapturePort.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
webNetworkCaptureSchema,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
/** Shared CLI/MCP historical inspection preserves caller selection and producer record identity. */
|
||||
export class WebNetworkCaptureService {
|
||||
constructor(readonly port: WebNetworkCapturePort) {}
|
||||
|
||||
/** Return selected complete records inline, without inventing live browser attribution. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const declarations =
|
||||
inspectWebNetworkCaptureInputSchema.shape.sensitive_values.safeParse(
|
||||
typeof rawInput === "object" &&
|
||||
rawInput !== null &&
|
||||
"sensitive_values" in rawInput
|
||||
? rawInput.sensitive_values
|
||||
: undefined,
|
||||
);
|
||||
const failure = (error: AnalysisError): Result<never, AnalysisError> =>
|
||||
err(
|
||||
redactExplicitFailure(
|
||||
error,
|
||||
declarations.success ? declarations.data : [],
|
||||
),
|
||||
);
|
||||
const parsed = inspectWebNetworkCaptureInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return failure(
|
||||
new AnalysisInputError(
|
||||
OPERATION,
|
||||
{ cause: parsed.error },
|
||||
projectInputIssues(parsed.error.issues, rawInput),
|
||||
),
|
||||
);
|
||||
const input = parsed.data;
|
||||
if (!isAbsolute(input.capture_path))
|
||||
return failure(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute filesystem path on this host.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
if (
|
||||
input.record_ordinals !== undefined &&
|
||||
new Set(input.record_ordinals).size !== input.record_ordinals.length
|
||||
)
|
||||
return failure(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["record_ordinals"],
|
||||
reason: "invalid_format",
|
||||
message: "Each requested producer ordinal must occur once.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const loaded = await this.port.inspect(input, options);
|
||||
if (!loaded.ok) return failure(loaded.error);
|
||||
if (options?.signal?.aborted)
|
||||
return failure(new AnalysisCancelledError(OPERATION));
|
||||
const report = webNetworkCaptureSchema.safeParse(loaded.value);
|
||||
if (!report.success)
|
||||
return failure(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture adapter returned malformed historical evidence.",
|
||||
),
|
||||
);
|
||||
const value = report.data;
|
||||
const artifactSha256 = value.artifact.sha256;
|
||||
if (artifactSha256 === null)
|
||||
return failure(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture adapter omitted its observed artifact digest before explicit projection.",
|
||||
),
|
||||
);
|
||||
if (
|
||||
value.artifact.path !== input.capture_path ||
|
||||
value.format !== input.format ||
|
||||
value.total_records !== value.records.length ||
|
||||
value.records.some((record, index) => record.ordinal !== index)
|
||||
)
|
||||
return failure(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture adapter changed the selected artifact, format or original record sequence.",
|
||||
),
|
||||
);
|
||||
const safeValue = excludeCaptureCoordinates(value, input.sensitive_values);
|
||||
const redactText = (text: string): string =>
|
||||
redactExplicitText(text, input.sensitive_values);
|
||||
const selected =
|
||||
input.record_ordinals ?? value.records.map(({ ordinal }) => ordinal);
|
||||
const records = [];
|
||||
for (const ordinal of selected) {
|
||||
const record = safeValue.records[ordinal];
|
||||
if (record === undefined)
|
||||
return failure(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["record_ordinals"],
|
||||
reason: "invalid_format",
|
||||
message: `Producer ordinal ${ordinal} is outside the retained capture (${value.total_records} records).`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
records.push({
|
||||
...record,
|
||||
limitations: record.limitations.map(redactText),
|
||||
});
|
||||
}
|
||||
const safePath = input.sensitive_values.some((literal) =>
|
||||
input.capture_path.includes(literal),
|
||||
)
|
||||
? ""
|
||||
: input.capture_path;
|
||||
const safeSha256 = input.sensitive_values.some((literal) =>
|
||||
artifactSha256.includes(literal),
|
||||
)
|
||||
? null
|
||||
: artifactSha256;
|
||||
const subjectUnavailableReason = redactText(
|
||||
"The explicitly sensitive artifact digest is excluded; its cryptographic identity is unknown in this Evidence.",
|
||||
);
|
||||
const limitations = [
|
||||
...safeValue.limitations,
|
||||
...(safePath === ""
|
||||
? [
|
||||
"The explicitly sensitive artifact path is excluded; its size remains available.",
|
||||
]
|
||||
: []),
|
||||
].map(redactText);
|
||||
const parameters = jsonObjectSchema.parse({
|
||||
capture_path: safePath,
|
||||
...(input.sensitive_values.some((literal) =>
|
||||
input.format.includes(literal),
|
||||
)
|
||||
? {}
|
||||
: { format: input.format }),
|
||||
record_ordinals: selected,
|
||||
sensitive_value_count: input.sensitive_values.length,
|
||||
});
|
||||
return ok(
|
||||
createEvidence(
|
||||
safeSha256 === null
|
||||
? undefined
|
||||
: {
|
||||
path: safePath,
|
||||
sha256: safeSha256,
|
||||
format: "file",
|
||||
},
|
||||
value.decoder,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters,
|
||||
result: {
|
||||
...safeValue,
|
||||
artifact: { ...value.artifact, path: safePath, sha256: safeSha256 },
|
||||
records,
|
||||
limitations:
|
||||
safeSha256 === null
|
||||
? [...limitations, subjectUnavailableReason]
|
||||
: limitations,
|
||||
},
|
||||
confidence: "observed",
|
||||
authority: "historical-reference",
|
||||
limitations,
|
||||
...(safeSha256 === null ? { subjectUnavailableReason } : {}),
|
||||
locations:
|
||||
safePath === "" ? [] : [{ kind: "artifact-path", path: safePath }],
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
import {
|
||||
probeProcessCaptureCapability,
|
||||
type ProcessCaptureCapability,
|
||||
} from "./ProcessCaptureCapability.js";
|
||||
} from "../process/capture/ProcessCaptureCapability.js";
|
||||
|
||||
/** One named Windows host observation without inferred authority. */
|
||||
export type WindowsCapabilityOutcome =
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisProviderRegistry,
|
||||
type AnalysisProviderBinding,
|
||||
} from "./AnalysisProviderRegistry.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
@@ -33,132 +30,77 @@ const ARTIFACT_TARGET: BinaryTarget = {
|
||||
format: "asar",
|
||||
};
|
||||
|
||||
describe("analysis provider registry: discovery and selection", () => {
|
||||
it("admits overlapping operations, sorts discovery, and rejects duplicate IDs", () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta");
|
||||
const registry = new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]);
|
||||
it("rejects malformed provider capability declarations", () => {
|
||||
const alpha = candidate("alpha");
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
|
||||
).toThrow(/Duplicate analysis provider ID: alpha/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => {
|
||||
const descriptor = capability(alpha.provider.identity());
|
||||
return [descriptor, descriptor];
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toThrow(/declares operation address_name more than once/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => [
|
||||
capability({ ...alpha.provider.identity(), name: "forged" }),
|
||||
],
|
||||
},
|
||||
]),
|
||||
).toThrow(/published mismatched capability provenance/u);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([candidate("auto").provider]),
|
||||
).toThrow(/Invalid analysis provider ID: auto/u);
|
||||
});
|
||||
|
||||
expect(registry.identities().map(({ id }) => id)).toEqual([
|
||||
"alpha",
|
||||
"beta",
|
||||
]);
|
||||
expect(
|
||||
registry.candidates().map(({ provider, targetSupport }) => ({
|
||||
id: provider.id,
|
||||
support: targetSupport.status,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "alpha", support: "unknown" },
|
||||
{ id: "beta", support: "unknown" },
|
||||
]);
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
|
||||
).toThrow(/Duplicate analysis provider ID: alpha/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => {
|
||||
const descriptor = capability(alpha.provider.identity());
|
||||
return [descriptor, descriptor];
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toThrow(/declares operation address_name more than once/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => [
|
||||
capability({
|
||||
...alpha.provider.identity(),
|
||||
name: "mismatched provider",
|
||||
}),
|
||||
],
|
||||
},
|
||||
]),
|
||||
).toThrow(/published mismatched capability provenance/u);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([candidate("auto").provider]),
|
||||
).toThrow(/Invalid analysis provider ID: auto/u);
|
||||
it("selects the sole available provider and honors explicit selection precedence", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta", { available: false });
|
||||
const sole = await new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]).select(DATABASE_TARGET);
|
||||
expect(sole).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: {
|
||||
identity: { id: "alpha" },
|
||||
selectionSource: "auto-single-candidate",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
it("selects the sole usable candidate without creating a client", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta", { available: false });
|
||||
const registry = new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]);
|
||||
|
||||
const selected = await registry.select(DATABASE_TARGET);
|
||||
expect(selected.ok).toBe(true);
|
||||
if (!selected.ok) throw new Error("provider selection failed");
|
||||
if (selected.value.binding === null)
|
||||
throw new Error("expected a bound provider");
|
||||
expect(bindingProjection(selected.value.binding)).toEqual({
|
||||
id: "alpha",
|
||||
source: "auto-single-candidate",
|
||||
version: "1",
|
||||
});
|
||||
expect(selected.value.candidates).toMatchObject([
|
||||
{ provider: { id: "alpha", version: "1" }, selected: true },
|
||||
{
|
||||
provider: { id: "beta" },
|
||||
selected: false,
|
||||
availability: { status: "unavailable", code: "runtime_missing" },
|
||||
const selected = new AnalysisProviderRegistry(
|
||||
[alpha.provider, candidate("beta").provider],
|
||||
"beta",
|
||||
);
|
||||
expect(await selected.select(DATABASE_TARGET)).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: {
|
||||
identity: { id: "beta" },
|
||||
selectionSource: "environment",
|
||||
},
|
||||
]);
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
},
|
||||
});
|
||||
|
||||
it("makes auto ambiguity explicit and honors request over environment", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta");
|
||||
const registry = new AnalysisProviderRegistry(
|
||||
[alpha.provider, beta.provider],
|
||||
"beta",
|
||||
);
|
||||
|
||||
const environment = await registry.select(DATABASE_TARGET);
|
||||
expect(environment.ok).toBe(true);
|
||||
if (environment.ok)
|
||||
expect(environment.value.binding?.selectionSource).toBe("environment");
|
||||
expect(environment.ok && environment.value.binding?.identity.id).toBe(
|
||||
"beta",
|
||||
);
|
||||
|
||||
const request = await registry.select(DATABASE_TARGET, "alpha");
|
||||
expect(request.ok && request.value.binding?.identity.id).toBe("alpha");
|
||||
if (request.ok)
|
||||
expect(request.value.binding?.selectionSource).toBe("request");
|
||||
|
||||
const automatic = await registry.select(DATABASE_TARGET, "auto");
|
||||
expect(automatic.ok).toBe(false);
|
||||
if (automatic.ok) return;
|
||||
expect(automatic.error).toMatchObject({
|
||||
reason: "ambiguous",
|
||||
requestedProviderId: "auto",
|
||||
candidateIds: ["alpha", "beta"],
|
||||
});
|
||||
expect(projectAnalysisError(automatic.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
selection_reason: "ambiguous",
|
||||
candidate_ids: ["alpha", "beta"],
|
||||
expect(await selected.select(DATABASE_TARGET, "alpha")).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: {
|
||||
identity: { id: "alpha" },
|
||||
selectionSource: "request",
|
||||
},
|
||||
});
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -414,9 +356,3 @@ const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const bindingProjection = (binding: AnalysisProviderBinding) => ({
|
||||
id: binding.identity.id,
|
||||
source: binding.selectionSource,
|
||||
version: binding.identity.version,
|
||||
});
|
||||
|
||||
@@ -10,15 +10,137 @@ import { createEvidence } from "../../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
import { createAnalysisExecution } from "../AnalysisProvider.js";
|
||||
import {
|
||||
createAnalysisSnapshotWorkflowEntry,
|
||||
parseAnalysisSnapshot,
|
||||
snapshotBinding,
|
||||
snapshotTarget,
|
||||
} from "../../domain/analysisSnapshot.js";
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
} from "../InvestigationProviders.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
CapabilityDescriptor,
|
||||
} from "../AnalysisProvider.js";
|
||||
import {
|
||||
AnalysisSnapshotCache,
|
||||
SNAPSHOT_CACHE_ENTRY_CEILING,
|
||||
isSnapshotCacheable,
|
||||
} from "./AnalysisSnapshotCache.js";
|
||||
|
||||
describe("analysis snapshot cache capacity", () => {
|
||||
it("shares capacity across query kinds while allowing replacements and fresh partitions", () => {
|
||||
const cache = new AnalysisSnapshotCache();
|
||||
const target = ANALYSIS_SNAPSHOT_TARGET;
|
||||
const profile = ANALYSIS_SNAPSHOT_PROFILE;
|
||||
const execution = {
|
||||
...createAnalysisExecution("workflow", REA_WORKFLOW_PROVIDER, {
|
||||
subject: target,
|
||||
}),
|
||||
analysisProfile: workflowAnalysisProfile(profile),
|
||||
};
|
||||
const workflowInput = {
|
||||
target,
|
||||
profile,
|
||||
operation: "trace_feature",
|
||||
parameters: { query: "existing" },
|
||||
execution,
|
||||
};
|
||||
for (let index = 0; index < SNAPSHOT_CACHE_ENTRY_CEILING - 1; index += 1)
|
||||
cache.recordWorkflow({
|
||||
...workflowInput,
|
||||
parameters: { query: String(index) },
|
||||
});
|
||||
// Staging and recording both spend the same budget; an existing query can
|
||||
// still be refreshed when no space remains for a new binding.
|
||||
const directInput = {
|
||||
target,
|
||||
profile,
|
||||
operation: "address_name" as const,
|
||||
parameters: { address: "0x1000", document: "fixture" },
|
||||
execution: createAnalysisExecution(
|
||||
"initial",
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{ subject: target, analysisProfile: profile },
|
||||
),
|
||||
};
|
||||
cache.record(directInput);
|
||||
cache.record({
|
||||
...directInput,
|
||||
parameters: { address: "0x2000", document: "fixture" },
|
||||
});
|
||||
cache.recordWorkflow(workflowInput);
|
||||
expect(cache.entries()).toHaveLength(1);
|
||||
expect(cache.workflowEntries()).toHaveLength(
|
||||
SNAPSHOT_CACHE_ENTRY_CEILING - 1,
|
||||
);
|
||||
|
||||
cache.record({
|
||||
...directInput,
|
||||
execution: { ...directInput.execution, result: "updated" },
|
||||
});
|
||||
cache.recordWorkflow({
|
||||
...workflowInput,
|
||||
parameters: { query: "0" },
|
||||
execution: { ...execution, result: "updated" },
|
||||
});
|
||||
expect(
|
||||
cache.lookup(target, profile, "address_name", directInput.parameters)
|
||||
?.result,
|
||||
).toBe("updated");
|
||||
expect(
|
||||
cache.workflowEntries().find(({ parameters }) => parameters.query === "0")
|
||||
?.execution.result,
|
||||
).toBe("updated");
|
||||
|
||||
const incoming = createAnalysisSnapshotWorkflowEntry({
|
||||
...workflowInput,
|
||||
target: snapshotTarget(target),
|
||||
binding: snapshotBinding(profile),
|
||||
});
|
||||
const evidence = createEvidence(target, REA_WORKFLOW_PROVIDER, {
|
||||
operation: workflowInput.operation,
|
||||
parameters: workflowInput.parameters,
|
||||
result: execution.result,
|
||||
rawResult: execution.rawResult,
|
||||
analysisProfile: execution.analysisProfile,
|
||||
limitations: execution.limitations,
|
||||
locations: execution.locations,
|
||||
});
|
||||
cache.stage(
|
||||
parseAnalysisSnapshot({
|
||||
target: snapshotTarget(target),
|
||||
binding: snapshotBinding(profile),
|
||||
entries: [],
|
||||
workflow_entries: [incoming],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
}),
|
||||
);
|
||||
expect(cache.workflowEntries()).toHaveLength(
|
||||
SNAPSHOT_CACHE_ENTRY_CEILING - 1,
|
||||
);
|
||||
|
||||
const otherTarget = { ...target, sha256: "b".repeat(64) };
|
||||
cache.recordWorkflow({
|
||||
...workflowInput,
|
||||
target: otherTarget,
|
||||
execution: { ...execution, subject: otherTarget },
|
||||
});
|
||||
expect(cache.entries()).toEqual([]);
|
||||
expect(cache.workflowEntries()).toHaveLength(1);
|
||||
cache.clear();
|
||||
cache.record({
|
||||
...directInput,
|
||||
target: otherTarget,
|
||||
execution: { ...directInput.execution, subject: otherTarget },
|
||||
});
|
||||
expect(cache.entries()).toHaveLength(1);
|
||||
expect(cache.workflowEntries()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis snapshot cache partitioning", () => {
|
||||
it.each<{
|
||||
operation: Exclude<AnalysisOperation, "health">;
|
||||
|
||||
@@ -9,6 +9,7 @@ import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
analysisQueryId,
|
||||
createAnalysisSnapshotEntry,
|
||||
createAnalysisSnapshotWorkflowEntry,
|
||||
snapshotBinding,
|
||||
snapshotMatchesProfile,
|
||||
snapshotMatchesTarget,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
parseAnalysisSnapshot,
|
||||
type AnalysisSnapshot,
|
||||
type AnalysisSnapshotEntry,
|
||||
type AnalysisSnapshotWorkflowEntry,
|
||||
type AnalysisSnapshotBinding,
|
||||
type AnalysisSnapshotTarget,
|
||||
} from "../../domain/analysisSnapshot.js";
|
||||
@@ -54,6 +56,9 @@ const DOCUMENT_SCOPED_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
),
|
||||
);
|
||||
|
||||
/** Maximum duplicated result bindings retained across direct and workflow queries. */
|
||||
export const SNAPSHOT_CACHE_ENTRY_CEILING = 10_000;
|
||||
|
||||
/** Whether an operation is immutable and independent of provider UI state. */
|
||||
export const isSnapshotCacheable = (
|
||||
operation: AnalysisOperation,
|
||||
@@ -73,6 +78,7 @@ export const isSnapshotCacheable = (
|
||||
/** Bounded in-memory cache for one immutable binary identity. */
|
||||
export class AnalysisSnapshotCache {
|
||||
readonly #entries = new Map<string, AnalysisSnapshotEntry>();
|
||||
readonly #workflowEntries = new Map<string, AnalysisSnapshotWorkflowEntry>();
|
||||
#target: AnalysisSnapshotTarget | undefined;
|
||||
#binding: AnalysisSnapshotBinding | undefined;
|
||||
|
||||
@@ -93,7 +99,7 @@ export class AnalysisSnapshotCache {
|
||||
|
||||
/** Replace cache state when the target or selected profile changes. */
|
||||
select(target: BinaryTarget, profile: AnalysisProfileCommitment): void {
|
||||
if (!this.matches(target, profile)) this.#entries.clear();
|
||||
if (!this.matches(target, profile)) this.#clearEntries();
|
||||
this.#target = snapshotTarget(target);
|
||||
this.#binding = snapshotBinding(profile);
|
||||
}
|
||||
@@ -109,14 +115,20 @@ export class AnalysisSnapshotCache {
|
||||
snapshot.binding.analysis_profile,
|
||||
))
|
||||
)
|
||||
this.#entries.clear();
|
||||
this.#clearEntries();
|
||||
this.#target = structuredClone(snapshot.target);
|
||||
this.#binding = structuredClone(snapshot.binding);
|
||||
let imported = 0;
|
||||
for (const entry of snapshot.entries) {
|
||||
if (!this.#entries.has(entry.query_id) && !this.#hasCapacity()) continue;
|
||||
if (!this.#entries.has(entry.query_id)) imported += 1;
|
||||
this.#entries.set(entry.query_id, structuredClone(entry));
|
||||
}
|
||||
for (const entry of snapshot.workflow_entries ?? []) {
|
||||
if (!this.#workflowEntries.has(entry.query_id) && !this.#hasCapacity())
|
||||
continue;
|
||||
this.#workflowEntries.set(entry.query_id, structuredClone(entry));
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
|
||||
@@ -137,6 +149,9 @@ export class AnalysisSnapshotCache {
|
||||
target: snapshotTargetIdentity,
|
||||
binding,
|
||||
entries: this.entries(),
|
||||
...(this.workflowEntries().length === 0
|
||||
? {}
|
||||
: { workflow_entries: this.workflowEntries() }),
|
||||
evidence_bundle: retainedEvidence,
|
||||
}),
|
||||
);
|
||||
@@ -193,6 +208,47 @@ export class AnalysisSnapshotCache {
|
||||
.map((entry) => structuredClone(entry));
|
||||
}
|
||||
|
||||
/** Return canonical composed-workflow entries for persistence. */
|
||||
workflowEntries(): AnalysisSnapshotWorkflowEntry[] {
|
||||
return [...this.#workflowEntries.values()]
|
||||
.sort((left, right) => left.query_id.localeCompare(right.query_id))
|
||||
.map((entry) => structuredClone(entry));
|
||||
}
|
||||
|
||||
/** Record one exact derived workflow result unless the shared cache is full. */
|
||||
recordWorkflow(input: {
|
||||
readonly target: BinaryTarget;
|
||||
readonly profile: AnalysisProfileCommitment;
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly execution: {
|
||||
readonly result: JsonValue;
|
||||
readonly rawResult: JsonValue | null;
|
||||
readonly provider: AnalysisExecution["provider"];
|
||||
readonly analysisProfile: AnalysisProfileCommitment;
|
||||
readonly limitations: readonly string[];
|
||||
readonly locations: AnalysisExecution["locations"];
|
||||
readonly subject: AnalysisExecution["subject"];
|
||||
};
|
||||
}): void {
|
||||
this.select(input.target, input.profile);
|
||||
const queryId = analysisQueryId(
|
||||
snapshotTarget(input.target),
|
||||
snapshotBinding(input.profile),
|
||||
input.operation,
|
||||
input.parameters,
|
||||
);
|
||||
if (!this.#workflowEntries.has(queryId) && !this.#hasCapacity()) return;
|
||||
const entry = createAnalysisSnapshotWorkflowEntry({
|
||||
target: snapshotTarget(input.target),
|
||||
binding: snapshotBinding(input.profile),
|
||||
operation: input.operation,
|
||||
parameters: input.parameters,
|
||||
execution: input.execution,
|
||||
});
|
||||
this.#workflowEntries.set(entry.query_id, entry);
|
||||
}
|
||||
|
||||
/** Replay an exact provider-specific query, marking its cached provenance. */
|
||||
lookup(
|
||||
target: BinaryTarget,
|
||||
@@ -246,8 +302,14 @@ export class AnalysisSnapshotCache {
|
||||
readonly execution: AnalysisExecution;
|
||||
}): void {
|
||||
const { target, profile, operation, parameters, execution } = input;
|
||||
if (this.#entries.size >= 10_000) return;
|
||||
this.select(target, profile);
|
||||
const queryId = analysisQueryId(
|
||||
snapshotTarget(target),
|
||||
snapshotBinding(profile),
|
||||
operation,
|
||||
parameters,
|
||||
);
|
||||
if (!this.#entries.has(queryId) && !this.#hasCapacity()) return;
|
||||
const entry = createAnalysisSnapshotEntry({
|
||||
target: snapshotTarget(target),
|
||||
binding: snapshotBinding(profile),
|
||||
@@ -260,8 +322,20 @@ export class AnalysisSnapshotCache {
|
||||
|
||||
/** Forget all target-bound entries. */
|
||||
clear(): void {
|
||||
this.#entries.clear();
|
||||
this.#clearEntries();
|
||||
this.#target = undefined;
|
||||
this.#binding = undefined;
|
||||
}
|
||||
|
||||
#clearEntries(): void {
|
||||
this.#entries.clear();
|
||||
this.#workflowEntries.clear();
|
||||
}
|
||||
|
||||
#hasCapacity(): boolean {
|
||||
return (
|
||||
this.#entries.size + this.#workflowEntries.size <
|
||||
SNAPSHOT_CACHE_ENTRY_CEILING
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,10 @@ import { BinarySessionRecords } from "./BinarySessionRecords.js";
|
||||
import { binarySessionStatus } from "./BinarySessionStatus.js";
|
||||
import {
|
||||
resolveSessionOpen,
|
||||
resolveSessionTarget,
|
||||
validateResolvedSessionTarget,
|
||||
type BinarySessionOpenOptions,
|
||||
type ResolvedSessionOpen,
|
||||
} from "./BinarySessionOpen.js";
|
||||
import {
|
||||
bindExecutionTarget,
|
||||
@@ -150,6 +153,27 @@ export class BinarySession
|
||||
return () => this.#availabilityListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Resolve a target and provider profile without creating a provider client. */
|
||||
previewTarget(
|
||||
target: BinaryTarget,
|
||||
options: BinarySessionOpenOptions = {},
|
||||
): Promise<Result<ResolvedSessionOpen, AnalysisError>> {
|
||||
if (isAborted(options.signal))
|
||||
return Promise.resolve(err(new AnalysisCancelledError("open_binary")));
|
||||
return resolveSessionTarget({
|
||||
router: this.#providerRouter,
|
||||
current: this.#active,
|
||||
target,
|
||||
options,
|
||||
stagedSnapshotMatches: (target, profile) =>
|
||||
this.matchesSnapshot(target, profile),
|
||||
}).then((resolved) =>
|
||||
isAborted(options.signal)
|
||||
? err(new AnalysisCancelledError("open_binary"))
|
||||
: resolved,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open or switch targets after draining calls against the current target.
|
||||
* Returns the switch failure even if best-effort restoration also fails.
|
||||
@@ -157,18 +181,49 @@ export class BinarySession
|
||||
open(
|
||||
path: string,
|
||||
options: BinarySessionOpenOptions = {},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#open(
|
||||
() =>
|
||||
resolveSessionOpen({
|
||||
router: this.#providerRouter,
|
||||
current: this.#active,
|
||||
path,
|
||||
options,
|
||||
stagedSnapshotMatches: (target, profile) =>
|
||||
this.matchesSnapshot(target, profile),
|
||||
}),
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/** Open a previewed target without repeating parsing or provider profile discovery. */
|
||||
openResolvedTarget(
|
||||
resolved: Pick<ResolvedSessionOpen, "target" | "route">,
|
||||
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot"> = {},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#open(
|
||||
() =>
|
||||
Promise.resolve(
|
||||
validateResolvedSessionTarget({
|
||||
...resolved,
|
||||
current: this.#active,
|
||||
options,
|
||||
stagedSnapshotMatches: (target, profile) =>
|
||||
this.matchesSnapshot(target, profile),
|
||||
}),
|
||||
),
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
#open(
|
||||
resolve: () => Promise<Result<ResolvedSessionOpen, AnalysisError>>,
|
||||
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot">,
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#serialize(async () => {
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
const resolved = await resolveSessionOpen({
|
||||
router: this.#providerRouter,
|
||||
current: this.#active,
|
||||
path,
|
||||
options,
|
||||
stagedSnapshotMatches: (target, profile) =>
|
||||
this.matchesSnapshot(target, profile),
|
||||
});
|
||||
const resolved = await resolve();
|
||||
if (!resolved.ok) return resolved;
|
||||
const { target, route, sameTarget } = resolved.value;
|
||||
const { profile, compatibility } = route;
|
||||
|
||||
@@ -46,11 +46,22 @@ interface ResolveSessionOpenInput {
|
||||
) => boolean;
|
||||
}
|
||||
|
||||
interface ResolveSessionTargetInput {
|
||||
readonly router: SessionProviderRouter;
|
||||
readonly current: CurrentOpenBinding | undefined;
|
||||
readonly target: BinaryTarget;
|
||||
readonly options: BinarySessionOpenOptions;
|
||||
readonly stagedSnapshotMatches: (
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment | null,
|
||||
) => boolean;
|
||||
}
|
||||
|
||||
/** Parse a target, resolve its provider route, and validate snapshot binding. */
|
||||
export const resolveSessionOpen = async (
|
||||
input: ResolveSessionOpenInput,
|
||||
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
|
||||
const { router, current, path, options, stagedSnapshotMatches } = input;
|
||||
const { path, options } = input;
|
||||
const parsed = await parseBinaryTarget(
|
||||
path,
|
||||
process.cwd(),
|
||||
@@ -59,7 +70,14 @@ export const resolveSessionOpen = async (
|
||||
options.formatHint,
|
||||
);
|
||||
if (!parsed.ok) return parsed;
|
||||
const target = parsed.value;
|
||||
return resolveSessionTarget({ ...input, target: parsed.value });
|
||||
};
|
||||
|
||||
/** Resolve a known target's provider route and validate snapshot binding. */
|
||||
export const resolveSessionTarget = async (
|
||||
input: ResolveSessionTargetInput,
|
||||
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
|
||||
const { router, current, target, options } = input;
|
||||
const sameTarget =
|
||||
current?.target.path === target.path &&
|
||||
snapshotMatchesTarget(snapshotTarget(current.target), target);
|
||||
@@ -68,7 +86,22 @@ export const resolveSessionOpen = async (
|
||||
? ({ ok: true, value: current.route } as const)
|
||||
: await router.resolve(target, options.providerId, options.signal);
|
||||
if (!resolvedRoute.ok) return resolvedRoute;
|
||||
const route = resolvedRoute.value;
|
||||
return validateResolvedSessionTarget({
|
||||
...input,
|
||||
route: resolvedRoute.value,
|
||||
});
|
||||
};
|
||||
|
||||
/** Revalidate a previewed route against the current session and snapshot binding. */
|
||||
export const validateResolvedSessionTarget = (
|
||||
input: Omit<ResolveSessionTargetInput, "router"> & {
|
||||
readonly route: SessionProviderRoute;
|
||||
},
|
||||
): Result<ResolvedSessionOpen, AnalysisError> => {
|
||||
const { current, target, route, options, stagedSnapshotMatches } = input;
|
||||
const sameTarget =
|
||||
current?.target.path === target.path &&
|
||||
snapshotMatchesTarget(snapshotTarget(current.target), target);
|
||||
const snapshotError = validateSnapshot({
|
||||
snapshot: options.snapshot,
|
||||
target,
|
||||
|
||||
@@ -68,7 +68,8 @@ export abstract class BinarySessionRecords {
|
||||
): Result<number, EvidenceIntegrityError> {
|
||||
const imported = this.#records.mergeEvidenceBundle(bundle);
|
||||
if (!imported.ok) return imported;
|
||||
if (imported.value.changed) this.#emitSnapshotChanged();
|
||||
if (imported.value.metadataChanged) this.invalidateSnapshot();
|
||||
else if (imported.value.changed) this.#emitSnapshotChanged();
|
||||
return ok(imported.value.recordsAdded);
|
||||
}
|
||||
|
||||
@@ -159,6 +160,43 @@ export abstract class BinarySessionRecords {
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
/** Retain one derived workflow result alongside its provider cache entries. */
|
||||
recordWorkflowSnapshot(input: {
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<
|
||||
Record<string, import("../../domain/jsonValue.js").JsonValue>
|
||||
>;
|
||||
readonly execution: Parameters<
|
||||
AnalysisSnapshotCache["recordWorkflow"]
|
||||
>[0]["execution"];
|
||||
}): Result<null, EvidenceIntegrityError> {
|
||||
const active = this.activeAnalysisBinding();
|
||||
if (active === undefined || active.profile === null)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Workflow snapshot entries require an active concrete provider profile",
|
||||
),
|
||||
);
|
||||
try {
|
||||
this.#snapshot.recordWorkflow({
|
||||
target: active.target,
|
||||
profile: active.profile,
|
||||
...input,
|
||||
});
|
||||
this.#emitSnapshotChanged();
|
||||
return ok(null);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "Workflow snapshot entry validation failed",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
protected invalidateSnapshot(): void {
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = true;
|
||||
|
||||
@@ -43,7 +43,6 @@ const input = (
|
||||
overrides: Partial<RecordUnknownInput> = {},
|
||||
): RecordUnknownInput =>
|
||||
recordUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
question,
|
||||
severity: "high",
|
||||
domain: "protocol",
|
||||
@@ -60,7 +59,6 @@ const update = (
|
||||
overrides: Readonly<Record<string, unknown>> = {},
|
||||
) =>
|
||||
updateUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
unknown_id: unknown.unknown_id,
|
||||
expected_revision: unknown.revision,
|
||||
status: "investigating",
|
||||
@@ -77,6 +75,78 @@ const update = (
|
||||
});
|
||||
|
||||
describe("residual unknown registry reads and identity", () => {
|
||||
it("merges record-only bundles without changing retained unknown history", () => {
|
||||
const store = ledger();
|
||||
const created = store.recordUnknown(
|
||||
input("Does a later record preserve this unknown?"),
|
||||
mutation("record-only-import"),
|
||||
);
|
||||
expect(created.ok).toBe(true);
|
||||
const originalUnknowns = store.export().unknowns;
|
||||
const addition = evidence("record-only-addition");
|
||||
const bundle = createEvidenceBundle([addition]);
|
||||
|
||||
expect(store.import(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 1,
|
||||
unknownsAdded: 0,
|
||||
changed: true,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
expect(store.export().unknowns).toEqual(originalUnknowns);
|
||||
expect(store.import(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: false,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("residual unknown dependency histories", () => {
|
||||
it("imports a valid dependency chain deeper than the JavaScript call stack", () => {
|
||||
const records = [];
|
||||
const unknowns: ResidualUnknown[] = [];
|
||||
let previousId: string | undefined;
|
||||
for (let index = 0; index < 10_000; index += 1) {
|
||||
const mutationEvidence = mutation(`deep-chain-${index}`);
|
||||
records.push(mutationEvidence);
|
||||
const relationships =
|
||||
previousId === undefined
|
||||
? []
|
||||
: [{ type: "depends-on" as const, unknown_id: previousId }];
|
||||
const unknown = createResidualUnknown(
|
||||
input(`Does chain item ${index} meet the expected state?`, {
|
||||
domain: "chain-profile",
|
||||
required_authority: null,
|
||||
relationships,
|
||||
}),
|
||||
mutationEvidence.evidence_id,
|
||||
null,
|
||||
);
|
||||
unknowns.push(unknown);
|
||||
previousId = unknown.unknown_id;
|
||||
}
|
||||
const bundle = createEvidenceBundle(records, unknowns);
|
||||
const store = ledger();
|
||||
|
||||
expect(store.import(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 10_000,
|
||||
unknownsAdded: 10_000,
|
||||
changed: true,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
expect(store.export()).toEqual(bundle);
|
||||
});
|
||||
|
||||
it("returns detached unknowns and evidence bundles from every read surface", () => {
|
||||
const store = ledger();
|
||||
expect(store.record(evidence("detached-record")).ok).toBe(true);
|
||||
|
||||
@@ -38,9 +38,55 @@ describe("evidence ledger recording", () => {
|
||||
});
|
||||
expect(ledger.import(createEvidenceBundle([evidence]))).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: false,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
expect(ledger.export().records).toEqual([evidence]);
|
||||
const relocatedBundleRecord = createEvidence(
|
||||
{ ...TARGET, path: "/relocated/fixture-renamed" },
|
||||
PROVIDER,
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
);
|
||||
expect(
|
||||
ledger.import(createEvidenceBundle([relocatedBundleRecord])),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: true,
|
||||
metadataChanged: true,
|
||||
},
|
||||
});
|
||||
expect(ledger.get(evidence.evidence_id)).toEqual(relocatedBundleRecord);
|
||||
expect(ledger.export().records).toEqual([relocatedBundleRecord]);
|
||||
expect(
|
||||
ledger.import(createEvidenceBundle([relocatedBundleRecord])),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: false,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
const conflictingBundle = createEvidenceBundle([
|
||||
evidence,
|
||||
relocatedBundleRecord,
|
||||
]);
|
||||
expect(ledger.import(conflictingBundle).ok).toBe(false);
|
||||
expect(ledger.get(evidence.evidence_id)).toEqual(relocatedBundleRecord);
|
||||
ledger.clear();
|
||||
expect(ledger.export().records).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores JSON object key order during imported identity checks", () => {
|
||||
const ledger = new EvidenceLedger();
|
||||
const ordered = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: { alpha: 1, beta: 2 },
|
||||
@@ -60,11 +106,77 @@ describe("evidence ledger recording", () => {
|
||||
);
|
||||
expect(ledger.import(reorderedBundle)).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: false,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
ledger.clear();
|
||||
expect(ledger.export().records).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evidence ledger metadata imports", () => {
|
||||
it("reports and commits metadata replacement when importing unknown history", () => {
|
||||
const ledger = new EvidenceLedger();
|
||||
const mutation = createEvidence(TARGET, PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation",
|
||||
operation: "record_unknown",
|
||||
parameters: {},
|
||||
result: { action: "record", question: "Which path is current?" },
|
||||
});
|
||||
const created = ledger.recordUnknown(
|
||||
recordUnknownInputSchema.parse({
|
||||
question: "Which path is current?",
|
||||
severity: "high",
|
||||
domain: "fixture",
|
||||
required_authority: null,
|
||||
required_confidence: "derived",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
}),
|
||||
mutation,
|
||||
);
|
||||
expect(created.ok).toBe(true);
|
||||
const relocatedMutation = createEvidence(
|
||||
{ ...TARGET, path: "/relocated/mutation" },
|
||||
PROVIDER,
|
||||
{
|
||||
predicateType: "rea.residual-unknown-mutation",
|
||||
operation: "record_unknown",
|
||||
parameters: {},
|
||||
result: { action: "record", question: "Which path is current?" },
|
||||
},
|
||||
);
|
||||
expect(relocatedMutation.evidence_id).toBe(mutation.evidence_id);
|
||||
const bundle = createEvidenceBundle(
|
||||
[relocatedMutation],
|
||||
ledger.export().unknowns,
|
||||
);
|
||||
|
||||
expect(ledger.import(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: true,
|
||||
metadataChanged: true,
|
||||
},
|
||||
});
|
||||
expect(ledger.get(mutation.evidence_id)).toEqual(relocatedMutation);
|
||||
expect(ledger.import(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: false,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("retains more than ten thousand inline evidence records", () => {
|
||||
const ledger = new EvidenceLedger();
|
||||
@@ -128,7 +240,6 @@ describe("evidence bundle imports", () => {
|
||||
result: { action: "record" },
|
||||
});
|
||||
const unknown = recordUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
question: "What remains unresolved?",
|
||||
severity: "high",
|
||||
domain: "atomic-test",
|
||||
|
||||
@@ -27,6 +27,7 @@ export interface EvidenceImportDelta {
|
||||
readonly recordsAdded: number;
|
||||
readonly unknownsAdded: number;
|
||||
readonly changed: boolean;
|
||||
readonly metadataChanged: boolean;
|
||||
}
|
||||
|
||||
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
|
||||
@@ -70,11 +71,50 @@ export class EvidenceLedger {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A record-only bundle cannot change the already-valid unknown graph. The
|
||||
// bundle parser has validated every incoming record and its manifests, so
|
||||
// checking ID conflicts and committing only the additions preserves the
|
||||
// atomic merge without rebuilding and reparsing the entire ledger.
|
||||
if (bundle.unknowns.length === 0) {
|
||||
const additions = new Map<string, Evidence>();
|
||||
const replacements = new Map<string, Evidence>();
|
||||
let metadataChanged = false;
|
||||
for (const evidence of bundle.records) {
|
||||
const existing = this.#records.get(evidence.evidence_id);
|
||||
if (existing !== undefined) {
|
||||
if (!recordsAgree(existing, evidence))
|
||||
return err(
|
||||
new EvidenceIntegrityError("Conflicting evidence record"),
|
||||
);
|
||||
if (canonicalize(existing) !== canonicalize(evidence)) {
|
||||
replacements.set(evidence.evidence_id, evidence);
|
||||
metadataChanged = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
additions.set(evidence.evidence_id, evidence);
|
||||
}
|
||||
for (const [id, evidence] of replacements)
|
||||
this.#records.set(id, evidence);
|
||||
for (const [id, evidence] of additions) this.#records.set(id, evidence);
|
||||
return ok({
|
||||
recordsAdded: additions.size,
|
||||
unknownsAdded: 0,
|
||||
changed: additions.size > 0 || metadataChanged,
|
||||
metadataChanged,
|
||||
});
|
||||
}
|
||||
const pending = new Map(this.#records);
|
||||
let metadataChanged = false;
|
||||
for (const evidence of bundle.records) {
|
||||
const existing = pending.get(evidence.evidence_id);
|
||||
if (existing !== undefined && !recordsAgree(existing, evidence))
|
||||
return err(new EvidenceIntegrityError("Conflicting evidence record"));
|
||||
if (
|
||||
existing !== undefined &&
|
||||
canonicalize(existing) !== canonicalize(evidence)
|
||||
)
|
||||
metadataChanged = true;
|
||||
pending.set(evidence.evidence_id, evidence);
|
||||
}
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
@@ -108,7 +148,8 @@ export class EvidenceLedger {
|
||||
return ok({
|
||||
recordsAdded: added,
|
||||
unknownsAdded,
|
||||
changed: added > 0 || unknownsAdded > 0,
|
||||
changed: added > 0 || unknownsAdded > 0 || metadataChanged,
|
||||
metadataChanged,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -101,9 +101,18 @@ describe("investigation record ownership", () => {
|
||||
);
|
||||
if (!created.ok) throw created.error;
|
||||
const input = updateUnknownInputSchema.parse({
|
||||
...created.value,
|
||||
unknown_id: created.value.unknown_id,
|
||||
expected_revision: created.value.revision,
|
||||
status: "investigating",
|
||||
severity: created.value.severity,
|
||||
supporting_evidence_ids: created.value.supporting_evidence_ids,
|
||||
contradicting_evidence_ids: created.value.contradicting_evidence_ids,
|
||||
required_authority: created.value.required_authority,
|
||||
required_confidence: created.value.required_confidence,
|
||||
required_environment: created.value.required_environment,
|
||||
recommended_probes: created.value.recommended_probes,
|
||||
relationships: created.value.relationships,
|
||||
resolution: created.value.resolution,
|
||||
});
|
||||
const updated = records.updateUnknown(input, target);
|
||||
expect(updated).toMatchObject({
|
||||
@@ -133,11 +142,21 @@ describe("investigation record ownership", () => {
|
||||
).toBe(true);
|
||||
expect(records.mergeEvidenceBundle(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 1, changed: true },
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 1,
|
||||
changed: true,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
expect(records.mergeEvidenceBundle(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
|
||||
value: {
|
||||
recordsAdded: 0,
|
||||
unknownsAdded: 0,
|
||||
changed: false,
|
||||
metadataChanged: false,
|
||||
},
|
||||
});
|
||||
records.clear();
|
||||
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
|
||||
|
||||
@@ -55,6 +55,24 @@ it.each([
|
||||
await expect(analyzeSource(source)).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it("analyzes a plain long-line loader without package metadata", async () => {
|
||||
const output = await analyzeSource(
|
||||
`var Module = {}; fetch(""); new Worker(""); var payload = "${"x".repeat(65_536)}";`,
|
||||
{ "game-data.js": "Module.data = { ready: true };" },
|
||||
);
|
||||
const nodes = output.graph.nodes.filter(
|
||||
({ kind }) => kind === "endpoint" || kind === "worker",
|
||||
);
|
||||
expect(nodes.map(({ kind }) => kind).sort()).toEqual(["endpoint", "worker"]);
|
||||
for (const node of nodes) {
|
||||
expect(node.identity).toMatchObject({
|
||||
strategy: "artifact-local-key",
|
||||
key: "",
|
||||
});
|
||||
expect(node.observations.map(({ label }) => label)).toEqual([null]);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps exact values for empty literals without synthetic application labels", async () => {
|
||||
const output = await analyzeSource(
|
||||
"fetch(''); fetch('\"\"'); fetch('/api'); process.on('', () => 1);",
|
||||
|
||||
@@ -47,6 +47,8 @@ describe("JavaScript application failure diagnostics", () => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-failure-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const cause = new RangeError("Invalid string length");
|
||||
// Retain the original failure locally, but never serialize its object graph.
|
||||
cause.cause = cause;
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
@@ -72,6 +74,8 @@ describe("JavaScript application failure diagnostics", () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
const projection = projectAnalysisError(result.error);
|
||||
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
|
||||
});
|
||||
|
||||
it("keeps filesystem failures distinct from engine failures", async () => {
|
||||
@@ -119,4 +123,35 @@ describe("JavaScript application failure diagnostics", () => {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([new Error("x".repeat(10_000)), "y".repeat(10_000)])(
|
||||
"preserves long failure messages through JSON projection (%#)",
|
||||
async (cause) => {
|
||||
const inputPath = await createTestTempDirectory("rea-js-oversized-");
|
||||
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
|
||||
const message = cause instanceof Error ? cause.message : cause;
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
{ input_path: inputPath, format: "directory" },
|
||||
{
|
||||
progress: {
|
||||
report: async (event) => {
|
||||
if (event.terminal) throw cause;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Expected analysis failure");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
error_message: message,
|
||||
},
|
||||
},
|
||||
});
|
||||
const projection = projectAnalysisError(result.error);
|
||||
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -57,13 +57,27 @@ export const analyzeJavaScriptApplicationValidated = async (
|
||||
format: input.format,
|
||||
},
|
||||
options.signal,
|
||||
options.progress,
|
||||
);
|
||||
const { electron_summary: summary, ...application } = reconstructed;
|
||||
await options.progress?.report({
|
||||
phase: "validate_javascript_application_result",
|
||||
completed: 0,
|
||||
total: 1,
|
||||
message: "Validating the application analysis result",
|
||||
});
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse({
|
||||
...application,
|
||||
summary,
|
||||
limitations: reconstructed.graph.limitations,
|
||||
});
|
||||
await options.progress?.report({
|
||||
phase: "create_javascript_application_evidence",
|
||||
completed: 0,
|
||||
total: 1,
|
||||
message: "Creating and hashing application analysis Evidence",
|
||||
});
|
||||
const evidence = createJavaScriptApplicationEvidence(input, result);
|
||||
await options.progress?.report({
|
||||
phase: "analyze_javascript_application",
|
||||
completed: 1,
|
||||
@@ -71,7 +85,7 @@ export const analyzeJavaScriptApplicationValidated = async (
|
||||
message: "Application graph and Electron boundaries reconstructed",
|
||||
terminal: true,
|
||||
});
|
||||
return ok(createJavaScriptApplicationEvidence(input, result));
|
||||
return ok(evidence);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure)
|
||||
return err(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ArtifactInventorySnapshot } from "../ArtifactInventory.js";
|
||||
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
type JavaScriptApplicationGraph,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ArtifactInventorySnapshot } from "../ArtifactInventory.js";
|
||||
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
|
||||
import {
|
||||
completeApplicationCoverage,
|
||||
partialApplicationCoverage,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ArtifactInventorySnapshot } from "../ArtifactInventory.js";
|
||||
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
|
||||
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraph.js";
|
||||
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
|
||||
@@ -9,6 +9,42 @@ import { artifactLocalIdentity } from "./JavaScriptArtifactGraphContext.js";
|
||||
import { applicationNodeIdentitySchema } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
|
||||
import { analyzeJavaScriptStaticSource } from "../../domain/javascript/javascriptStaticAnalysis.js";
|
||||
|
||||
describe("artifact URI scheme classification", () => {
|
||||
it.each(["html-reference", "module-specifier", "url-reference"] as const)(
|
||||
"keeps digit-bearing schemes external in %s even when a local file matches",
|
||||
(context) => {
|
||||
const files = fileMap([
|
||||
file("index.html", "root"),
|
||||
file("web3:app.js", "root"),
|
||||
]);
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "web3:app.js",
|
||||
sourcePath: "index.html",
|
||||
context,
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolution_status: "external", resolved_path: null });
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps references under a digit-bearing external base href external", () => {
|
||||
const files = fileMap([
|
||||
file("index.html", "root"),
|
||||
file("web3:assets/app.js", "root"),
|
||||
]);
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: "app.js",
|
||||
sourcePath: "index.html",
|
||||
context: "html-reference",
|
||||
htmlBaseHref: "web3:assets/",
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({ resolution_status: "external", resolved_path: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("artifact-local graph identity", () => {
|
||||
it("preserves complete long namespace and key values", () => {
|
||||
const digest = "a".repeat(64);
|
||||
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
javascriptArtifactReconstructionInputSchema,
|
||||
type JavaScriptArtifactReconstructionInput,
|
||||
} from "./JavaScriptArtifactReconstructionInput.js";
|
||||
import { scanCanonicalArtifactInventory } from "../ArtifactInventory.js";
|
||||
import { scanCanonicalArtifactInventory } from "../../artifacts/inventory/ArtifactInventory.js";
|
||||
import { summarizeElectronBoundaries } from "./ElectronBoundaryAnalysis.js";
|
||||
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
|
||||
import type { ProgressReporter } from "../ProgressReporter.js";
|
||||
|
||||
/** Application-layer result retaining local diagnostics outside the canonical graph. */
|
||||
export interface JavaScriptArtifactReconstructionResult {
|
||||
@@ -45,7 +46,11 @@ export interface JavaScriptArtifactReconstructionResult {
|
||||
export const reconstructJavaScriptArtifact = async (
|
||||
rawInput: unknown,
|
||||
signal?: AbortSignal,
|
||||
progress?: ProgressReporter,
|
||||
): Promise<JavaScriptArtifactReconstructionResult> => {
|
||||
const reportPhase = async (phase: string, message: string): Promise<void> => {
|
||||
await progress?.report({ phase, completed: 0, total: 1, message });
|
||||
};
|
||||
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
|
||||
abortIfNeeded(signal);
|
||||
const path = await realpath(input.input_path);
|
||||
@@ -58,10 +63,26 @@ export const reconstructJavaScriptArtifact = async (
|
||||
);
|
||||
const reader = createReader(path, format);
|
||||
try {
|
||||
await reportPhase(
|
||||
"read_javascript_artifacts",
|
||||
"Reading inventoried JavaScript application sources",
|
||||
);
|
||||
const files = await readJavaScriptArtifactFiles(reader, snapshot, signal);
|
||||
await reportPhase(
|
||||
"parse_javascript_sources",
|
||||
`Parsing ${String(files.files.length)} application source files`,
|
||||
);
|
||||
const analysis = analyzeJavaScriptArtifactFiles(files);
|
||||
abortIfNeeded(signal);
|
||||
await reportPhase(
|
||||
"build_javascript_application_graph",
|
||||
"Constructing application and Electron boundary relationships",
|
||||
);
|
||||
const graph = buildJavaScriptArtifactGraph(snapshot, files, analysis);
|
||||
await reportPhase(
|
||||
"build_javascript_semantic_graph",
|
||||
"Constructing static semantic relationships",
|
||||
);
|
||||
const semanticGraph = buildJavaScriptSemanticGraph({
|
||||
rootArtifactSha256: snapshot.manifest.root_sha256,
|
||||
applicationGraph: graph,
|
||||
|
||||
@@ -20,37 +20,46 @@ const filesFor = (paths: readonly string[]) =>
|
||||
]),
|
||||
);
|
||||
|
||||
const cases = ["#", "?"].flatMap((punctuation) =>
|
||||
(["require", "import", undefined] as const).flatMap((moduleKind) =>
|
||||
(["literal", "stripped", "both"] as const).map((layout) => ({
|
||||
punctuation,
|
||||
moduleKind,
|
||||
layout,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
describe("module specifier punctuation", () => {
|
||||
it.each(cases)(
|
||||
"resolves $moduleKind with $punctuation and $layout files",
|
||||
({ punctuation, moduleKind, layout }) => {
|
||||
it.each(["#", "?"])(
|
||||
"keeps CommonJS punctuation and strips URL suffixes for ESM (%s)",
|
||||
(punctuation) => {
|
||||
const literal = `app/dep.cjs${punctuation}literal.cjs`;
|
||||
const stripped = "app/dep.cjs";
|
||||
const files = filesFor([
|
||||
...(layout !== "stripped" ? [literal] : []),
|
||||
...(layout !== "literal" ? [stripped] : []),
|
||||
]);
|
||||
const expected = moduleKind === "require" ? literal : stripped;
|
||||
const result = resolveArtifactPathByContext({
|
||||
const commonJs = resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
files,
|
||||
...(moduleKind === undefined ? {} : { moduleKind }),
|
||||
files: filesFor([literal, stripped]),
|
||||
moduleKind: "require",
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
resolution_status: files.has(expected) ? "resolved" : "not-found",
|
||||
resolved_path: files.has(expected) ? expected : null,
|
||||
expect(commonJs).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: literal,
|
||||
});
|
||||
|
||||
const esm = resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
files: filesFor([literal, stripped]),
|
||||
moduleKind: "import",
|
||||
});
|
||||
expect(esm).toMatchObject({
|
||||
resolution_status: "resolved",
|
||||
resolved_path: stripped,
|
||||
});
|
||||
|
||||
const noStrippedTarget = resolveArtifactPathByContext({
|
||||
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
|
||||
sourcePath: "app/main.js",
|
||||
context: "module-specifier",
|
||||
files: filesFor([literal]),
|
||||
moduleKind: "import",
|
||||
});
|
||||
expect(noStrippedTarget).toMatchObject({
|
||||
resolution_status: "not-found",
|
||||
resolved_path: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
|
||||
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
|
||||
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
|
||||
|
||||
const projectReturns = (body: string) => {
|
||||
const ir = analyzeJavaScriptSemantics(`export function result() { ${body} }`);
|
||||
const link = ir.moduleLinks.find(
|
||||
({ exportedName }) => exportedName === "result",
|
||||
);
|
||||
if (link === undefined) throw new Error("Expected the result export");
|
||||
const projected = projectJavaScriptExportReturnShapes({
|
||||
ir,
|
||||
link,
|
||||
modulePath: "fixture.js",
|
||||
baseCoverage: completeApplicationCoverage(),
|
||||
});
|
||||
if (projected === null) throw new Error("Expected exported return shapes");
|
||||
return projected;
|
||||
};
|
||||
|
||||
const unknownBranchField = {
|
||||
path: "",
|
||||
state: "unknown",
|
||||
value: null,
|
||||
reason: "Branches have incompatible values.",
|
||||
};
|
||||
|
||||
describe("exported primitive union return shapes", () => {
|
||||
const conditionalCases = [
|
||||
"missing",
|
||||
"unsupported()",
|
||||
'({ key: "value" })',
|
||||
'["value"]',
|
||||
'+"invalid"',
|
||||
].flatMap((other) => [
|
||||
`condition ? (choice ? "one" : "two") : ${other}`,
|
||||
`condition ? ${other} : (choice ? "one" : "two")`,
|
||||
]);
|
||||
const logicalCases = [
|
||||
{ operator: "||", known: '(choice ? "" : "one")' },
|
||||
{ operator: "&&", known: '(choice ? 0 : "one")' },
|
||||
{ operator: "??", known: '(choice ? null : "one")' },
|
||||
].flatMap(({ operator, known }) => [
|
||||
`${known} ${operator} missing`,
|
||||
`missing ${operator} ${known}`,
|
||||
]);
|
||||
|
||||
it.each([...conditionalCases, ...logicalCases])(
|
||||
"projects an unknown field instead of a definite union for %s",
|
||||
(expression) => {
|
||||
const projected = projectReturns(`return ${expression};`);
|
||||
|
||||
expect(projected.properties.static_return_shapes).toEqual([
|
||||
{
|
||||
source_range: expect.any(Object),
|
||||
value_status: "ambiguous",
|
||||
fields: [unknownBranchField],
|
||||
property_coverage: [],
|
||||
},
|
||||
]);
|
||||
// Complete return-site collection does not make its values known.
|
||||
expect(projected.properties.return_shape_coverage).toEqual({
|
||||
status: "complete",
|
||||
retained_return_sites: 1,
|
||||
omitted_return_sites: 0,
|
||||
omitted_fields: 0,
|
||||
omitted_property_coverage: 0,
|
||||
projection_complete: true,
|
||||
});
|
||||
expect(projected.coverage).toEqual(completeApplicationCoverage());
|
||||
expect(projected.limitations).toContain(
|
||||
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an incompatible object field unknown beside a known literal", () => {
|
||||
const projected = projectReturns(`
|
||||
return {
|
||||
kind: "result",
|
||||
value: condition ? (choice ? "one" : "two") : missing,
|
||||
};
|
||||
`);
|
||||
expect(projected.properties.static_return_shapes).toEqual([
|
||||
{
|
||||
source_range: expect.any(Object),
|
||||
value_status: "object",
|
||||
fields: [
|
||||
{ path: "/kind", state: "literal", value: "result", reason: null },
|
||||
{ ...unknownBranchField, path: "/value" },
|
||||
],
|
||||
property_coverage: [{ path: "", status: "complete", omitted: 0 }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains valid nested unions, duplicates, and null alternatives", () => {
|
||||
const projected = projectReturns(`
|
||||
return condition
|
||||
? (choice ? "two" : "one")
|
||||
: (other ? "one" : null);
|
||||
`);
|
||||
expect(projected.properties.static_return_shapes).toEqual([
|
||||
{
|
||||
source_range: expect.any(Object),
|
||||
value_status: "union",
|
||||
fields: [
|
||||
{
|
||||
path: "",
|
||||
state: "union",
|
||||
value: [null, "one", "two"],
|
||||
reason: null,
|
||||
},
|
||||
],
|
||||
property_coverage: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves three independent direct returns without merging their values", () => {
|
||||
const projected = projectReturns(`
|
||||
if (condition) return choice ? "one" : "two";
|
||||
if (other) return missing;
|
||||
return { kind: "object" };
|
||||
`);
|
||||
expect(projected.properties.static_return_shapes).toEqual([
|
||||
{
|
||||
source_range: expect.any(Object),
|
||||
value_status: "union",
|
||||
fields: [
|
||||
{ path: "", state: "union", value: ["one", "two"], reason: null },
|
||||
],
|
||||
property_coverage: [],
|
||||
},
|
||||
{
|
||||
source_range: expect.any(Object),
|
||||
value_status: "unknown",
|
||||
fields: [
|
||||
{
|
||||
path: "",
|
||||
state: "unknown",
|
||||
value: null,
|
||||
reason: "Unbound identifier missing.",
|
||||
},
|
||||
],
|
||||
property_coverage: [],
|
||||
},
|
||||
{
|
||||
source_range: expect.any(Object),
|
||||
value_status: "object",
|
||||
fields: [
|
||||
{ path: "/kind", state: "literal", value: "object", reason: null },
|
||||
],
|
||||
property_coverage: [{ path: "", status: "complete", omitted: 0 }],
|
||||
},
|
||||
]);
|
||||
expect(projected.properties.return_shape_coverage).toMatchObject({
|
||||
status: "complete",
|
||||
retained_return_sites: 3,
|
||||
omitted_return_sites: 0,
|
||||
projection_complete: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,15 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
|
||||
import {
|
||||
buildJavaScriptSemanticGraph,
|
||||
SEMANTIC_GRAPH_FILE_NODE_CEILING,
|
||||
SEMANTIC_GRAPH_NODE_CEILING,
|
||||
} from "./JavaScriptSemanticGraphBuilder.js";
|
||||
import {
|
||||
addSemanticGraphNode,
|
||||
constructSemanticGraphNode,
|
||||
createSemanticGraphProjectionState,
|
||||
} from "./JavaScriptSemanticGraphConstruction.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
|
||||
import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
|
||||
@@ -287,6 +296,31 @@ const graphFor = (source: string) => {
|
||||
});
|
||||
};
|
||||
|
||||
const semanticNodeFor = (roleKey: string) => {
|
||||
const file: JavaScriptArtifactFile = {
|
||||
path: "budget.js",
|
||||
container_sha256: SHA256,
|
||||
sha256: SHA256,
|
||||
bytes: 0,
|
||||
inventory_artifact_id: `art_${SHA256}`,
|
||||
kind: "javascript",
|
||||
unpacked: false,
|
||||
text: { included: true, value: "" },
|
||||
};
|
||||
const state = createSemanticGraphProjectionState({ nodes: [] });
|
||||
return constructSemanticGraphNode(
|
||||
file,
|
||||
{
|
||||
kind: "expression",
|
||||
roleKey,
|
||||
location: null,
|
||||
label: roleKey,
|
||||
functionNodeId: null,
|
||||
},
|
||||
state,
|
||||
);
|
||||
};
|
||||
|
||||
it.each([
|
||||
"const value = consume(Promise.resolve(1));",
|
||||
"async function run() { await consume(Promise.resolve(1)); }",
|
||||
@@ -428,3 +462,75 @@ it.each([
|
||||
expect(query.relations).toContainEqual(relation);
|
||||
expect(query.nodes.map(({ node_id }) => node_id)).toContain(promise?.node_id);
|
||||
});
|
||||
|
||||
it("bounds semantic node projection and reports the ceiling in coverage", () => {
|
||||
// A bundled vendor library can emit tens of thousands of semantic nodes on its
|
||||
// own (measured: 135,286 from one minified editor bundle). Without a ceiling the
|
||||
// projection exhausts the heap and the result cannot be serialized. The bound
|
||||
// must be reported through coverage rather than dropping data silently.
|
||||
const statements = Array.from(
|
||||
{ length: 4_000 },
|
||||
(_, index) =>
|
||||
`const value${index} = { a: ${index}, b: [${index}, ${index + 1}] };`,
|
||||
).join("\n");
|
||||
const graph = graphFor(statements);
|
||||
|
||||
expect(graph.nodes.length).toBeLessThanOrEqual(SEMANTIC_GRAPH_NODE_CEILING);
|
||||
expect(graph.coverage.truncated).toBe(true);
|
||||
expect(graph.coverage.status).toBe("partial");
|
||||
expect(graph.coverage.omitted_nodes).toBeNull();
|
||||
expect(graph.coverage.omitted_relations).toBeNull();
|
||||
expect(
|
||||
graph.coverage.families.every(
|
||||
({ omitted_relations }) => omitted_relations === null,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
graph.coverage.limits.some(
|
||||
({ name }) => name === "semantic_graph_node_ceiling",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves a small application complete and untruncated", () => {
|
||||
const graph = graphFor("const answer = 40 + 2;");
|
||||
expect(graph.coverage.truncated).toBe(false);
|
||||
expect(graph.coverage.omitted_nodes).toBe(0);
|
||||
expect(graph.coverage.omitted_relations).toBe(0);
|
||||
expect(graph.coverage.limits).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not mark a file truncated when it exactly fills its budget", () => {
|
||||
// Each unbound reference projects one expression, plus the module root.
|
||||
const graph = graphFor(
|
||||
"external;\n".repeat(SEMANTIC_GRAPH_FILE_NODE_CEILING - 1),
|
||||
);
|
||||
expect(graph.nodes).toHaveLength(SEMANTIC_GRAPH_FILE_NODE_CEILING);
|
||||
expect(graph.coverage).toMatchObject({
|
||||
truncated: false,
|
||||
omitted_nodes: 0,
|
||||
omitted_relations: 0,
|
||||
limits: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("only records node loss when the budget rejects a new identity", () => {
|
||||
// The truncation signal must record blocked node creation, not a zero
|
||||
// remaining budget: a file using exactly its share drops nothing.
|
||||
const state = createSemanticGraphProjectionState({ nodes: [] });
|
||||
state.fileNodeBudget = 2;
|
||||
state.fileNodesDropped = false;
|
||||
const first = addSemanticGraphNode(state, semanticNodeFor("first"));
|
||||
const second = addSemanticGraphNode(state, semanticNodeFor("second"));
|
||||
expect(first).not.toBeNull();
|
||||
expect(second).not.toBeNull();
|
||||
expect(state.fileNodeBudget).toBe(0);
|
||||
expect(state.fileNodesDropped).toBe(false);
|
||||
|
||||
expect(addSemanticGraphNode(state, semanticNodeFor("first"))).toBe(first);
|
||||
expect(state.fileNodesDropped).toBe(false);
|
||||
|
||||
const blocked = addSemanticGraphNode(state, semanticNodeFor("third"));
|
||||
expect(blocked).toBeNull();
|
||||
expect(state.fileNodesDropped).toBe(true);
|
||||
});
|
||||
|
||||
@@ -74,7 +74,35 @@ interface FileContext extends SemanticFlowProjectionContext {
|
||||
readonly callResolutions: ReadonlyMap<string, "candidate" | "resolved">;
|
||||
}
|
||||
|
||||
/** Project per-file semantic IR into an artifact-bound companion graph. */
|
||||
/**
|
||||
* Resource-safety ceiling on retained semantic nodes.
|
||||
*
|
||||
* The semantic projection emits one node per AST expression, call site, binding
|
||||
* and property slot. That is unbounded in input size. A small tree of five files
|
||||
* already yields on the order of 170,000 nodes, and larger trees yield millions,
|
||||
* exhausting the heap before the result can be serialized.
|
||||
*
|
||||
* This is a real resource-safety constraint, not a presentation preference, so
|
||||
* the ceiling is applied and reported through the graph's own `coverage` fields
|
||||
* (`truncated`, `omitted_nodes`, `omitted_relations`, `limits`) rather than
|
||||
* silently dropping data.
|
||||
*
|
||||
* Sizing: a retained semantic node costs roughly 3 KB once serialized, and V8
|
||||
* additionally caps a single string at 512 MB. The result is serialized after the
|
||||
* object graph is built and validated, so both phases must fit together. A single
|
||||
* minified vendor bundle can account for most of a tree's nodes, so a whole-tree
|
||||
* ceiling without a per-file ceiling does not bound the work. Both are applied.
|
||||
*/
|
||||
export const SEMANTIC_GRAPH_NODE_CEILING = 100_000;
|
||||
|
||||
/**
|
||||
* Per-file share of the semantic node budget.
|
||||
*
|
||||
* Bound each source file independently so one large bundled library cannot
|
||||
* consume the whole tree's budget and starve the application's own modules.
|
||||
*/
|
||||
export const SEMANTIC_GRAPH_FILE_NODE_CEILING = 20_000;
|
||||
|
||||
export const buildJavaScriptSemanticGraph = ({
|
||||
rootArtifactSha256,
|
||||
applicationGraph,
|
||||
@@ -82,11 +110,27 @@ export const buildJavaScriptSemanticGraph = ({
|
||||
}: BuilderInput): JavaScriptSemanticGraph => {
|
||||
const state = emptyState(applicationGraph);
|
||||
const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
|
||||
let truncatedFiles = 0;
|
||||
for (const analyzed of analysis.files) {
|
||||
if (analyzed.semantic === null) continue;
|
||||
if (state.nodes.size >= SEMANTIC_GRAPH_NODE_CEILING) {
|
||||
truncatedFiles += 1;
|
||||
continue;
|
||||
}
|
||||
const remainingTreeBudget = SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size;
|
||||
state.fileNodeBudget = Math.min(
|
||||
SEMANTIC_GRAPH_FILE_NODE_CEILING,
|
||||
remainingTreeBudget,
|
||||
);
|
||||
state.fileNodesDropped = false;
|
||||
fingerprints.push(
|
||||
...projectFile(analyzed.file, analyzed.semantic.ir, state),
|
||||
);
|
||||
// Nodes were dropped only if the budget actually blocked creation. A file
|
||||
// that exactly fills its share ends with a zero budget without dropping
|
||||
// anything, so the remaining budget alone cannot decide truncation.
|
||||
if (state.fileNodesDropped) truncatedFiles += 1;
|
||||
state.fileNodeBudget = null;
|
||||
}
|
||||
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
|
||||
const unknowns = [...state.unknowns.values()];
|
||||
@@ -100,11 +144,20 @@ export const buildJavaScriptSemanticGraph = ({
|
||||
fingerprints,
|
||||
unknowns,
|
||||
coverage: {
|
||||
status: "unknown",
|
||||
truncated: false,
|
||||
omitted_nodes: 0,
|
||||
omitted_relations: 0,
|
||||
limits: [],
|
||||
status: truncatedFiles > 0 ? "partial" : "unknown",
|
||||
truncated: truncatedFiles > 0,
|
||||
omitted_nodes: truncatedFiles > 0 ? null : 0,
|
||||
omitted_relations: truncatedFiles > 0 ? null : 0,
|
||||
limits:
|
||||
truncatedFiles > 0
|
||||
? [
|
||||
{
|
||||
name: "semantic_graph_node_ceiling",
|
||||
value: SEMANTIC_GRAPH_NODE_CEILING,
|
||||
unit: "items" as const,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
|
||||
family,
|
||||
status: semanticFamilyStatus(family, analysis),
|
||||
@@ -112,7 +165,7 @@ export const buildJavaScriptSemanticGraph = ({
|
||||
(relation) =>
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] === family,
|
||||
).length,
|
||||
omitted_relations: 0,
|
||||
omitted_relations: truncatedFiles > 0 ? null : 0,
|
||||
unknown_ids: unknowns
|
||||
.filter((unknown) => unknown.family === family)
|
||||
.map(({ unknown_id: identifier }) => identifier),
|
||||
|
||||
@@ -26,6 +26,24 @@ export interface SemanticGraphProjectionState {
|
||||
readonly unknowns: Map<string, JavaScriptSemanticGraphUnknown>;
|
||||
readonly roots: Set<string>;
|
||||
readonly applicationNodeIdsByLocation: ReadonlyMap<string, readonly string[]>;
|
||||
/**
|
||||
* Remaining node budget for the file currently being projected.
|
||||
*
|
||||
* The projection emits one node per AST expression, call site, binding and
|
||||
* property slot, which is unbounded in file size: one bundled vendor library
|
||||
* measured 135,286 nodes on its own. `null` means unbounded; a number is the
|
||||
* number of nodes this file may still add. Exhausting it stops node creation
|
||||
* for that file and is reported through the graph's `coverage` fields.
|
||||
*/
|
||||
fileNodeBudget?: number | null;
|
||||
/**
|
||||
* Whether the file currently being projected lost any nodes to its budget.
|
||||
*
|
||||
* A file that exactly fills its share ends with a zero budget without
|
||||
* dropping anything, so callers must consult this flag rather than the
|
||||
* remaining budget to decide whether coverage is truncated.
|
||||
*/
|
||||
fileNodesDropped?: boolean;
|
||||
}
|
||||
|
||||
/** Input for one exact artifact-version semantic node. */
|
||||
@@ -90,6 +108,14 @@ export const addSemanticGraphNode = (
|
||||
): JavaScriptSemanticGraphNode | null => {
|
||||
const existing = state.nodes.get(node.node_id);
|
||||
if (existing !== undefined) return existing;
|
||||
const budget = state.fileNodeBudget;
|
||||
if (typeof budget === "number") {
|
||||
if (budget <= 0) {
|
||||
state.fileNodesDropped = true;
|
||||
return null;
|
||||
}
|
||||
state.fileNodeBudget = budget - 1;
|
||||
}
|
||||
state.nodes.set(node.node_id, node);
|
||||
return node;
|
||||
};
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { createEvidence, parseEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { processTraceSpecificationSchema } from "../domain/processTraceComparison.js";
|
||||
import { processScenarioSchema } from "../domain/processScenario.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { createEvidence, parseEvidence } from "../../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { processTraceSpecificationSchema } from "../../domain/process/processTraceComparison.js";
|
||||
import { processScenarioSchema } from "../../domain/process/processScenario.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import { captureProcessScenario } from "./ProcessHarness.js";
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import { captureProcessScenario } from "../../process/capture/ProcessHarness.js";
|
||||
import {
|
||||
PROCESS_PROVIDER,
|
||||
createProcessCaptureEvidence,
|
||||
@@ -165,7 +165,11 @@ const readJson = async (path: string): Promise<unknown> => {
|
||||
);
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(bytes.toString("utf8"));
|
||||
const text = new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
ignoreBOM: true,
|
||||
}).decode(bytes);
|
||||
const parsed: unknown = JSON.parse(text);
|
||||
return parsed;
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
@@ -1,13 +1,13 @@
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { PROCESS_PROVIDER } from "../domain/processEvidenceProvider.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import type {
|
||||
ProcessCapture,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
} from "../../domain/process/processCapture.js";
|
||||
|
||||
export { PROCESS_PROVIDER } from "../domain/processEvidenceProvider.js";
|
||||
export { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
|
||||
|
||||
/** Project one process scenario into secret-free Evidence parameters. */
|
||||
const processEvidenceParameters = (
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { inspectBundleKeyedArchive } from "./apple/KeyedArchiveReader.js";
|
||||
import { basename, dirname } from "node:path";
|
||||
import { inventoryArtifact } from "../application/ArtifactInventory.js";
|
||||
import { extractArtifact } from "../application/ArtifactExtraction.js";
|
||||
import { inventoryArtifact } from "./inventory/ArtifactInventory.js";
|
||||
import { extractArtifact } from "./extraction/ArtifactExtraction.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "./apple/InterfaceBuilderAnalysis.js";
|
||||
import { analyzeAppleAssetCatalogs } from "./apple/AppleAssetCatalogAnalysis.js";
|
||||
import {
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
} from "./ArtifactProviderMetadata.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { createArtifactInspection } from "../domain/artifactInspection.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "../application/ArtifactInventory/policy.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "./inventory/policy.js";
|
||||
|
||||
/** Read-only inventory and exclusively owned extraction provider. */
|
||||
export class ArtifactProvider implements AnalysisProvider {
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { sep } from "node:path";
|
||||
import { constants, createReadStream, type Stats } from "node:fs";
|
||||
import { lstat, open, realpath, type FileHandle } from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { extractFile, listPackage, statFile, uncache } from "@electron/asar";
|
||||
import { getRawHeader, listPackage, statFile, uncache } from "@electron/asar";
|
||||
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
|
||||
|
||||
/**
|
||||
* Official Electron ASAR adapter. Individual files remain caller-bounded.
|
||||
* Official Electron ASAR adapter with range-streamed member reads.
|
||||
*
|
||||
* An entry marked `unpacked` is metadata, not an integrity exemption: Electron
|
||||
* stores its bytes beside the archive in `<archive>.unpacked`, and callers must
|
||||
@@ -19,17 +21,33 @@ import {
|
||||
*/
|
||||
export class AsarArtifactReader implements ArtifactReader {
|
||||
readonly format = "asar" as const;
|
||||
#archiveSize: number | undefined;
|
||||
#headerSize: number | undefined;
|
||||
readonly #entries = new Map<string, AsarEntryState>();
|
||||
|
||||
constructor(private readonly path: string) {}
|
||||
constructor(
|
||||
private readonly path: string,
|
||||
private readonly openUnpackedFile: OpenAsarUnpackedFile = open,
|
||||
) {}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
let paths: string[];
|
||||
try {
|
||||
// ASAR caches headers by path even after the archive has been replaced.
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
uncache(this.path);
|
||||
paths = listPackage(this.path, { isPack: false }).sort((left, right) =>
|
||||
left.localeCompare(right, "en"),
|
||||
);
|
||||
this.#headerSize = getRawHeader(this.path).headerSize;
|
||||
const archiveMetadata = await lstat(this.path);
|
||||
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"ASAR container is not a regular file",
|
||||
);
|
||||
this.#archiveSize = archiveMetadata.size;
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(this.path, "inventory", cause);
|
||||
}
|
||||
@@ -56,7 +74,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
: "link" in metadata
|
||||
? "symlink"
|
||||
: "file";
|
||||
yield {
|
||||
const entry: ArtifactEntry = {
|
||||
path,
|
||||
kind,
|
||||
declaredSize: "size" in metadata ? metadata.size : null,
|
||||
@@ -74,42 +92,121 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
limitations:
|
||||
kind === "symlink"
|
||||
? ["ASAR symlink target was not followed or disclosed."]
|
||||
: [
|
||||
"Official ASAR extraction buffers each individually bounded file.",
|
||||
],
|
||||
: [],
|
||||
adapterKey: providerPath,
|
||||
};
|
||||
if (kind === "file" && isAsarFileMetadata(metadata))
|
||||
this.#entries.set(providerPath, {
|
||||
metadata,
|
||||
entry: copyArtifactEntry(entry),
|
||||
});
|
||||
yield entry;
|
||||
}
|
||||
}
|
||||
|
||||
open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
|
||||
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
|
||||
abortIfNeeded(signal);
|
||||
if (entry.kind !== "file")
|
||||
return Promise.reject(
|
||||
new ArtifactReaderFailure("format", "ASAR entry is not a regular file"),
|
||||
const state = this.#entries.get(entry.adapterKey);
|
||||
if (state === undefined && entry.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"ASAR entry is not a regular file",
|
||||
);
|
||||
if (state === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry was not produced by this reader: ${entry.path}`,
|
||||
);
|
||||
if (!sameArtifactEntry(entry, state.entry))
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry metadata changed since inventory: ${state.entry.path}`,
|
||||
);
|
||||
const { metadata } = state;
|
||||
const producedEntry = state.entry;
|
||||
if (producedEntry.unpacked) {
|
||||
const handle = await this.#openUnpackedEntry(producedEntry);
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
abortIfNeeded(signal);
|
||||
if (!observed.isFile())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry is not a regular file: ${producedEntry.path}`,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw asarFailure(this.path, `read ${producedEntry.path}`, cause);
|
||||
}
|
||||
const source = handle.createReadStream({
|
||||
start: 0,
|
||||
autoClose: true,
|
||||
});
|
||||
return readValidatedAsarEntry(
|
||||
source,
|
||||
undefined,
|
||||
producedEntry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
const archiveSize = this.#archiveSize;
|
||||
const headerSize = this.#headerSize;
|
||||
const offset =
|
||||
metadata.offset === undefined
|
||||
? undefined
|
||||
: parseArchiveOffset(metadata.offset);
|
||||
const start =
|
||||
offset === undefined || headerSize === undefined
|
||||
? undefined
|
||||
: 8 + headerSize + offset;
|
||||
if (
|
||||
archiveSize === undefined ||
|
||||
start === undefined ||
|
||||
!Number.isSafeInteger(start) ||
|
||||
metadata.size < 0 ||
|
||||
!Number.isSafeInteger(metadata.size) ||
|
||||
start > archiveSize ||
|
||||
metadata.size > archiveSize - start
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`ASAR entry range is outside its container: ${producedEntry.path}`,
|
||||
);
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
return Promise.resolve(
|
||||
Readable.from(extractFile(this.path, entry.adapterKey, false)),
|
||||
const openedHandle = await open(
|
||||
this.path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
handle = openedHandle;
|
||||
const observed = await openedHandle.stat();
|
||||
abortIfNeeded(signal);
|
||||
if (!observed.isFile() || observed.size !== archiveSize)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before read: ${producedEntry.path}`,
|
||||
);
|
||||
if (metadata.size === 0) {
|
||||
await closeAsarHandle(() => openedHandle.close(), signal);
|
||||
handle = undefined;
|
||||
return Readable.from([]);
|
||||
}
|
||||
const source = openedHandle.createReadStream({
|
||||
start,
|
||||
end: start + metadata.size - 1,
|
||||
autoClose: true,
|
||||
});
|
||||
return readValidatedAsarEntry(
|
||||
source,
|
||||
metadata.size,
|
||||
producedEntry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (entry.unpacked && isMissingFile(cause))
|
||||
return Promise.reject(
|
||||
new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`ASAR unpacked entry bytes are unavailable: ${entry.path}`,
|
||||
{ cause },
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
),
|
||||
);
|
||||
return Promise.reject(
|
||||
asarFailure(this.path, `read ${entry.path}`, cause),
|
||||
);
|
||||
await handle?.close().catch(() => undefined);
|
||||
throw asarFailure(this.path, `read ${producedEntry.path}`, cause);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,14 +218,154 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
|
||||
close(): Promise<void> {
|
||||
uncache(this.path);
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
provenance(): readonly [] {
|
||||
return [];
|
||||
}
|
||||
|
||||
async #openUnpackedEntry(entry: ArtifactEntry): Promise<UnpackedFileHandle> {
|
||||
const unpackedRoot = `${this.path}.unpacked`;
|
||||
try {
|
||||
const rootMetadata = await lstat(unpackedRoot);
|
||||
if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"ASAR unpacked companion is not a regular directory",
|
||||
);
|
||||
const canonicalRoot = await realpath(unpackedRoot);
|
||||
const candidate = join(unpackedRoot, entry.adapterKey);
|
||||
const canonical = await realpath(candidate);
|
||||
const relativePath = relative(canonicalRoot, canonical);
|
||||
if (
|
||||
relativePath === ".." ||
|
||||
relativePath.startsWith(`..${sep}`) ||
|
||||
isAbsolute(relativePath)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry escaped its companion directory: ${entry.path}`,
|
||||
);
|
||||
const pathMetadata = await lstat(candidate);
|
||||
if (!pathMetadata.isFile() || pathMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry is not a regular file: ${entry.path}`,
|
||||
);
|
||||
const handle = await this.openUnpackedFile(
|
||||
canonical,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
const openedMetadata = await handle
|
||||
.stat()
|
||||
.catch(async (cause: unknown) => {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw cause;
|
||||
});
|
||||
if (
|
||||
!openedMetadata.isFile() ||
|
||||
openedMetadata.dev !== pathMetadata.dev ||
|
||||
openedMetadata.ino !== pathMetadata.ino
|
||||
) {
|
||||
await handle.close();
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR unpacked entry changed before read: ${entry.path}`,
|
||||
{},
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return handle;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
if (entry.unpacked && isMissingFile(cause))
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`ASAR unpacked entry bytes are unavailable: ${entry.path}`,
|
||||
{ cause },
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
);
|
||||
throw asarFailure(this.path, `read ${entry.path}`, cause);
|
||||
}
|
||||
}
|
||||
|
||||
#resetArchiveState(): void {
|
||||
this.#archiveSize = undefined;
|
||||
this.#headerSize = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
type AsarFileMetadata = Extract<ReturnType<typeof statFile>, { size: number }>;
|
||||
type AsarEntryState = {
|
||||
readonly metadata: AsarFileMetadata;
|
||||
readonly entry: ArtifactEntry;
|
||||
};
|
||||
type UnpackedFileHandle = {
|
||||
stat(): Promise<Stats>;
|
||||
close(): Promise<void>;
|
||||
createReadStream: FileHandle["createReadStream"];
|
||||
};
|
||||
type OpenAsarUnpackedFile = (
|
||||
path: string,
|
||||
flags: number,
|
||||
) => Promise<UnpackedFileHandle>;
|
||||
|
||||
const copyArtifactEntry = (entry: ArtifactEntry): ArtifactEntry => ({
|
||||
...entry,
|
||||
limitations: [...entry.limitations],
|
||||
...(entry.sourceIdentity === undefined
|
||||
? {}
|
||||
: { sourceIdentity: { ...entry.sourceIdentity } }),
|
||||
});
|
||||
|
||||
const sameArtifactEntry = (
|
||||
entry: ArtifactEntry,
|
||||
produced: ArtifactEntry,
|
||||
): boolean =>
|
||||
entry.path === produced.path &&
|
||||
entry.kind === produced.kind &&
|
||||
entry.declaredSize === produced.declaredSize &&
|
||||
entry.compressedSize === produced.compressedSize &&
|
||||
entry.executable === produced.executable &&
|
||||
entry.encrypted === produced.encrypted &&
|
||||
entry.byteOffset === produced.byteOffset &&
|
||||
entry.declaredSha256 === produced.declaredSha256 &&
|
||||
entry.unpacked === produced.unpacked &&
|
||||
entry.adapterKey === produced.adapterKey &&
|
||||
entry.limitations.length === produced.limitations.length &&
|
||||
entry.limitations.every(
|
||||
(limitation, index) => limitation === produced.limitations[index],
|
||||
) &&
|
||||
entry.sourceIdentity?.device === produced.sourceIdentity?.device &&
|
||||
entry.sourceIdentity?.inode === produced.sourceIdentity?.inode;
|
||||
|
||||
const isAsarFileMetadata = (
|
||||
metadata: ReturnType<typeof statFile>,
|
||||
): metadata is AsarFileMetadata =>
|
||||
"size" in metadata &&
|
||||
typeof metadata.size === "number" &&
|
||||
!("files" in metadata) &&
|
||||
!("link" in metadata);
|
||||
|
||||
const parseArchiveOffset = (value: string): number | undefined => {
|
||||
if (!/^(?:0|[1-9][0-9]*)$/u.test(value)) return undefined;
|
||||
const offset = Number(value);
|
||||
return Number.isSafeInteger(offset) ? offset : undefined;
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure("cancelled", "ASAR operation cancelled");
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
|
||||
/** Close an ASAR file handle before honoring cancellation of an empty member. */
|
||||
export const closeAsarHandle = async (
|
||||
close: () => Promise<void>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
await close();
|
||||
abortIfNeeded(signal);
|
||||
};
|
||||
|
||||
/** Validate and contextualize bytes read from one ASAR member source. */
|
||||
export const readValidatedAsarEntry = (
|
||||
source: Readable,
|
||||
expectedBytes: number | undefined,
|
||||
entryPath: string,
|
||||
archivePath: string,
|
||||
signal?: AbortSignal,
|
||||
): Readable => {
|
||||
const output = Readable.from(
|
||||
(async function* () {
|
||||
let observedBytes = 0;
|
||||
const iterator = source[Symbol.asyncIterator]();
|
||||
try {
|
||||
while (true) {
|
||||
abortIfNeeded(signal);
|
||||
const next = await iterator.next();
|
||||
if (next.done) break;
|
||||
const chunk: unknown = next.value;
|
||||
if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`ASAR entry did not return bytes: ${entryPath}`,
|
||||
);
|
||||
observedBytes += Buffer.isBuffer(chunk)
|
||||
? chunk.length
|
||||
: chunk.byteLength;
|
||||
if (expectedBytes !== undefined && observedBytes > expectedBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry exceeded its declared size: ${entryPath}`,
|
||||
);
|
||||
yield chunk;
|
||||
}
|
||||
if (expectedBytes !== undefined && observedBytes !== expectedBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry size disagrees with its header: ${entryPath}`,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
throw asarFailure(archivePath, `read ${entryPath}`, cause);
|
||||
} finally {
|
||||
try {
|
||||
await iterator.return?.();
|
||||
} catch {
|
||||
// Preserve the read failure; source destruction below owns cleanup.
|
||||
}
|
||||
if (!source.destroyed) source.destroy();
|
||||
}
|
||||
})(),
|
||||
);
|
||||
const closeSource = (): void => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
if (!source.destroyed) source.destroy();
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
closeSource();
|
||||
output.destroy(
|
||||
new ArtifactReaderFailure("cancelled", "ASAR operation cancelled"),
|
||||
);
|
||||
};
|
||||
output.once("close", closeSource);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
return output;
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure("cancelled", "ASAR operation cancelled");
|
||||
};
|
||||
|
||||
const asarFailure = (
|
||||
path: string,
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause;
|
||||
if (isFilesystemFailure(cause))
|
||||
return new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Could not ${operation} ASAR at ${path}: ${cause.message}`,
|
||||
{ cause },
|
||||
);
|
||||
return new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Malformed ASAR during ${operation}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const isFilesystemFailure = (
|
||||
cause: unknown,
|
||||
): cause is NodeJS.ErrnoException & Error =>
|
||||
cause instanceof Error &&
|
||||
"errno" in cause &&
|
||||
typeof cause.errno === "number" &&
|
||||
"syscall" in cause &&
|
||||
typeof cause.syscall === "string";
|
||||
@@ -13,34 +13,48 @@ import {
|
||||
export class DirectoryArtifactReader implements ArtifactReader {
|
||||
readonly format = "directory" as const;
|
||||
readonly #rootPromise: Promise<string>;
|
||||
readonly #rootPath: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.#rootPath = root;
|
||||
this.#rootPromise = realpath(root);
|
||||
}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
const root = await this.#rootPromise;
|
||||
const root = await this.#rootPromise.catch((cause: unknown) => {
|
||||
throw directoryIoFailure("resolve artifact root", this.#rootPath, cause);
|
||||
});
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
abortIfNeeded(signal);
|
||||
const directory = pending.pop();
|
||||
if (directory === undefined) break;
|
||||
await assertContainedDirectory(root, directory);
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory),
|
||||
);
|
||||
const children: string[] = [];
|
||||
const handle = await opendir(directory);
|
||||
const handle = await opendir(directory).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open directory", directory, cause);
|
||||
});
|
||||
try {
|
||||
for await (const child of handle) children.push(child.name);
|
||||
} catch (cause: unknown) {
|
||||
throw directoryIoFailure("read directory", directory, cause);
|
||||
} finally {
|
||||
// best-effort cleanup: directory-handle close must not mask traversal.
|
||||
await handle.close().catch(() => undefined);
|
||||
}
|
||||
await assertContainedDirectory(root, directory);
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory),
|
||||
);
|
||||
children.sort((left, right) => left.localeCompare(right, "en"));
|
||||
const directories: string[] = [];
|
||||
for (const name of children) {
|
||||
abortIfNeeded(signal);
|
||||
const absolute = join(directory, name);
|
||||
const metadata = await lstat(absolute);
|
||||
const metadata = await lstat(absolute).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("inspect entry", absolute, cause);
|
||||
});
|
||||
const path = relative(root, absolute).split(sep).join("/");
|
||||
const kind = metadata.isSymbolicLink()
|
||||
? "symlink"
|
||||
@@ -86,9 +100,17 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
const handle = await open(
|
||||
entry.adapterKey,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open entry", entry.adapterKey, cause);
|
||||
});
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
const observed = await handle.stat().catch((cause: unknown) => {
|
||||
throw directoryIoFailure(
|
||||
"inspect opened entry",
|
||||
entry.adapterKey,
|
||||
cause,
|
||||
);
|
||||
});
|
||||
if (
|
||||
!observed.isFile() ||
|
||||
entry.sourceIdentity === undefined ||
|
||||
@@ -117,6 +139,38 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
const directoryIoFailure = (
|
||||
operation: string,
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause;
|
||||
const code =
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "string"
|
||||
? ` (${cause.code})`
|
||||
: "";
|
||||
return new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Could not ${operation} at ${path}${code}`,
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const withDirectoryIoContext = async <T>(
|
||||
operation: string,
|
||||
path: string,
|
||||
action: () => Promise<T>,
|
||||
): Promise<T> => {
|
||||
try {
|
||||
return await action();
|
||||
} catch (cause: unknown) {
|
||||
throw directoryIoFailure(operation, path, cause);
|
||||
}
|
||||
};
|
||||
|
||||
const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
|
||||
@@ -37,13 +37,18 @@ export interface NativeDmgHost {
|
||||
arguments_: readonly string[],
|
||||
signal?: AbortSignal,
|
||||
options?: { readonly timeoutMs: number },
|
||||
): Promise<{ readonly stdout: string; readonly exitCode: number }>;
|
||||
): Promise<{
|
||||
readonly stdout: string;
|
||||
readonly stderr?: string;
|
||||
readonly exitCode: number;
|
||||
readonly cause?: unknown;
|
||||
}>;
|
||||
}
|
||||
|
||||
const systemHost: NativeDmgHost = {
|
||||
async run(arguments_, signal, options) {
|
||||
try {
|
||||
const { stdout } = await execFileOutput(
|
||||
const { stdout, stderr } = await execFileOutput(
|
||||
"/usr/bin/hdiutil",
|
||||
[...arguments_],
|
||||
{
|
||||
@@ -51,13 +56,23 @@ const systemHost: NativeDmgHost = {
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
},
|
||||
);
|
||||
return { stdout, exitCode: 0 };
|
||||
return { stdout, stderr, exitCode: 0 };
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && cause.name === "AbortError")
|
||||
throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled");
|
||||
throw new ArtifactReaderFailure("format", "hdiutil rejected the DMG", {
|
||||
cause,
|
||||
});
|
||||
const exitCode = processExitCode(cause);
|
||||
if (exitCode !== undefined)
|
||||
return {
|
||||
stdout: processOutput(cause, "stdout"),
|
||||
stderr: processOutput(cause, "stderr"),
|
||||
exitCode,
|
||||
cause,
|
||||
};
|
||||
throw new ArtifactReaderFailure(
|
||||
commandFailureReason(cause, arguments_[0]),
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(cause, arguments_)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -250,15 +265,157 @@ const runChecked = async (
|
||||
signal?: AbortSignal,
|
||||
options?: { readonly timeoutMs: number },
|
||||
): Promise<{ readonly stdout: string; readonly exitCode: 0 }> => {
|
||||
const result = await host.run(arguments_, signal, options);
|
||||
if (result.exitCode !== 0)
|
||||
let result: Awaited<ReturnType<NativeDmgHost["run"]>>;
|
||||
try {
|
||||
result = await host.run(arguments_, signal, options);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
if (cause instanceof Error && cause.name === "AbortError")
|
||||
throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled", {
|
||||
cause,
|
||||
});
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed with a non-zero exit code`,
|
||||
commandFailureReason(cause, arguments_[0]),
|
||||
`hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(
|
||||
cause,
|
||||
arguments_,
|
||||
)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
if (result.exitCode !== 0) {
|
||||
const failure = {
|
||||
command: "/usr/bin/hdiutil",
|
||||
exitCode: result.exitCode,
|
||||
...(result.cause === undefined
|
||||
? {}
|
||||
: { code: processExitCode(result.cause) }),
|
||||
stdout: result.stdout,
|
||||
...(result.stderr === undefined ? {} : { stderr: result.stderr }),
|
||||
};
|
||||
const reason = commandFailureReason(failure, arguments_[0]);
|
||||
const details = describeCommandFailure(failure, arguments_);
|
||||
const unknownVerifyFailure =
|
||||
arguments_[0] === "verify" && reason === "unavailable";
|
||||
throw new ArtifactReaderFailure(
|
||||
reason,
|
||||
unknownVerifyFailure
|
||||
? `hdiutil verify failed; captured diagnostics do not establish the failure cause: ${details}`
|
||||
: `hdiutil ${arguments_[0] ?? "operation"} failed: ${details}`,
|
||||
result.cause === undefined ? undefined : { cause: result.cause },
|
||||
);
|
||||
}
|
||||
return { stdout: result.stdout, exitCode: 0 };
|
||||
};
|
||||
|
||||
const describeCommandFailure = (
|
||||
cause: unknown,
|
||||
arguments_: readonly string[],
|
||||
): string => {
|
||||
const fields: Record<string, string | number | readonly string[]> = {
|
||||
command: "/usr/bin/hdiutil",
|
||||
arguments: [...arguments_],
|
||||
};
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
for (const key of [
|
||||
"code",
|
||||
"exitCode",
|
||||
"errno",
|
||||
"syscall",
|
||||
"signal",
|
||||
"stdout",
|
||||
"stderr",
|
||||
] as const) {
|
||||
const value = Reflect.get(cause, key);
|
||||
if (typeof value === "string" || typeof value === "number")
|
||||
fields[key] = value;
|
||||
}
|
||||
const code = Reflect.get(cause, "code");
|
||||
if (typeof code === "number") fields.exitCode = code;
|
||||
}
|
||||
if (cause instanceof ArtifactReaderFailure) fields.message = cause.message;
|
||||
else if (cause instanceof Error) fields.message = cause.message;
|
||||
return JSON.stringify(fields);
|
||||
};
|
||||
|
||||
const processExitCode = (cause: unknown): number | undefined => {
|
||||
if (typeof cause !== "object" || cause === null) return undefined;
|
||||
const exitCode = Reflect.get(cause, "exitCode");
|
||||
if (typeof exitCode === "number") return exitCode;
|
||||
const code = Reflect.get(cause, "code");
|
||||
return typeof code === "number" ? code : undefined;
|
||||
};
|
||||
|
||||
const processOutput = (cause: unknown, field: "stdout" | "stderr"): string => {
|
||||
if (typeof cause !== "object" || cause === null) return "";
|
||||
const value = Reflect.get(cause, field);
|
||||
return typeof value === "string" ? value : "";
|
||||
};
|
||||
|
||||
const commandFailureReason = (
|
||||
cause: unknown,
|
||||
operation: string | undefined,
|
||||
): ArtifactReaderFailure["reason"] => {
|
||||
if (typeof cause !== "object" || cause === null) return "unavailable";
|
||||
const code = Reflect.get(cause, "code");
|
||||
const exitCode = Reflect.get(cause, "exitCode");
|
||||
if (typeof code === "number" || typeof exitCode === "number")
|
||||
return operation === "verify" ? verifyFailureReason(cause) : "unavailable";
|
||||
if (code === "ENOENT") {
|
||||
const syscall = Reflect.get(cause, "syscall");
|
||||
return typeof syscall === "string" && syscall.startsWith("spawn")
|
||||
? "unavailable"
|
||||
: "io";
|
||||
}
|
||||
if (
|
||||
code === "EACCES" ||
|
||||
code === "EPERM" ||
|
||||
code === "EIO" ||
|
||||
code === "ENOTDIR" ||
|
||||
code === "EISDIR" ||
|
||||
code === "ENODEV" ||
|
||||
code === "EROFS" ||
|
||||
code === "EMFILE" ||
|
||||
code === "ENFILE"
|
||||
)
|
||||
return "io";
|
||||
return "unavailable";
|
||||
};
|
||||
|
||||
const verifyFailureReason = (
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure["reason"] => {
|
||||
const diagnostic = verifyFailureDiagnostic(
|
||||
processOutput(cause, "stdout"),
|
||||
processOutput(cause, "stderr"),
|
||||
);
|
||||
switch (diagnostic) {
|
||||
case "image not recognized":
|
||||
return "format";
|
||||
case "invalid checksum":
|
||||
case "image data corrupted":
|
||||
return "integrity";
|
||||
case "No such file or directory":
|
||||
case "Permission denied":
|
||||
case "Input/output error":
|
||||
return "io";
|
||||
default:
|
||||
return "unavailable";
|
||||
}
|
||||
};
|
||||
|
||||
const verifyFailureDiagnostic = (
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
): string | undefined => {
|
||||
const prefix = "hdiutil: verify failed - ";
|
||||
return `${stdout}\n${stderr}`
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.startsWith(prefix))
|
||||
?.slice(prefix.length);
|
||||
};
|
||||
|
||||
const command = (
|
||||
arguments_: readonly string[],
|
||||
effects: ArtifactCommand["effects"],
|
||||
|
||||
@@ -53,6 +53,9 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
this.#reader = new ZipReader(this.#source, {
|
||||
checkSignature: true,
|
||||
checkOverlappingEntry: true,
|
||||
// REA applies its own provider-neutral path validation in scanReader and
|
||||
// must preserve that typed failure instead of zip.js rejecting first.
|
||||
filenameValidation: "tolerant",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -1,29 +1,29 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
|
||||
import { canonicalDigest } from "../domain/comparisonSemantics.js";
|
||||
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../artifacts/ArtifactPaths.js";
|
||||
} from "../ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
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";
|
||||
} from "../ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { SafeOutputTree } from "../SafeOutputTree.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
type ArtifactExtractionResult,
|
||||
type ArtifactGraphManifest,
|
||||
type ArtifactNode,
|
||||
type ArtifactOccurrence,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { scanArtifactInventory } from "./ArtifactInventory.js";
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
|
||||
|
||||
/** Local extraction input with the output root chosen by the adapter. */
|
||||
export interface ArtifactExtractionInput {
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { compareDirectoryChildNames } from "./ArtifactGraphConstruction.js";
|
||||
|
||||
it("breaks locale-collation ties deterministically by code unit", () => {
|
||||
const names = ["a\u200d.txt", "a.txt", "a\u200b.txt", "a\u200c.txt"];
|
||||
expect("a\u200d.txt".localeCompare("a.txt")).toBe(0);
|
||||
expect(names.sort(compareDirectoryChildNames)).toEqual([
|
||||
"a.txt",
|
||||
"a\u200b.txt",
|
||||
"a\u200c.txt",
|
||||
"a\u200d.txt",
|
||||
]);
|
||||
});
|
||||
+5
-5
@@ -1,13 +1,13 @@
|
||||
import { canonicalDigest } from "../domain/comparisonSemantics.js";
|
||||
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import type { ArtifactEntry } from "../ArtifactReader.js";
|
||||
import type {
|
||||
ArtifactCommand,
|
||||
ArtifactEdge,
|
||||
ArtifactNode,
|
||||
ArtifactOccurrence,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import { zipPackageFormatForPath } from "../domain/zipPackageFormat.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../domain/dosMz.js";
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import { zipPackageFormatForPath } from "../../domain/zipPackageFormat.js";
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../../domain/dosMz.js";
|
||||
|
||||
/** Mutable internal occurrence used until root-bound IDs are known. */
|
||||
export interface MutableOccurrence {
|
||||
@@ -3,22 +3,22 @@ import { realpath } from "node:fs/promises";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import { abortIfNeeded } from "../artifacts/ArtifactHash.js";
|
||||
import { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
|
||||
} from "../../domain/artifactGraph.js";
|
||||
import { abortIfNeeded } from "../ArtifactHash.js";
|
||||
import { scanCanonicalArtifactInventory } from "./scanCanonical.js";
|
||||
import type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactInventoryOptions,
|
||||
ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory/types.js";
|
||||
} from "./types.js";
|
||||
|
||||
export { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
|
||||
export { scanCanonicalArtifactInventory } from "./scanCanonical.js";
|
||||
|
||||
export type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactInventoryOptions,
|
||||
ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory/types.js";
|
||||
} from "./types.js";
|
||||
|
||||
/** Inventory one local artifact and return every graph collection inline. */
|
||||
export const inventoryArtifact = async (
|
||||
@@ -1,7 +1,7 @@
|
||||
import { open } from "node:fs/promises";
|
||||
|
||||
import { classifyArtifactContent } from "../ArtifactGraphConstruction.js";
|
||||
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../../artifacts/ArtifactHash.js";
|
||||
import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";
|
||||
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
@@ -1,10 +1,10 @@
|
||||
import { AsarArtifactReader } from "../../artifacts/AsarArtifactReader.js";
|
||||
import type { ArtifactReader } from "../../artifacts/ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../../artifacts/DirectoryArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../../artifacts/MachOSliceArtifactReader.js";
|
||||
import { NativeDmgArtifactReader } from "../../artifacts/NativeDmgArtifactReader.js";
|
||||
import { XarArtifactReader } from "../../artifacts/XarArtifactReader.js";
|
||||
import { ZipArtifactReader } from "../../artifacts/ZipArtifactReader.js";
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import type { ArtifactReader } from "../ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
|
||||
import { XarArtifactReader } from "../XarArtifactReader.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
|
||||
export const createReader = async (
|
||||
+3
-3
@@ -5,7 +5,7 @@ import type { Stats } from "node:fs";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactReader,
|
||||
} from "../../artifacts/ArtifactReader.js";
|
||||
} from "../ArtifactReader.js";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
@@ -20,10 +20,10 @@ import {
|
||||
rekeyOccurrences,
|
||||
rootOccurrenceFor,
|
||||
type MutableOccurrence,
|
||||
} from "../ArtifactGraphConstruction.js";
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
|
||||
import { classifyRoot } from "./classify.js";
|
||||
import { hashReadable, type HashResult } from "../../artifacts/ArtifactHash.js";
|
||||
import { hashReadable, type HashResult } from "../ArtifactHash.js";
|
||||
import { createReader, inventoryLimitations } from "./reader.js";
|
||||
import {
|
||||
scanReader,
|
||||
+6
-6
@@ -3,14 +3,14 @@ import { isAbsolute } from "node:path";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../../artifacts/ArtifactPaths.js";
|
||||
} from "../ArtifactPaths.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "../../artifacts/ArtifactReader.js";
|
||||
import { AsarArtifactReader } from "../../artifacts/AsarArtifactReader.js";
|
||||
import { CpioArtifactReader } from "../../artifacts/CpioArtifactReader.js";
|
||||
} from "../ArtifactReader.js";
|
||||
import { AsarArtifactReader } from "../AsarArtifactReader.js";
|
||||
import { CpioArtifactReader } from "../CpioArtifactReader.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
import {
|
||||
classifyArtifactContent,
|
||||
@@ -18,12 +18,12 @@ import {
|
||||
createOccurrence,
|
||||
nearestParent,
|
||||
type MutableOccurrence,
|
||||
} from "../ArtifactGraphConstruction.js";
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
import {
|
||||
STRICT_INTEGRITY_POLICY,
|
||||
type ArtifactIntegrityPolicy,
|
||||
} from "./types.js";
|
||||
import { hashReadable } from "../../artifacts/ArtifactHash.js";
|
||||
import { hashReadable } from "../ArtifactHash.js";
|
||||
|
||||
export interface PendingIntegrityContradiction {
|
||||
readonly logicalPath: string;
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
open,
|
||||
rm,
|
||||
symlink,
|
||||
unlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, it } from "vitest";
|
||||
import { readStableArtifact } from "./readStableArtifact.js";
|
||||
|
||||
const checkChange = async (
|
||||
stage: "before-open" | "after-read" | "symlink-replacement",
|
||||
): Promise<void> => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-stable-read-"));
|
||||
const path = join(root, "selected");
|
||||
await writeFile(path, "original evidence");
|
||||
let inspected = 0;
|
||||
try {
|
||||
const reading = readStableArtifact(path, 1024, undefined, {
|
||||
async lstat(selected) {
|
||||
inspected++;
|
||||
if (stage === "after-read" && inspected === 2) await unlink(selected);
|
||||
const stat = await lstat(selected, { bigint: true });
|
||||
if (inspected === 1 && stage !== "after-read") {
|
||||
await unlink(selected);
|
||||
if (stage === "symlink-replacement")
|
||||
await symlink("missing", selected);
|
||||
}
|
||||
return stat;
|
||||
},
|
||||
open,
|
||||
});
|
||||
await expect(reading).rejects.toMatchObject({ reason: "integrity" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
it.each(["before-open", "after-read"] as const)(
|
||||
"retains an actual post-validation %s change as integrity failure",
|
||||
checkChange,
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains a post-validation symlink replacement as an integrity failure",
|
||||
() => checkChange("symlink-replacement"),
|
||||
);
|
||||
|
||||
it("keeps initially missing inputs distinguishable from later changes", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-stable-missing-"));
|
||||
try {
|
||||
await expect(
|
||||
readStableArtifact(join(root, "missing"), 1024),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,16 +1,50 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import { constants, type BigIntStats } from "node:fs";
|
||||
import { lstat, open, type FileHandle } from "node:fs/promises";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
|
||||
/** Filesystem boundary for stable reads, including deterministic replacement probes. */
|
||||
export interface StableArtifactFileSystem {
|
||||
lstat(path: string): Promise<BigIntStats>;
|
||||
open(path: string, flags: number): Promise<FileHandle>;
|
||||
}
|
||||
|
||||
const FILE_SYSTEM: StableArtifactFileSystem = {
|
||||
lstat: (path) => lstat(path, { bigint: true }),
|
||||
open,
|
||||
};
|
||||
|
||||
const afterValidation = async <T>(
|
||||
path: string,
|
||||
stage: string,
|
||||
read: () => Promise<T>,
|
||||
): Promise<T> => {
|
||||
try {
|
||||
return await read();
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code))
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact changed ${stage}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Read one bounded regular file and reject replacement or in-place changes. */
|
||||
export const readStableArtifact = async (
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
signal?: AbortSignal,
|
||||
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
|
||||
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
|
||||
signal?.throwIfAborted();
|
||||
const before = await lstat(path, { bigint: true });
|
||||
const before = await fileSystem.lstat(path);
|
||||
if (!before.isFile() || before.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
@@ -21,9 +55,11 @@ export const readStableArtifact = async (
|
||||
"limit",
|
||||
`Selected artifact exceeds ${String(maximumBytes)} bytes: ${path}`,
|
||||
);
|
||||
const file = await open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
const file = await afterValidation(path, "before open", () =>
|
||||
fileSystem.open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
),
|
||||
);
|
||||
try {
|
||||
const initial = await file.stat({ bigint: true });
|
||||
@@ -59,7 +95,9 @@ export const readStableArtifact = async (
|
||||
chunks.push(bytes);
|
||||
}
|
||||
const after = await file.stat({ bigint: true });
|
||||
const current = await lstat(path, { bigint: true });
|
||||
const current = await afterValidation(path, "during read", () =>
|
||||
fileSystem.lstat(path),
|
||||
);
|
||||
if (
|
||||
[after, current].some(
|
||||
(stat) =>
|
||||
|
||||
@@ -115,29 +115,6 @@ describe("DOM metadata document base URLs", () => {
|
||||
});
|
||||
|
||||
describe("empty form destinations with a document base URL", () => {
|
||||
it.each([
|
||||
{ nodeName: "FORM", attribute: "action" },
|
||||
{ nodeName: "BUTTON", attribute: "formaction" },
|
||||
{ nodeName: "INPUT", attribute: "formaction" },
|
||||
])(
|
||||
"resolves an empty $nodeName $attribute to the document",
|
||||
({ nodeName, attribute }) => {
|
||||
const pageUrl = `${documentUrl}?selected=fixture#section`;
|
||||
const baseUrl = `${origin}/assets/`;
|
||||
const value = snapshot(baseUrl, "/assets/", pageUrl, "");
|
||||
value.strings[6] = nodeName;
|
||||
value.strings[14] = attribute;
|
||||
value.strings[15] = "";
|
||||
const result = capture(value);
|
||||
expect(result.urls[3]).toMatchObject({
|
||||
attribute,
|
||||
url: pageUrl,
|
||||
destination_scope: "approved",
|
||||
});
|
||||
expect(result.urls[1]?.url).toBe(baseUrl);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an empty form action approved when the document base is foreign", () => {
|
||||
const foreign = "https://cdn.example.test/assets/";
|
||||
const value = snapshot(foreign, foreign);
|
||||
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
cdpStringValue,
|
||||
type UnknownRecord,
|
||||
} from "./CdpCaptureValues.js";
|
||||
import { requestBodyShape } from "./CdpCaptureEventBodyShapes.js";
|
||||
import {
|
||||
requestBodyShape,
|
||||
updateResponseBodyShape,
|
||||
} from "./CdpCaptureEventBodyShapes.js";
|
||||
import {
|
||||
consolePrimitive,
|
||||
decodeBase64,
|
||||
@@ -19,10 +22,11 @@ import {
|
||||
firstCallFrame,
|
||||
initiatorLocation,
|
||||
integerOrNull,
|
||||
isJsonMediaType,
|
||||
isMainFrameNavigation,
|
||||
} from "./CdpCaptureEventHelpers.js";
|
||||
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
|
||||
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
|
||||
import type { CapturedScript, NetworkState } from "./CdpCaptureEventTypes.js";
|
||||
|
||||
export const handleExecutionContextCreated = (
|
||||
state: CdpCaptureEventsState,
|
||||
@@ -120,9 +124,11 @@ export const handleRequestWillBeSent = (
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (state.malformedRedirectRequestIds.has(requestId)) return;
|
||||
if (request === undefined) {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
state.network.delete(requestId);
|
||||
state.networkRequestTimestamps.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const sanitized = allowedSanitizedUrl(request.url, state.allowedOrigins);
|
||||
@@ -132,8 +138,60 @@ export const handleRequestWillBeSent = (
|
||||
exclusionReasonForUrl(cdpStringValue(request.url)),
|
||||
);
|
||||
state.network.delete(requestId);
|
||||
state.networkRequestTimestamps.delete(requestId);
|
||||
return;
|
||||
}
|
||||
const previous = state.network.get(requestId);
|
||||
const redirectResponse = recordValue(params.redirectResponse);
|
||||
if (
|
||||
Object.hasOwn(params, "redirectResponse") &&
|
||||
redirectResponse === undefined &&
|
||||
preserveMalformedRedirectEvidence(state, requestId, previous)
|
||||
)
|
||||
return;
|
||||
const redirects = [...(previous?.redirects ?? [])];
|
||||
if (redirectResponse !== undefined) {
|
||||
const rawResponseUrl = cdpStringValue(redirectResponse.url);
|
||||
const responseUrl =
|
||||
rawResponseUrl === undefined || rawResponseUrl === ""
|
||||
? undefined
|
||||
: allowedSanitizedUrl(rawResponseUrl, state.allowedOrigins);
|
||||
const responseUrlReason = redirectResponseUrlReason(rawResponseUrl);
|
||||
if (previous === undefined) {
|
||||
if (responseUrl === undefined)
|
||||
state.completeness.exclude("network_requests", responseUrlReason);
|
||||
else
|
||||
// CDP may deliver the continuation after its predecessor was excluded
|
||||
// by origin policy or before capture began. Keep the final request but
|
||||
// report missing prior coverage without calling it malformed protocol.
|
||||
state.completeness.attachLimited("network_requests");
|
||||
} else if (responseUrl === undefined) {
|
||||
// redirectResponse belongs to the same request ID and can contain an
|
||||
// excluded origin. Drop the entire chain before retaining any details.
|
||||
state.completeness.exclude("network_requests", responseUrlReason);
|
||||
state.network.delete(requestId);
|
||||
state.networkRequestTimestamps.delete(requestId);
|
||||
return;
|
||||
} else {
|
||||
redirects.push({
|
||||
url: previous.url,
|
||||
response_url: responseUrl.url,
|
||||
method: previous.method,
|
||||
resource_type: previous.resource_type,
|
||||
status: numberValue(redirectResponse.status) ?? null,
|
||||
mime_type: cdpStringValue(redirectResponse.mimeType) ?? null,
|
||||
encoded_data_length: (() => {
|
||||
const length = numberValue(redirectResponse.encodedDataLength);
|
||||
return length === undefined ? null : Math.max(0, length);
|
||||
})(),
|
||||
request_timestamp:
|
||||
state.networkRequestTimestamps.get(requestId) ?? null,
|
||||
// CDP reports redirectResponse on the next requestWillBeSent event.
|
||||
// This is the event boundary, not a separately observed response time.
|
||||
redirect_event_timestamp: numberValue(params.timestamp) ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
const initiator = recordValue(params.initiator);
|
||||
const initiatorFrame = initiatorLocation(initiator);
|
||||
const rawInitiatorUrl = cdpStringValue(initiatorFrame?.url);
|
||||
@@ -155,6 +213,7 @@ export const handleRequestWillBeSent = (
|
||||
status: null,
|
||||
mime_type: null,
|
||||
encoded_data_length: null,
|
||||
redirects,
|
||||
initiator: {
|
||||
type: cdpStringValue(initiator?.type) ?? "other",
|
||||
url: initiatorUrl?.url ?? null,
|
||||
@@ -163,6 +222,44 @@ export const handleRequestWillBeSent = (
|
||||
},
|
||||
body_shapes: requestBodyShape(state, request),
|
||||
});
|
||||
const timestamp = numberValue(params.timestamp);
|
||||
if (timestamp === undefined) state.networkRequestTimestamps.delete(requestId);
|
||||
else state.networkRequestTimestamps.set(requestId, timestamp);
|
||||
};
|
||||
|
||||
const preserveMalformedRedirectEvidence = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
previous: NetworkState | undefined,
|
||||
): boolean => {
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
if (previous === undefined) return false;
|
||||
state.malformedRedirectRequestIds.add(requestId);
|
||||
if (
|
||||
state.input.include_json_body_shapes &&
|
||||
isJsonMediaType(previous.mime_type) &&
|
||||
previous.body_shapes.response === null
|
||||
) {
|
||||
updateResponseBodyShape(state, requestId, null);
|
||||
state.completeness.exclude("json_body_shapes", "invalid_protocol_value");
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const redirectResponseUrlReason = (
|
||||
value: string | undefined,
|
||||
):
|
||||
| "invalid_protocol_value"
|
||||
| "disallowed_origin"
|
||||
| "unsupported_url"
|
||||
| "unattributed_origin" => {
|
||||
if (value === undefined || value === "") return "invalid_protocol_value";
|
||||
try {
|
||||
new URL(value);
|
||||
} catch {
|
||||
return "invalid_protocol_value";
|
||||
}
|
||||
return exclusionReasonForUrl(value);
|
||||
};
|
||||
|
||||
export const handleResponseReceived = (
|
||||
@@ -174,6 +271,7 @@ export const handleResponseReceived = (
|
||||
state.completeness.exclude("network_requests", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (state.malformedRedirectRequestIds.has(requestId)) return;
|
||||
const current = state.network.get(requestId);
|
||||
const response = recordValue(params.response);
|
||||
if (current === undefined) return;
|
||||
@@ -186,6 +284,7 @@ export const handleResponseReceived = (
|
||||
: exclusionReasonForUrl(cdpStringValue(response.url)),
|
||||
);
|
||||
state.network.delete(requestId);
|
||||
state.networkRequestTimestamps.delete(requestId);
|
||||
return;
|
||||
}
|
||||
state.network.set(requestId, {
|
||||
@@ -209,6 +308,7 @@ export const handleLoadingFinished = (
|
||||
): void => {
|
||||
const requestId = cdpStringValue(params.requestId);
|
||||
if (requestId === undefined) return;
|
||||
if (state.malformedRedirectRequestIds.has(requestId)) return;
|
||||
const current = state.network.get(requestId);
|
||||
if (current === undefined) return;
|
||||
state.network.set(requestId, {
|
||||
|
||||
@@ -11,6 +11,8 @@ export interface CdpCaptureEventsState {
|
||||
readonly scripts: Map<string, CapturedScript>;
|
||||
readonly executionContextFrames: Map<string, string>;
|
||||
readonly network: Map<string, NetworkState>;
|
||||
readonly networkRequestTimestamps: Map<string, number>;
|
||||
readonly malformedRedirectRequestIds: Set<string>;
|
||||
readonly allowedWebSockets: Set<string>;
|
||||
console: WebPageInspection["console"]["events"];
|
||||
websockets: WebPageInspection["network"]["websocket_events"];
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
|
||||
|
||||
it("preserves an already captured response shape without marking it unavailable", () => {
|
||||
const origin = "http://127.0.0.1:43127";
|
||||
const events = new CdpCaptureEvents(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: origin,
|
||||
allowed_origins: [origin],
|
||||
target_id: "allowed-page",
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
new Set([origin]),
|
||||
);
|
||||
events.ingest({
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "request-1",
|
||||
request: {
|
||||
url: `${origin}/prior`,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
postData: '{"request":true}',
|
||||
},
|
||||
timestamp: 1,
|
||||
},
|
||||
});
|
||||
events.ingest({
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "request-1",
|
||||
response: {
|
||||
url: `${origin}/prior`,
|
||||
status: 200,
|
||||
mimeType: "application/json",
|
||||
},
|
||||
},
|
||||
});
|
||||
events.ingestResponseBody("request-1", {
|
||||
body: '{"response":true}',
|
||||
base64Encoded: false,
|
||||
});
|
||||
const capturedShape = events.network.get("request-1")?.body_shapes.response;
|
||||
expect(capturedShape).not.toBeNull();
|
||||
|
||||
events.ingest({
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "request-1",
|
||||
request: { url: `${origin}/continuation`, method: "GET" },
|
||||
redirectResponse: null,
|
||||
timestamp: 2,
|
||||
},
|
||||
});
|
||||
|
||||
expect(events.network.get("request-1")?.body_shapes.response).toEqual(
|
||||
capturedShape,
|
||||
);
|
||||
expect(events.network.get("request-1")?.body_shapes.status).toBe("included");
|
||||
expect(events.responseBodyRequestIds()).toEqual([]);
|
||||
expect(events.completeness.snapshot().unavailable_sections).not.toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,8 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
|
||||
readonly scripts = new Map<string, CapturedScript>();
|
||||
readonly executionContextFrames = new Map<string, string>();
|
||||
readonly network = new Map<string, NetworkState>();
|
||||
readonly networkRequestTimestamps = new Map<string, number>();
|
||||
readonly malformedRedirectRequestIds = new Set<string>();
|
||||
readonly allowedWebSockets = new Set<string>();
|
||||
console: WebPageInspection["console"]["events"] = [];
|
||||
websockets: WebPageInspection["network"]["websocket_events"] = [];
|
||||
@@ -51,6 +53,8 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
|
||||
this.scripts.clear();
|
||||
this.executionContextFrames.clear();
|
||||
this.network.clear();
|
||||
this.networkRequestTimestamps.clear();
|
||||
this.malformedRedirectRequestIds.clear();
|
||||
this.allowedWebSockets.clear();
|
||||
this.console.length = 0;
|
||||
this.websockets.length = 0;
|
||||
@@ -135,16 +139,21 @@ export class CdpCaptureEvents implements CdpCaptureEventsState {
|
||||
responseBodyRequestIds(): readonly string[] {
|
||||
if (!this.input.include_json_body_shapes) return [];
|
||||
return [...this.network.values()]
|
||||
.filter(
|
||||
(request) => !this.malformedRedirectRequestIds.has(request.request_id),
|
||||
)
|
||||
.filter((request) => isJsonMediaType(request.mime_type))
|
||||
.map((request) => request.request_id);
|
||||
}
|
||||
|
||||
responseBodyUnavailable(requestId: string): void {
|
||||
if (this.malformedRedirectRequestIds.has(requestId)) return;
|
||||
bodyShapes.updateResponseBodyShape(this, requestId, null);
|
||||
this.completeness.unavailable("json_body_shapes");
|
||||
}
|
||||
|
||||
ingestResponseBody(requestId: string, value: unknown): void {
|
||||
if (this.malformedRedirectRequestIds.has(requestId)) return;
|
||||
bodyShapes.ingestResponseBodyShape(this, requestId, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { safeResponseMetadata } from "./CdpSafeMetadata.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
describe("safe CDP response metadata", () => {
|
||||
it("drops credential headers and preserves complete local link URLs", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-1",
|
||||
`${origin}/api`,
|
||||
{
|
||||
mimeType: "application/json",
|
||||
headers: {
|
||||
Authorization: "Bearer credential-secret",
|
||||
Cookie: "session=cookie-secret",
|
||||
"Set-Cookie": "session=response-secret",
|
||||
Link: `</agent?token=link-secret>; rel="mcp service-desc"; title="a,b", <https://private.example.test/x>; rel="mcp"`,
|
||||
"Content-Security-Policy":
|
||||
"default-src 'self'; script-src 'nonce-nonce-secret' 'sha256-hash-secret' https://private.example.test",
|
||||
"Permissions-Policy":
|
||||
"camera=(), geolocation=(self), invalid secret=()",
|
||||
"X-Model-Context": "agent-header-secret",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response).toMatchObject({
|
||||
url: `${origin}/api`,
|
||||
csp: {
|
||||
nonce_count: 1,
|
||||
hash_count: 1,
|
||||
directives: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "script-src",
|
||||
sources: expect.arrayContaining([
|
||||
{ kind: "external_origin", value: null },
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
links: [
|
||||
{
|
||||
href: `${origin}/agent?token=link-secret`,
|
||||
destination_scope: "approved",
|
||||
rel: ["mcp", "service-desc"],
|
||||
as: null,
|
||||
type: null,
|
||||
crossorigin: null,
|
||||
},
|
||||
expect.objectContaining({
|
||||
href: "https://private.example.test/x",
|
||||
destination_scope: "outside_policy",
|
||||
}),
|
||||
],
|
||||
policies: { permissions_policy_features: ["camera", "geolocation"] },
|
||||
});
|
||||
expect(captured.agentHints).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ mechanism: "link_rel" }),
|
||||
expect.objectContaining({
|
||||
mechanism: "response_header",
|
||||
declaration: "x-model-context",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const serialized = JSON.stringify(captured);
|
||||
for (const secret of [
|
||||
"credential-secret",
|
||||
"cookie-secret",
|
||||
"response-secret",
|
||||
"nonce-secret",
|
||||
"hash-secret",
|
||||
"agent-header-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
expect(serialized).toContain("link-secret");
|
||||
expect(serialized).toContain("private.example.test/x");
|
||||
});
|
||||
|
||||
it("reports well-known agent resources as untrusted observations", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-2",
|
||||
`${origin}/.well-known/mcp?token=secret`,
|
||||
{ headers: {} },
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.agentHints).toEqual([
|
||||
{
|
||||
mechanism: "well_known_resource",
|
||||
declaration: "/.well-known/mcp",
|
||||
url: `${origin}/.well-known/mcp?token=secret`,
|
||||
trust: "page-declared-untrusted",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains every parsed header, CSP directive, link, relation, and policy feature", () => {
|
||||
const csp = Array.from(
|
||||
{ length: 105 },
|
||||
(_, index) => `x-${String(index)} 'self'`,
|
||||
).join("; ");
|
||||
const links = Array.from(
|
||||
{ length: 105 },
|
||||
(_, index) => `</${String(index)}>; rel="mcp service-desc"`,
|
||||
).join(", ");
|
||||
const permissions = Array.from(
|
||||
{ length: 205 },
|
||||
(_, index) => `feature-${String(index)}=()`,
|
||||
).join(", ");
|
||||
const headers = Object.fromEntries(
|
||||
Array.from({ length: 501 }, (_, index) => [
|
||||
`x-extra-${String(index)}`,
|
||||
"ok",
|
||||
]),
|
||||
);
|
||||
const captured = safeResponseMetadata(
|
||||
"request-1",
|
||||
`${origin}/api`,
|
||||
{
|
||||
mimeType: "application/json",
|
||||
headers: {
|
||||
...headers,
|
||||
"Content-Security-Policy": csp,
|
||||
Link: links,
|
||||
"Permissions-Policy": permissions,
|
||||
"X-Model-Context": "present-after-many-headers",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response.csp.directives).toHaveLength(105);
|
||||
expect(captured.response.links).toHaveLength(105);
|
||||
expect(captured.response.policies.permissions_policy_features).toHaveLength(
|
||||
205,
|
||||
);
|
||||
expect(captured.agentHints).toContainEqual(
|
||||
expect.objectContaining({ declaration: "x-model-context" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("safe CDP response metadata CSP sources", () => {
|
||||
it("classifies scheme-less CSP host sources by their own host, not the page origin", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-csp",
|
||||
`${origin}/api`,
|
||||
{
|
||||
headers: {
|
||||
"Content-Security-Policy":
|
||||
"script-src cdn.example.test *.trusted.test * 'self' https://api.other.test",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response.csp.directives).toEqual([
|
||||
{
|
||||
name: "script-src",
|
||||
sources: [
|
||||
{ kind: "external_origin", value: null },
|
||||
{ kind: "external_origin", value: null },
|
||||
{ kind: "external_origin", value: null },
|
||||
{ kind: "keyword", value: "'self'" },
|
||||
{ kind: "external_origin", value: null },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("inherits the protected resource scheme for a scheme-less host source", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-csp-scheme",
|
||||
`${origin}/api`,
|
||||
{
|
||||
headers: {
|
||||
"Content-Security-Policy":
|
||||
"script-src cdn.example.test app.example.test",
|
||||
},
|
||||
},
|
||||
new Set([origin, "https://cdn.example.test"]),
|
||||
);
|
||||
|
||||
expect(captured.response.csp.directives[0]?.sources).toEqual([
|
||||
{ kind: "approved_origin", value: "https://cdn.example.test" },
|
||||
{ kind: "approved_origin", value: origin },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Link header value delimiters", () => {
|
||||
const captureLinks = (link: string) =>
|
||||
safeResponseMetadata(
|
||||
"owned",
|
||||
"https://owned.test/page",
|
||||
{
|
||||
headers: { Link: link },
|
||||
},
|
||||
new Set(["https://owned.test"]),
|
||||
).response.links;
|
||||
|
||||
it("preserves commas in URI references and separates later links", () => {
|
||||
const links = captureLinks(
|
||||
'</assets/red,blue.js>; rel="preload"; as=script, </ordinary.js>; rel="modulepreload"',
|
||||
);
|
||||
expect(links.map(({ href }) => href)).toEqual([
|
||||
"https://owned.test/assets/red,blue.js",
|
||||
"https://owned.test/ordinary.js",
|
||||
]);
|
||||
expect(links[0]?.as).toBe("script");
|
||||
});
|
||||
|
||||
it("preserves semicolons and commas inside quoted parameter values", () => {
|
||||
const links = captureLinks(
|
||||
'</plugin.js>; rel="preload"; type="text/javascript; charset=utf-8"; title="a,b", </ordinary.js>; rel="modulepreload"',
|
||||
);
|
||||
expect(links).toHaveLength(2);
|
||||
expect(links[0]?.type).toBe("text/javascript; charset=utf-8");
|
||||
expect(links[1]?.href).toBe("https://owned.test/ordinary.js");
|
||||
});
|
||||
|
||||
it("counts quoted-pair escapes rather than treating every preceding slash as an escape", () => {
|
||||
const links = captureLinks(
|
||||
String.raw`</one.js>; title="ends with \\"; rel="preload", </two.js>; rel="modulepreload"`,
|
||||
);
|
||||
expect(links.map(({ href }) => href)).toEqual([
|
||||
"https://owned.test/one.js",
|
||||
"https://owned.test/two.js",
|
||||
]);
|
||||
expect(links[0]?.rel).toEqual(["preload"]);
|
||||
});
|
||||
|
||||
it("keeps a quoted escaped quote from exposing a delimiter", () => {
|
||||
const links = captureLinks(
|
||||
String.raw`</one.js>; title="quoted \" comma, value"; rel="preload", </two.js>; rel="modulepreload"`,
|
||||
);
|
||||
expect(links).toHaveLength(2);
|
||||
expect(links[0]?.rel).toEqual(["preload"]);
|
||||
});
|
||||
|
||||
it("retains the existing outside-policy classification", () => {
|
||||
const links = captureLinks(
|
||||
'<https://elsewhere.test/red,blue.js>; rel="preload", </ordinary.js>; rel="modulepreload"',
|
||||
);
|
||||
expect(links[0]?.destination_scope).toBe("outside_policy");
|
||||
expect(links[1]?.destination_scope).toBe("approved");
|
||||
});
|
||||
});
|
||||
describe("safe CDP response metadata referrer policy", () => {
|
||||
it.each<[string | undefined, string | null]>([
|
||||
[
|
||||
"no-referrer, strict-origin-when-cross-origin",
|
||||
"strict-origin-when-cross-origin",
|
||||
],
|
||||
["origin, future-policy", "origin"],
|
||||
["future-policy, no-referrer", "no-referrer"],
|
||||
["unsafe-url, NO-REFERRER", "no-referrer"],
|
||||
["origin,, no-referrer", "no-referrer"],
|
||||
["future-policy", null],
|
||||
['unsafe-url, "no-referrer"', null],
|
||||
["no-referrer; report-to=x, origin", null],
|
||||
["", null],
|
||||
[undefined, null],
|
||||
...[
|
||||
"no-referrer",
|
||||
"no-referrer-when-downgrade",
|
||||
"same-origin",
|
||||
"origin",
|
||||
"strict-origin",
|
||||
"origin-when-cross-origin",
|
||||
"strict-origin-when-cross-origin",
|
||||
"unsafe-url",
|
||||
].map((policy): [string, string] => [policy, policy]),
|
||||
])("normalizes declared Referrer-Policy %s", (raw, expected) => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-referrer",
|
||||
`${origin}/api`,
|
||||
{
|
||||
headers: {
|
||||
"Referrer-Policy": raw,
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
expect(captured.response.policies.referrer_policy).toBe(expected);
|
||||
expect(captured.response.policies.coop).toBe("same-origin");
|
||||
});
|
||||
});
|
||||
@@ -27,7 +27,11 @@ import {
|
||||
type ProcessCleanupResult,
|
||||
type ProcessLineageObservation,
|
||||
} from "../process/ProcessOwnership.js";
|
||||
import { observeOwnedProcessLineage } from "../process/ProcessOwnershipObservation.js";
|
||||
import {
|
||||
observeOwnedProcessLineage,
|
||||
prepareProcessOwnershipInspection,
|
||||
systemProcessOwnershipHost,
|
||||
} from "../process/ProcessOwnershipObservation.js";
|
||||
import { selectCapturedProcessGroupIds } from "../process/ProcessOwnershipProcessTree.js";
|
||||
import {
|
||||
runElectronActions,
|
||||
@@ -157,8 +161,13 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
try {
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
await prepareProcessOwnershipInspection(options.signal);
|
||||
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
|
||||
const paths = await canonicalPaths(input);
|
||||
const captureBaseline =
|
||||
await systemProcessOwnershipHost.captureBaseline?.(options.signal);
|
||||
if (options.signal?.aborted)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
application = await electron.launch({
|
||||
executablePath: paths.executable,
|
||||
cwd: paths.root,
|
||||
@@ -183,6 +192,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
expectedParentPid: process.pid,
|
||||
expectedCommand: paths.executable,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
...(captureBaseline === undefined ? {} : { captureBaseline }),
|
||||
};
|
||||
const actions = await runElectronActions(application, input, options);
|
||||
const state = await runWithExecutionLimits(
|
||||
@@ -191,7 +201,13 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
);
|
||||
outcome = ok(createResult(paths, input, actions, state));
|
||||
} catch (cause: unknown) {
|
||||
outcome = err(providerError(cause));
|
||||
outcome = err(
|
||||
options.signal?.aborted === true &&
|
||||
(cause === options.signal.reason ||
|
||||
(cause instanceof Error && cause.name === "AbortError"))
|
||||
? new BrowserObservationError(OPERATION, "cancelled", { cause })
|
||||
: providerError(cause),
|
||||
);
|
||||
}
|
||||
if (application !== undefined) {
|
||||
if (ownership !== undefined)
|
||||
@@ -277,7 +293,11 @@ const cleanupElectronProcesses = async (
|
||||
if (!result.cleaned) return result;
|
||||
signaled ||= result.signaled;
|
||||
}
|
||||
const remaining = await verifyNoTokenOwnedProcesses(ownership.runId);
|
||||
const remaining = await verifyNoTokenOwnedProcesses(
|
||||
ownership.runId,
|
||||
undefined,
|
||||
ownership.captureBaseline,
|
||||
);
|
||||
if (!remaining.cleaned) return remaining;
|
||||
return { cleaned: true, signaled };
|
||||
};
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import type { Page } from "playwright-core";
|
||||
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { performPlaywrightScenarioAction } from "./PlaywrightScenarioActions.js";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
|
||||
it("uses exact accessible-name matching without a caller confirmation field", async () => {
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
browser: { mode: "launch", executable_path: "chrome" },
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
actions: [
|
||||
{
|
||||
step_id: "submit",
|
||||
action: "click",
|
||||
locator: { kind: "role", role: "button", name: "Submit" },
|
||||
},
|
||||
],
|
||||
});
|
||||
const calls: unknown[][] = [];
|
||||
const page = {
|
||||
getByRole: (...args: unknown[]) => {
|
||||
calls.push(args);
|
||||
return { click: async () => undefined };
|
||||
},
|
||||
} as unknown as Page;
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
|
||||
if (secrets === undefined) throw new Error("No secret declarations expected");
|
||||
const action = scenario.actions.at(0);
|
||||
if (action === undefined) throw new Error("Expected one scenario action");
|
||||
|
||||
await performPlaywrightScenarioAction({
|
||||
page,
|
||||
action,
|
||||
secrets,
|
||||
});
|
||||
|
||||
expect(calls).toEqual([["button", { name: "Submit", exact: true }]]);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
|
||||
import { inspectWebNetworkCaptureInputSchema } from "../../domain/webNetworkCapture.js";
|
||||
import { historicalCaptureFailure } from "./CaptureFailures.js";
|
||||
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
|
||||
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
|
||||
|
||||
it.each(["before open", "during read"])(
|
||||
"preserves observed capture changes %s as retryable acquisition integrity failures",
|
||||
(stage) => {
|
||||
const path = "/selected/private-marker.har";
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
});
|
||||
const cause = new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact changed ${stage}: ${path}`,
|
||||
);
|
||||
const error = historicalCaptureFailure(input, cause, "capture-read");
|
||||
const projected = projectAnalysisError(error);
|
||||
expect(analysisErrorProjectionSchema.parse(projected)).toMatchObject({
|
||||
code: "artifact_changed",
|
||||
category: "integrity_mismatch",
|
||||
retryable: true,
|
||||
details: {
|
||||
operation: "inspect_web_network_capture",
|
||||
path,
|
||||
boundary: "stable-artifact-read",
|
||||
reason: cause.message,
|
||||
},
|
||||
});
|
||||
expect(projected.remediation.action).toContain("stable");
|
||||
const redacted = projectAnalysisError(
|
||||
redactExplicitFailure(error, ["private-marker", "REDACTED"]),
|
||||
);
|
||||
expect(redacted.code).toBe("artifact_changed");
|
||||
expect(JSON.stringify(redacted)).not.toContain("private-marker");
|
||||
expect(JSON.stringify(redacted)).not.toContain("REDACTED");
|
||||
},
|
||||
);
|
||||
|
||||
it("retains actual command status and both diagnostic streams when cleanup also fails", () => {
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: "/selected/input.har",
|
||||
format: "har",
|
||||
});
|
||||
const cause = new OwnedCommandFailure(
|
||||
"process",
|
||||
"Observed command failure",
|
||||
{
|
||||
stdout: { text: "original provider output", bytes: 24 },
|
||||
stderr: { text: "private-marker provider reason", bytes: 30 },
|
||||
exitCode: 2,
|
||||
signal: null,
|
||||
},
|
||||
"Observed cleanup failure",
|
||||
undefined,
|
||||
["pid:42"],
|
||||
);
|
||||
const error = historicalCaptureFailure(input, cause, "decoder");
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
previous_error: {
|
||||
failure_kind: "process",
|
||||
exit_code: 2,
|
||||
stdout: "original provider output",
|
||||
stderr: "private-marker provider reason",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const redacted = projectAnalysisError(
|
||||
redactExplicitFailure(error, ["private-marker"]),
|
||||
);
|
||||
expect(JSON.stringify(redacted)).not.toContain("private-marker");
|
||||
expect(redacted.code).toBe("cleanup_incomplete");
|
||||
});
|
||||
it.each(["io", "unavailable"] as const)(
|
||||
"keeps %s read failures separate from malformed capture input",
|
||||
(reason) => {
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: "/selected/input.har",
|
||||
format: "har",
|
||||
});
|
||||
const error = historicalCaptureFailure(
|
||||
input,
|
||||
new ArtifactReaderFailure(reason, "Observed acquisition failure"),
|
||||
"capture-read",
|
||||
);
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
category: "execution_failure",
|
||||
details: { diagnostics: { phase: "capture-read", failure_kind: reason } },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
type InspectWebNetworkCaptureInput,
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
/** Preserve the origin and typed cause of a historical capture failure. */
|
||||
export const historicalCaptureFailure = (
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
cause: unknown,
|
||||
phase: "capture-read" | "decoder",
|
||||
options?: ExecutionOptions,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof OwnedCommandFailure) {
|
||||
if (cause.cleanupFailure !== null)
|
||||
return new ProviderCleanupError(
|
||||
input.format,
|
||||
cause.resources,
|
||||
{
|
||||
reason: cause.cleanupFailure,
|
||||
previous_error: {
|
||||
failure_kind: cause.reason,
|
||||
message: cause.message,
|
||||
exit_code: cause.snapshot?.exitCode ?? null,
|
||||
signal: cause.snapshot?.signal ?? null,
|
||||
stdout: cause.snapshot?.stdout.text ?? null,
|
||||
stderr: cause.snapshot?.stderr.text ?? null,
|
||||
diagnostic_truncated: cause.snapshot?.diagnosticTruncated ?? null,
|
||||
},
|
||||
},
|
||||
{ operation: OPERATION, cause },
|
||||
);
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError(OPERATION);
|
||||
if (cause.reason === "timeout")
|
||||
return new AnalysisTimeoutError(
|
||||
OPERATION,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.timeoutMs,
|
||||
);
|
||||
if (cause.reason === "output-limit")
|
||||
return new AnalysisOutputError(OPERATION, cause.message);
|
||||
}
|
||||
if (options?.signal?.aborted) return new AnalysisCancelledError(OPERATION);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "integrity"
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
input.capture_path,
|
||||
cause.message,
|
||||
{ cause },
|
||||
);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "cancelled"
|
||||
)
|
||||
return new AnalysisCancelledError(OPERATION);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
(cause.reason === "limit" ||
|
||||
cause.reason === "format" ||
|
||||
cause.reason === "path")
|
||||
)
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
|
||||
message:
|
||||
cause.reason === "limit"
|
||||
? `${cause.message}. Select a capture within the ${WEB_NETWORK_CAPTURE_LIMITS.inputBytes}-byte input budget.`
|
||||
: cause.message,
|
||||
...(cause.reason === "limit"
|
||||
? {
|
||||
expected: {
|
||||
maximum_capture_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
]);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(
|
||||
OPERATION,
|
||||
input.capture_path,
|
||||
cause.code,
|
||||
{ cause },
|
||||
);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
["ENOENT", "ENOTDIR"].includes(String(cause.code))
|
||||
)
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: "invalid_value",
|
||||
message: `Selected capture could not be read (${String(cause.code)}): ${input.capture_path}.`,
|
||||
},
|
||||
]);
|
||||
return new ProviderAdapterError(input.format, OPERATION, {
|
||||
cause,
|
||||
diagnostics: {
|
||||
phase,
|
||||
capture_path: input.capture_path,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
...(cause instanceof ArtifactReaderFailure
|
||||
? { failure_kind: cause.reason }
|
||||
: {}),
|
||||
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
|
||||
? {
|
||||
exit_code: cause.snapshot.exitCode ?? null,
|
||||
signal: cause.snapshot.signal ?? null,
|
||||
stdout: cause.snapshot.stdout.text,
|
||||
stderr: cause.snapshot.stderr.text,
|
||||
diagnostic_truncated: cause.snapshot.diagnosticTruncated ?? false,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Expected malformed, unsupported or oversized producer data at a historical decoder boundary. */
|
||||
export class CaptureFormatError extends Error {
|
||||
constructor(
|
||||
readonly reason: "format" | "unsupported" | "input-limit",
|
||||
message: string,
|
||||
readonly pointer = "",
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { CaptureRedaction } from "./CaptureRedaction.js";
|
||||
|
||||
it.each([
|
||||
{
|
||||
value: " https://user:password@example.test/path ",
|
||||
expected: " https://example.test/path ",
|
||||
},
|
||||
{
|
||||
value: "\tHTTPS://user:password@example.test/path\t",
|
||||
expected: "\tHTTPS://example.test/path\t",
|
||||
},
|
||||
{
|
||||
value: " \t//user:password@example.test/path?token=ordinary#fragment\t ",
|
||||
expected: " \t//example.test/path?token=ordinary#fragment\t ",
|
||||
},
|
||||
{
|
||||
value: "\r\n \v\fhttps://user:password@example.test/path",
|
||||
expected: "\r\n \v\fhttps://example.test/path",
|
||||
},
|
||||
{
|
||||
value: "\u0000\u001f//user:password@example.test/path",
|
||||
expected: "\u0000\u001f//example.test/path",
|
||||
},
|
||||
])(
|
||||
"excludes URL userinfo after optional whitespace while preserving the original header text: $value",
|
||||
({ value, expected }) => {
|
||||
const redactor = new CaptureRedaction([]);
|
||||
expect(redactor.text(value, "/response/headers/0/value", true)).toBe(
|
||||
expected,
|
||||
);
|
||||
expect(redactor.redactions).toEqual([
|
||||
{ pointer: "/response/headers/0/value", reason: "transport-credential" },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the same URL-looking text in an ordinary extension", () => {
|
||||
const redactor = new CaptureRedaction([]);
|
||||
const value = " \thttps://user:password@example.test/path\t ";
|
||||
expect(redactor.text(value, "/_extension")).toBe(value);
|
||||
expect(redactor.redactions).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["\ud800", "\udfff"])(
|
||||
"does not invent replacement UTF-8 bytes for a non-scalar declaration",
|
||||
(literal) => {
|
||||
const redactor = new CaptureRedaction([literal]);
|
||||
expect(redactor.sensitiveBytes(Buffer.from("\ufffd"))).toBe(false);
|
||||
expect(redactor.text(literal, "/reported")).toBe(null);
|
||||
},
|
||||
);
|
||||
|
||||
it("matches scalar UTF-8 declarations and complete surrogate pairs exactly", () => {
|
||||
expect(
|
||||
new CaptureRedaction(["\ufffd"]).sensitiveBytes(Buffer.from("\ufffd")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
new CaptureRedaction(["\ud83d\ude00"]).sensitiveBytes(Buffer.from("😀")),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { WebNetworkCaptureRecord } from "../../domain/webNetworkCapture.js";
|
||||
|
||||
type Redaction = WebNetworkCaptureRecord["redactions"][number];
|
||||
const CREDENTIAL_HEADERS = new Set([
|
||||
"authorization",
|
||||
"proxy-authorization",
|
||||
"cookie",
|
||||
"set-cookie",
|
||||
]);
|
||||
|
||||
/** Literal redaction and structural authentication exclusions preserve unrelated local evidence. */
|
||||
export class CaptureRedaction {
|
||||
readonly redactions: Redaction[] = [];
|
||||
readonly #sensitiveByteValues: readonly Buffer[];
|
||||
constructor(readonly sensitiveValues: readonly string[]) {
|
||||
// An unpaired surrogate has no UTF-8 representation. Buffer.from would
|
||||
// invent replacement-character bytes and incorrectly discard real evidence.
|
||||
this.#sensitiveByteValues = sensitiveValues.flatMap((value) => {
|
||||
const encoded = Buffer.from(value, "utf8");
|
||||
return encoded.toString("utf8") === value ? [encoded] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Preserve exact text unless explicitly sensitive or known transport URL userinfo. */
|
||||
text(value: string, pointer: string, transportUrl = false): string | null {
|
||||
let result = value;
|
||||
if (transportUrl) {
|
||||
const match =
|
||||
/^([\x00-\x20]*(?:[a-z][a-z0-9+.-]*:)?\/\/)([^/?#]*@)/i.exec(result);
|
||||
if (match !== null) {
|
||||
result = `${match[1]}${result.slice(match[0].length)}`;
|
||||
this.redactions.push({ pointer, reason: "transport-credential" });
|
||||
}
|
||||
}
|
||||
if (
|
||||
this.sensitiveValues.some(
|
||||
(literal) => value.includes(literal) || result.includes(literal),
|
||||
)
|
||||
) {
|
||||
this.redactions.push({ pointer, reason: "explicit-sensitive-value" });
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Remove a credential field's value without retaining its digest or encoded form. */
|
||||
credential(pointer: string): null {
|
||||
this.redactions.push({ pointer, reason: "transport-credential" });
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Known HAR credential surfaces; unknown extensions are ordinary caller-selected evidence. */
|
||||
harCredential(
|
||||
pointer: string,
|
||||
parent: Readonly<Record<string, unknown>>,
|
||||
): boolean {
|
||||
return (
|
||||
(/^\/(request|response)\/headers\/\d+\/value$/.test(pointer) &&
|
||||
typeof parent.name === "string" &&
|
||||
CREDENTIAL_HEADERS.has(parent.name.toLowerCase())) ||
|
||||
/^\/(request|response)\/cookies\/\d+\/value$/.test(pointer)
|
||||
);
|
||||
}
|
||||
|
||||
/** Only actual request/redirect fields and known transport header URLs declare URL semantics. */
|
||||
harTransportUrl(
|
||||
pointer: string,
|
||||
parent?: Readonly<Record<string, unknown>>,
|
||||
): boolean {
|
||||
return (
|
||||
pointer === "/request/url" ||
|
||||
pointer === "/response/redirectURL" ||
|
||||
(/^\/(request|response)\/headers\/\d+\/value$/.test(pointer) &&
|
||||
typeof parent?.name === "string" &&
|
||||
["location", "referer", "origin"].includes(parent.name.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
/** Preserve bytes unless an explicitly declared UTF-8 literal occurs in them. */
|
||||
sensitiveBytes(bytes: Buffer): boolean {
|
||||
return this.#sensitiveByteValues.some((value) => bytes.includes(value));
|
||||
}
|
||||
}
|
||||
|
||||
/** Escape a producer property for an RFC 6901 location. */
|
||||
export const capturePointer = (parent: string, key: string): string =>
|
||||
`${parent}/${key.replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
||||
|
||||
/** Structural record guard does not duck-type number/byte sidecar markers. */
|
||||
export const captureObject = (
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Exact upstream package profile for unchanged offline HAR validation and numeric parsing. */
|
||||
export const HAR_CAPTURE_PROVIDER_IDENTITY = {
|
||||
id: "har-schema/lossless-json",
|
||||
name: "REA HAR capture adapter",
|
||||
version: "har-schema@2.0.0;jsonc-parser@3.3.1;lossless-json@4.3.1",
|
||||
} as const;
|
||||
|
||||
/** Native executable profile verified with unchanged mitmproxy raw-state decoding. */
|
||||
export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
|
||||
id: "mitmproxy-native-tnetstring",
|
||||
name: "REA offline native mitmproxy adapter",
|
||||
version: "12.2.3",
|
||||
} as const;
|
||||
@@ -0,0 +1,546 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { historicalHar } from "../../../tests/fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "./HarCapture.js";
|
||||
|
||||
it.each([
|
||||
{ values: [] },
|
||||
{ values: ["response"] },
|
||||
{ values: ["content"] },
|
||||
{ values: ["log"] },
|
||||
{ values: ["entries"] },
|
||||
])(
|
||||
"validates canonical base64 even when its parent property is sensitive: %j",
|
||||
({ values }) => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const input = {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
response: {
|
||||
...first.response,
|
||||
content: {
|
||||
size: 1,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "AR==",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(() => decodeHarCapture(JSON.stringify(input), values)).toThrow(
|
||||
"not valid canonical base64",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["log", "entries", "ntries"])(
|
||||
"excludes extracted record payloads beneath the marked structural property %s",
|
||||
(literal) => {
|
||||
const decoded = decodeHarCapture(JSON.stringify(historicalHar()), [
|
||||
literal,
|
||||
]);
|
||||
expect(decoded.total_records).toBeGreaterThan(0);
|
||||
expect(decoded.container.records_pointer).toBe(null);
|
||||
for (const [ordinal, record] of decoded.records.entries()) {
|
||||
expect(record).toMatchObject({
|
||||
ordinal,
|
||||
location: { kind: "unknown", reason: "explicit-sensitive-value" },
|
||||
reported: null,
|
||||
binary_fields: [],
|
||||
numeric_literals: [],
|
||||
redactions: [{ pointer: "", reason: "explicit-sensitive-value" }],
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes sensitive property identities before emitting keys and sidecar coordinates", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
...fixture,
|
||||
_extension: {
|
||||
"api-secret/~": { numeric: 123, text: "api-secret" },
|
||||
kept: 7,
|
||||
},
|
||||
log: { ...fixture.log, entries: [{ ...first, "api-secret": 42 }] },
|
||||
}),
|
||||
["api-secret"],
|
||||
);
|
||||
expect(JSON.stringify(result)).not.toContain("api-secret");
|
||||
expect(result.container.reported).toMatchObject({ _extension: { kept: 7 } });
|
||||
expect(result.container.redactions).toContainEqual({
|
||||
pointer: "/_extension",
|
||||
reason: "explicit-sensitive-value",
|
||||
scope: "property-name",
|
||||
});
|
||||
expect(result.records[0]?.redactions).toContainEqual({
|
||||
pointer: "",
|
||||
reason: "explicit-sensitive-value",
|
||||
scope: "property-name",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ value: "REDACTED", sensitive: ["REDACTED"] },
|
||||
{ value: "literal[", sensitive: ["["] },
|
||||
{ value: "before secret after", sensitive: ["secret", "REDACTED"] },
|
||||
{ value: "before secret after", sensitive: ["secret", "[RED"] },
|
||||
])(
|
||||
"excludes sensitive text without introducing replacement literals: $value",
|
||||
({ value, sensitive }) => {
|
||||
const fixture = historicalHar();
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({ ...fixture, _sensitive: value, _ordinary: "unmarked" }),
|
||||
sensitive,
|
||||
);
|
||||
expect(result.container.reported).toMatchObject({
|
||||
_sensitive: null,
|
||||
_ordinary: "unmarked",
|
||||
});
|
||||
expect(result.container.redactions).toContainEqual({
|
||||
pointer: "/_sensitive",
|
||||
reason: "explicit-sensitive-value",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes a declared literal introduced by stripping transport URL userinfo", () => {
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const url = "https://example.test/sensitive";
|
||||
const input = {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
request: {
|
||||
...entry.request,
|
||||
url: "https://user:password@example.test/sensitive",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify(input), [url]);
|
||||
expect(result.records[0]?.reported).toMatchObject({ request: { url: null } });
|
||||
});
|
||||
|
||||
it.each([
|
||||
'"_duplicate":1,"_duplicate":1',
|
||||
'"_duplicate":null,"_duplicate":null',
|
||||
'"_duplicate":{"value":1},"_duplicate":{"value":1}',
|
||||
'"_duplicate":1,"\\u005fduplicate":1',
|
||||
])(
|
||||
"rejects equal-valued duplicate JSON members before projection: %s",
|
||||
(members) => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
`"cache":{},${members}`,
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow("duplicate");
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects identical duplicate core fields before schema validation", () => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"version":"1.2"',
|
||||
'"version":"1.2","version":"1.2"',
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow("duplicate");
|
||||
});
|
||||
|
||||
it("reports an unsupported JSON schema boundary instead of dropping a producer property", () => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
'"cache":{},"_extension":{"__proto__":{"preserved":7},"constructor":"ordinary"}',
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow(
|
||||
"JSON schema boundary cannot preserve",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves Unicode, offsets, sizes, duplicate URLs and opaque extensions without inventing bytes", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
fixture.log.entries.push(structuredClone(first));
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
...fixture,
|
||||
_extension: { isLosslessNumber: true, value: "ordinary" },
|
||||
}),
|
||||
[],
|
||||
);
|
||||
expect(result.total_records).toBe(2);
|
||||
expect(result.records[0]?.reported).toEqual(fixture.log.entries[0]);
|
||||
expect(result.records[0]?.binary_fields).toEqual([]);
|
||||
expect(result.records[0]?.numeric_literals).toContainEqual({
|
||||
pointer: "/response/bodySize",
|
||||
producer_type: "json-number",
|
||||
literal: "99",
|
||||
});
|
||||
expect(result.records[1]?.location).toEqual({
|
||||
kind: "json-pointer",
|
||||
pointer: "/log/entries/1",
|
||||
});
|
||||
expect(result.container.reported).toMatchObject({
|
||||
_extension: { isLosslessNumber: true, value: "ordinary" },
|
||||
log: { entries: null },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["9007199254740993", "4740993", "99"])(
|
||||
"excludes explicitly sensitive numeric lexemes and their reported values: %s",
|
||||
(literal) => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
'"cache":{},"_big":9007199254740993',
|
||||
);
|
||||
const result = decodeHarCapture(text, [literal]);
|
||||
for (const record of result.records) {
|
||||
expect(
|
||||
record.numeric_literals.every(
|
||||
(number) => !number.literal.includes(literal),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
const pointer = literal === "99" ? "/response/bodySize" : "/_big";
|
||||
expect(result.records[0]?.redactions).toContainEqual({
|
||||
pointer,
|
||||
reason: "explicit-sensitive-value",
|
||||
});
|
||||
if (literal === "99")
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
response: { bodySize: null },
|
||||
});
|
||||
else expect(result.records[0]?.reported).toMatchObject({ _big: null });
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps unsafe extension numeric lexemes and rejects unsafe mandatory schema numbers", () => {
|
||||
const text = JSON.stringify(historicalHar());
|
||||
const result = decodeHarCapture(
|
||||
text.replace('"cache":{}', '"cache":{},"_big":9007199254740993'),
|
||||
[],
|
||||
);
|
||||
expect(result.records[0]?.numeric_literals).toContainEqual({
|
||||
pointer: "/_big",
|
||||
producer_type: "json-number",
|
||||
literal: "9007199254740993",
|
||||
});
|
||||
expect(result.records[0]?.reported).toMatchObject({ _big: null });
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
text.replace('"bodySize":0', '"bodySize":9007199254740993'),
|
||||
[],
|
||||
),
|
||||
).toThrow("HAR schema validation failed");
|
||||
});
|
||||
|
||||
it.each(["container", "record"] as const)(
|
||||
"retains %s extension content without interpreting it as an HTTP body",
|
||||
(location) => {
|
||||
const fixture = historicalHar();
|
||||
const extension = {
|
||||
response: { content: { encoding: "base64", text: "opaque extension" } },
|
||||
};
|
||||
const input =
|
||||
location === "container"
|
||||
? { ...fixture, _extension: extension }
|
||||
: {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: fixture.log.entries.map((entry) => ({
|
||||
...entry,
|
||||
_extension: extension,
|
||||
})),
|
||||
},
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify(input), []);
|
||||
expect(
|
||||
location === "container"
|
||||
? result.container.reported
|
||||
: result.records[0]?.reported,
|
||||
).toMatchObject({ _extension: extension });
|
||||
expect(result.records[0]?.binary_fields).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains valid base64 bytes independently of declared sizes", () => {
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const text = JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
response: {
|
||||
...entry.response,
|
||||
content: {
|
||||
size: 999,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "AP9B\n",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = decodeHarCapture(text, []);
|
||||
expect(result.records[0]?.binary_fields[0]).toMatchObject({
|
||||
pointer: "/response/content/text",
|
||||
state: "retained",
|
||||
content_base64: "AP9B",
|
||||
bytes: 3,
|
||||
});
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
response: { content: { size: 999, text: "AP9B\n" } },
|
||||
});
|
||||
expect(() => decodeHarCapture(text.replace("AP9B", "AR=="), [])).toThrow(
|
||||
"not valid canonical base64",
|
||||
);
|
||||
});
|
||||
|
||||
it("redacts actual authentication fields and explicit binary values while preserving similarly named extensions", () => {
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const raw = {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
request: {
|
||||
...entry.request,
|
||||
url: "https://user:password@example.test/a?token=ordinary#fragment",
|
||||
headers: [
|
||||
{ name: "Authorization", value: "Bearer transport-secret" },
|
||||
{ name: "X-Test", value: "a" },
|
||||
{ name: "X-Test", value: "b" },
|
||||
],
|
||||
cookies: [{ name: "session", value: "cookie-secret" }],
|
||||
},
|
||||
response: {
|
||||
...entry.response,
|
||||
content: {
|
||||
size: 5,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: Buffer.from("chosen-private").toString("base64"),
|
||||
},
|
||||
},
|
||||
_extension: {
|
||||
response: {
|
||||
headers: [{ name: "Authorization", value: "ordinary-extension" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify(raw), ["chosen-private"]);
|
||||
const output = JSON.stringify(result);
|
||||
for (const secret of [
|
||||
"password",
|
||||
"transport-secret",
|
||||
"cookie-secret",
|
||||
Buffer.from("chosen-private").toString("base64"),
|
||||
])
|
||||
expect(output).not.toContain(secret);
|
||||
expect(output).toContain("token=ordinary#fragment");
|
||||
expect(output).toContain("ordinary-extension");
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
request: {
|
||||
headers: [
|
||||
{ name: "Authorization", value: null },
|
||||
{ name: "X-Test", value: "a" },
|
||||
{ name: "X-Test", value: "b" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.records[0]?.binary_fields[0]).toMatchObject({
|
||||
state: "redacted",
|
||||
sha256: null,
|
||||
content_base64: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"{",
|
||||
'{"log":{},"log":{}}',
|
||||
JSON.stringify({ log: { version: "1.2", entries: [] } }),
|
||||
])("rejects malformed producer data %s", (text) => {
|
||||
expect(() => decodeHarCapture(text, [])).toThrow();
|
||||
});
|
||||
|
||||
it("preserves observed SaveHar null post-data without broadening arbitrary HAR producers", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const log = {
|
||||
...fixture.log,
|
||||
creator: { name: "mitmproxy", version: "12.2.3" },
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
request: {
|
||||
...first.request,
|
||||
postData: { mimeType: "text/plain", text: null },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
decodeHarCapture(JSON.stringify({ log }), []).records[0]?.reported,
|
||||
).toMatchObject({ request: { postData: { text: null } } });
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: { ...log, creator: { name: "other", version: "1" } },
|
||||
}),
|
||||
[],
|
||||
),
|
||||
).toThrow("HAR schema validation failed");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"c2VjcmV0",
|
||||
"c2Vj",
|
||||
createHash("sha256").update("secret").digest("hex"),
|
||||
])(
|
||||
"excludes sensitive derived byte representations from spaced HAR text: %s",
|
||||
(literal) => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
response: {
|
||||
...first.response,
|
||||
content: {
|
||||
size: 6,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "c2 VjcmV0",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
[literal],
|
||||
);
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
response: { content: { text: null } },
|
||||
});
|
||||
expect(result.records[0]?.binary_fields).toContainEqual({
|
||||
pointer: "/response/content/text",
|
||||
representation: "har-base64-content",
|
||||
state: "redacted",
|
||||
content_base64: null,
|
||||
bytes: null,
|
||||
sha256: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes a declared literal in encoded HAR text from its binary sidecar too", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const log = {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
response: {
|
||||
...first.response,
|
||||
content: {
|
||||
size: 3,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "AP9B",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify({ log }), ["AP9B"]);
|
||||
expect(JSON.stringify(result)).not.toContain("AP9B");
|
||||
expect(result.records[0]?.binary_fields[0]?.state).toBe("redacted");
|
||||
});
|
||||
|
||||
it("rejects excessive extension nesting instead of returning a partial capture", () => {
|
||||
let extension: unknown = null;
|
||||
for (let index = 0; index < 66; index++) extension = { child: extension };
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
JSON.stringify({ ...historicalHar(), _extension: extension }),
|
||||
[],
|
||||
),
|
||||
).toThrow("nesting budget");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "Location", side: "response" as const },
|
||||
{ name: "Referer", side: "request" as const },
|
||||
{ name: "Origin", side: "request" as const },
|
||||
])(
|
||||
"excludes leading-OWS userinfo from a producer $name header",
|
||||
({ name, side }) => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const value =
|
||||
" \tHTTPS://user:password@example.test/path?token=ordinary#fragment\t ";
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
[side]: { ...first[side], headers: [{ name, value }] },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
[side]: {
|
||||
headers: [
|
||||
{
|
||||
name,
|
||||
value: " \tHTTPS://example.test/path?token=ordinary#fragment\t ",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.records[0]?.redactions).toContainEqual({
|
||||
pointer: `/${side}/headers/0/value`,
|
||||
reason: "transport-credential",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,244 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isSafeNumber, LosslessNumber } from "lossless-json";
|
||||
import { parseHarJson } from "./HarJson.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
type WebNetworkCapture,
|
||||
type WebNetworkCaptureRecord,
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
import {
|
||||
CaptureRedaction,
|
||||
captureObject,
|
||||
capturePointer,
|
||||
} from "./CaptureRedaction.js";
|
||||
import { createHarValidator } from "./HarSchema.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
|
||||
|
||||
type DecodedCapture = Omit<
|
||||
WebNetworkCapture,
|
||||
"artifact" | "format" | "runtime_attribution" | "limitations"
|
||||
>;
|
||||
type Projection = Pick<
|
||||
WebNetworkCaptureRecord,
|
||||
"reported" | "numeric_literals" | "binary_fields" | "redactions"
|
||||
>;
|
||||
|
||||
/** Decode a retained HAR with exact numeric lexemes and unchanged upstream schema validation. */
|
||||
export const decodeHarCapture = (
|
||||
text: string,
|
||||
sensitiveValues: readonly string[],
|
||||
): DecodedCapture => {
|
||||
const raw = parseHarJson(text);
|
||||
const validation = projectHar(raw, [], false);
|
||||
createHarValidator()(validation.reported);
|
||||
if (
|
||||
!captureObject(raw) ||
|
||||
!captureObject(raw.log) ||
|
||||
!Array.isArray(raw.log.entries)
|
||||
)
|
||||
throw new CaptureFormatError("format", "HAR must contain log.entries.");
|
||||
if (raw.log.version !== "1.2")
|
||||
throw new CaptureFormatError(
|
||||
"unsupported",
|
||||
"Only the pinned HAR 1.2 schema profile is supported.",
|
||||
"/log/version",
|
||||
);
|
||||
const entries = raw.log.entries;
|
||||
const recordsExcluded = ["log", "entries"].some((key) =>
|
||||
sensitiveValues.some((literal) => key.includes(literal)),
|
||||
);
|
||||
const container = projectHar(
|
||||
{ ...raw, log: { ...raw.log, entries: null } },
|
||||
sensitiveValues,
|
||||
true,
|
||||
);
|
||||
const records = entries.map((entry, ordinal): WebNetworkCaptureRecord => {
|
||||
// Validate each original record even when a structural ancestor excludes it.
|
||||
const projected = projectHar(entry, sensitiveValues, true);
|
||||
const projection: Projection = recordsExcluded
|
||||
? {
|
||||
reported: null,
|
||||
numeric_literals: [],
|
||||
binary_fields: [],
|
||||
redactions: [{ pointer: "", reason: "explicit-sensitive-value" }],
|
||||
}
|
||||
: projected;
|
||||
return {
|
||||
ordinal,
|
||||
location: recordsExcluded
|
||||
? { kind: "unknown", reason: "explicit-sensitive-value" }
|
||||
: { kind: "json-pointer", pointer: `/log/entries/${ordinal}` },
|
||||
...projection,
|
||||
limitations: [
|
||||
"HAR text is producer-decoded Unicode. Original body bytes remain unknown unless content explicitly uses valid base64; declared sizes are preserved independently of retained bytes. mitmproxy 12.2.3 SaveHar may report null optional postData.text; that null is retained and omitted only from the upstream validation copy.",
|
||||
...(recordsExcluded
|
||||
? [
|
||||
"This record's payload and sidecars are excluded because its structural ancestor property was explicitly marked sensitive.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
});
|
||||
return {
|
||||
decoder: { ...HAR_CAPTURE_PROVIDER_IDENTITY },
|
||||
container: {
|
||||
reported: container.reported,
|
||||
numeric_literals: container.numeric_literals,
|
||||
redactions: container.redactions,
|
||||
records_pointer: recordsExcluded ? null : "/log/entries",
|
||||
},
|
||||
total_records: records.length,
|
||||
records,
|
||||
};
|
||||
};
|
||||
|
||||
const projectHar = (
|
||||
value: unknown,
|
||||
sensitiveValues: readonly string[],
|
||||
redact: boolean,
|
||||
): Projection => {
|
||||
const redactor = new CaptureRedaction(sensitiveValues);
|
||||
const numeric_literals: Projection["numeric_literals"] = [];
|
||||
const binary_fields: Projection["binary_fields"] = [];
|
||||
const visit = (
|
||||
item: unknown,
|
||||
pointer: string,
|
||||
depth: number,
|
||||
parent?: Readonly<Record<string, unknown>>,
|
||||
): JsonValue => {
|
||||
if (depth > WEB_NETWORK_CAPTURE_LIMITS.depth)
|
||||
throw new CaptureFormatError(
|
||||
"input-limit",
|
||||
"HAR exceeds the 64-level complete-evidence nesting budget.",
|
||||
pointer,
|
||||
);
|
||||
if (
|
||||
redact &&
|
||||
parent !== undefined &&
|
||||
redactor.harCredential(pointer, parent)
|
||||
)
|
||||
return redactor.credential(pointer);
|
||||
if (item instanceof LosslessNumber) {
|
||||
if (redact && redactor.text(item.value, pointer) === null) return null;
|
||||
numeric_literals.push({
|
||||
pointer,
|
||||
producer_type: "json-number",
|
||||
literal: item.value,
|
||||
});
|
||||
return isSafeNumber(item.value) ? Number(item.value) : null;
|
||||
}
|
||||
if (typeof item === "string") {
|
||||
if (
|
||||
redact &&
|
||||
pointer === "/response/content/text" &&
|
||||
parent?.encoding === "base64"
|
||||
) {
|
||||
const bytes = decodeHarBase64(item, pointer);
|
||||
const contentBase64 = bytes.toString("base64");
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
const hidden =
|
||||
redactor.sensitiveBytes(bytes) ||
|
||||
sensitiveValues.some(
|
||||
(literal) =>
|
||||
item.includes(literal) ||
|
||||
contentBase64.includes(literal) ||
|
||||
sha256.includes(literal),
|
||||
);
|
||||
binary_fields.push(
|
||||
hidden
|
||||
? {
|
||||
pointer,
|
||||
representation: "har-base64-content",
|
||||
state: "redacted",
|
||||
content_base64: null,
|
||||
bytes: null,
|
||||
sha256: null,
|
||||
}
|
||||
: {
|
||||
pointer,
|
||||
representation: "har-base64-content",
|
||||
state: "retained",
|
||||
content_base64: contentBase64,
|
||||
bytes: bytes.length,
|
||||
sha256,
|
||||
},
|
||||
);
|
||||
if (hidden) {
|
||||
redactor.redactions.push({
|
||||
pointer,
|
||||
reason: "explicit-sensitive-value",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return redact
|
||||
? redactor.text(
|
||||
item,
|
||||
pointer,
|
||||
redactor.harTransportUrl(pointer, parent),
|
||||
)
|
||||
: item;
|
||||
}
|
||||
if (item === null || typeof item === "boolean") return item;
|
||||
if (Array.isArray(item))
|
||||
return item.map((child, index) =>
|
||||
visit(child, capturePointer(pointer, String(index)), depth + 1),
|
||||
);
|
||||
if (captureObject(item))
|
||||
return Object.fromEntries(
|
||||
Object.entries(item).flatMap(([key, child]) => {
|
||||
if (
|
||||
redact &&
|
||||
sensitiveValues.some((literal) => key.includes(literal))
|
||||
) {
|
||||
const beforeNumbers = numeric_literals.length;
|
||||
const beforeBinaries = binary_fields.length;
|
||||
const beforeRedactions = redactor.redactions.length;
|
||||
visit(child, capturePointer(pointer, key), depth + 1, item);
|
||||
numeric_literals.splice(beforeNumbers);
|
||||
binary_fields.splice(beforeBinaries);
|
||||
redactor.redactions.splice(beforeRedactions);
|
||||
redactor.redactions.push({
|
||||
pointer,
|
||||
reason: "explicit-sensitive-value",
|
||||
scope: "property-name",
|
||||
});
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
[key, visit(child, capturePointer(pointer, key), depth + 1, item)],
|
||||
];
|
||||
}),
|
||||
);
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR parser returned a non-JSON value.",
|
||||
pointer,
|
||||
);
|
||||
};
|
||||
return {
|
||||
reported: visit(value, "", 0),
|
||||
numeric_literals,
|
||||
binary_fields,
|
||||
redactions: redactor.redactions,
|
||||
};
|
||||
};
|
||||
|
||||
const decodeHarBase64 = (value: string, pointer: string): Buffer => {
|
||||
const compact = value.replace(/[\t\n\r ]/g, "");
|
||||
const bytes = Buffer.from(compact, "base64");
|
||||
if (
|
||||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
|
||||
compact,
|
||||
) ||
|
||||
bytes.toString("base64") !== compact
|
||||
)
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR content declares base64 but its text is not valid canonical base64 (ASCII whitespace is allowed).",
|
||||
pointer,
|
||||
);
|
||||
return bytes;
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
|
||||
|
||||
/** HAR's parser/schema packages run in one bounded Node heap, without network or target execution. */
|
||||
export class HarCaptureAdapter implements HistoricalCaptureFormatAdapter {
|
||||
readonly format = "har";
|
||||
readonly identity = HAR_CAPTURE_PROVIDER_IDENTITY;
|
||||
async command(
|
||||
requestPath: string,
|
||||
): Promise<{ command: string; arguments: readonly string[] }> {
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"--max-old-space-size=192",
|
||||
"--max-semi-space-size=8",
|
||||
"--v8-pool-size=1",
|
||||
"--single-threaded",
|
||||
fileURLToPath(new URL("./HarCaptureProcess.js", import.meta.url)),
|
||||
requestPath,
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { z } from "zod";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
import { decodeHarCapture } from "./HarCapture.js";
|
||||
|
||||
const requestSchema = z.strictObject({
|
||||
snapshot_path: z.string(),
|
||||
reply_path: z.string(),
|
||||
sensitive_values: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
/** Decode untrusted HAR in an owned, bounded heap rather than the long-lived MCP process. */
|
||||
const main = async (): Promise<void> => {
|
||||
const request = requestSchema.parse(
|
||||
JSON.parse(await readFile(process.argv[2] ?? "", "utf8")),
|
||||
);
|
||||
let reply: unknown;
|
||||
try {
|
||||
const snapshot = await readStableArtifact(
|
||||
request.snapshot_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
);
|
||||
let text: string;
|
||||
try {
|
||||
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
||||
snapshot.bytes,
|
||||
);
|
||||
} catch {
|
||||
throw new CaptureFormatError("format", "HAR is not valid UTF-8 JSON.");
|
||||
}
|
||||
reply = {
|
||||
ok: true,
|
||||
value: decodeHarCapture(text, request.sensitive_values),
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
reply =
|
||||
cause instanceof CaptureFormatError
|
||||
? {
|
||||
ok: false,
|
||||
reason: cause.reason,
|
||||
message: cause.message,
|
||||
pointer: cause.pointer,
|
||||
}
|
||||
: {
|
||||
ok: false,
|
||||
reason: "decoder",
|
||||
message: `HAR decoder failed unexpectedly (${cause instanceof Error ? cause.name : "unknown exception"}).`,
|
||||
pointer: "",
|
||||
};
|
||||
}
|
||||
let text = JSON.stringify(reply);
|
||||
if (Buffer.byteLength(text) > WEB_NETWORK_CAPTURE_LIMITS.outputBytes)
|
||||
text = JSON.stringify({
|
||||
ok: false,
|
||||
reason: "limit",
|
||||
message: "HAR reply exceeds the complete-evidence output budget.",
|
||||
pointer: "",
|
||||
});
|
||||
await writeFile(request.reply_path, text, { flag: "wx", mode: 0o600 });
|
||||
};
|
||||
await main();
|
||||
@@ -0,0 +1,118 @@
|
||||
import { visit } from "jsonc-parser";
|
||||
import { LosslessNumber } from "lossless-json";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
|
||||
type Frame =
|
||||
| {
|
||||
kind: "object";
|
||||
pointer: string;
|
||||
members: Map<string, unknown>;
|
||||
pendingKey?: string;
|
||||
}
|
||||
| { kind: "array"; pointer: string; items: unknown[] };
|
||||
|
||||
/** Materialize upstream JSON events without duplicate folding, prototype setters or numeric rounding. */
|
||||
export const parseHarJson = (text: string): unknown => {
|
||||
const frames: Frame[] = [];
|
||||
let result: unknown;
|
||||
const valuePointer = (): string => {
|
||||
const parent = frames.at(-1);
|
||||
if (parent === undefined) return "";
|
||||
if (parent.kind === "array")
|
||||
return `${parent.pointer}/${parent.items.length}`;
|
||||
return parent.pendingKey === undefined
|
||||
? parent.pointer
|
||||
: `${parent.pointer}/${parent.pendingKey.replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
||||
};
|
||||
const checkDepth = (): void => {
|
||||
if (frames.length > WEB_NETWORK_CAPTURE_LIMITS.depth)
|
||||
throw new CaptureFormatError(
|
||||
"input-limit",
|
||||
"HAR exceeds the 64-level complete-evidence nesting budget.",
|
||||
valuePointer(),
|
||||
);
|
||||
};
|
||||
const append = (value: unknown): void => {
|
||||
const parent = frames.at(-1);
|
||||
if (parent === undefined) result = value;
|
||||
else if (parent.kind === "array") parent.items.push(value);
|
||||
else {
|
||||
if (parent.pendingKey === undefined)
|
||||
throw new TypeError(
|
||||
"JSON visitor omitted an object property identity.",
|
||||
);
|
||||
parent.members.set(parent.pendingKey, value);
|
||||
delete parent.pendingKey;
|
||||
}
|
||||
};
|
||||
visit(
|
||||
text,
|
||||
{
|
||||
onObjectBegin: () => {
|
||||
checkDepth();
|
||||
frames.push({
|
||||
kind: "object",
|
||||
pointer: valuePointer(),
|
||||
members: new Map(),
|
||||
});
|
||||
},
|
||||
onObjectProperty: (key) => {
|
||||
if (key === "__proto__")
|
||||
throw new CaptureFormatError(
|
||||
"unsupported",
|
||||
"HAR object contains a __proto__ member that the current JSON schema boundary cannot preserve.",
|
||||
);
|
||||
const frame = frames.at(-1);
|
||||
if (frame?.kind !== "object")
|
||||
throw new TypeError(
|
||||
"JSON visitor emitted a property outside an object.",
|
||||
);
|
||||
if (frame.members.has(key))
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR JSON contains duplicate object members.",
|
||||
);
|
||||
frame.pendingKey = key;
|
||||
},
|
||||
onObjectEnd: () => {
|
||||
const frame = frames.pop();
|
||||
if (frame?.kind !== "object")
|
||||
throw new TypeError("JSON visitor ended an unexpected object.");
|
||||
append(Object.fromEntries(frame.members));
|
||||
},
|
||||
onArrayBegin: () => {
|
||||
checkDepth();
|
||||
frames.push({ kind: "array", pointer: valuePointer(), items: [] });
|
||||
},
|
||||
onArrayEnd: () => {
|
||||
const frame = frames.pop();
|
||||
if (frame?.kind !== "array")
|
||||
throw new TypeError("JSON visitor ended an unexpected array.");
|
||||
append(frame.items);
|
||||
},
|
||||
onLiteralValue: (value: unknown, offset, length) => {
|
||||
checkDepth();
|
||||
if (typeof value === "number")
|
||||
append(new LosslessNumber(text.slice(offset, offset + length)));
|
||||
else if (
|
||||
value === null ||
|
||||
typeof value === "boolean" ||
|
||||
typeof value === "string"
|
||||
)
|
||||
append(value);
|
||||
else
|
||||
throw new TypeError("JSON visitor emitted an unsupported literal.");
|
||||
},
|
||||
onError: () => {
|
||||
throw new CaptureFormatError("format", "HAR is malformed JSON.");
|
||||
},
|
||||
},
|
||||
{
|
||||
disallowComments: true,
|
||||
allowTrailingComma: false,
|
||||
allowEmptyContent: false,
|
||||
},
|
||||
);
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { Ajv } from "ajv";
|
||||
import { z } from "zod";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
|
||||
/** Validate using the unchanged, pinned upstream HAR 1.2 draft-06 schemas. */
|
||||
export const createHarValidator = (): ((value: unknown) => void) => {
|
||||
const require = createRequire(import.meta.url);
|
||||
const schemas = z
|
||||
.record(z.string(), z.record(z.string(), z.unknown()))
|
||||
.parse(require("har-schema"));
|
||||
const ajv = new Ajv({ strict: false, allErrors: false, ownProperties: true });
|
||||
ajv.addMetaSchema(require("ajv/dist/refs/json-schema-draft-06.json"));
|
||||
const plugin: unknown = require("ajv-formats");
|
||||
if (typeof plugin !== "function")
|
||||
throw new Error("Pinned AJV formats plugin is unavailable");
|
||||
plugin(ajv);
|
||||
for (const schema of Object.values(schemas)) ajv.addSchema(schema);
|
||||
const validate = ajv.getSchema("har.json#");
|
||||
if (validate === undefined)
|
||||
throw new Error("Pinned HAR root schema is unavailable");
|
||||
return (value) => {
|
||||
allowMitmproxyAbsentPostData(value);
|
||||
if (!validate(value)) {
|
||||
const error = validate.errors?.[0];
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
`HAR schema validation failed: ${error?.keyword ?? "unknown constraint"}.`,
|
||||
error?.instancePath ?? "",
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** Observed SaveHar 12.2.3 compatibility: validate omitted optional text while retaining reported null. */
|
||||
const allowMitmproxyAbsentPostData = (value: unknown): void => {
|
||||
const parsed = z
|
||||
.object({
|
||||
log: z.object({
|
||||
creator: z.object({
|
||||
name: z.literal("mitmproxy"),
|
||||
version: z.literal("12.2.3"),
|
||||
}),
|
||||
entries: z.array(z.unknown()),
|
||||
}),
|
||||
})
|
||||
.safeParse(value);
|
||||
if (
|
||||
!parsed.success ||
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!("log" in value)
|
||||
)
|
||||
return;
|
||||
const log = value.log;
|
||||
if (
|
||||
typeof log !== "object" ||
|
||||
log === null ||
|
||||
!("entries" in log) ||
|
||||
!Array.isArray(log.entries)
|
||||
)
|
||||
return;
|
||||
for (const entry of log.entries) {
|
||||
const candidate: unknown = entry;
|
||||
if (
|
||||
typeof candidate !== "object" ||
|
||||
candidate === null ||
|
||||
!("request" in candidate)
|
||||
)
|
||||
continue;
|
||||
const request = candidate.request;
|
||||
if (
|
||||
typeof request !== "object" ||
|
||||
request === null ||
|
||||
!("postData" in request)
|
||||
)
|
||||
continue;
|
||||
const body = request.postData;
|
||||
if (
|
||||
typeof body === "object" &&
|
||||
body !== null &&
|
||||
"text" in body &&
|
||||
body.text === null
|
||||
)
|
||||
delete body.text;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,250 @@
|
||||
import { historicalCaptureFailure } from "./CaptureFailures.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { z } from "zod";
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
webNetworkCaptureSchema,
|
||||
type InspectWebNetworkCaptureInput,
|
||||
type WebNetworkCapture,
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { runOwnedCommand } from "../../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
|
||||
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
|
||||
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
const decodedSchema = webNetworkCaptureSchema.omit({
|
||||
artifact: true,
|
||||
format: true,
|
||||
runtime_attribution: true,
|
||||
limitations: true,
|
||||
});
|
||||
const replySchema = z.discriminatedUnion("ok", [
|
||||
z.strictObject({ ok: z.literal(true), value: decodedSchema }),
|
||||
z.strictObject({
|
||||
ok: z.literal(false),
|
||||
reason: z.enum([
|
||||
"format",
|
||||
"unsupported",
|
||||
"input-limit",
|
||||
"resource-limit",
|
||||
"decoder",
|
||||
"limit",
|
||||
]),
|
||||
message: z.string(),
|
||||
pointer: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** One owned snapshot/process/root lifecycle for replaceable historical format decoders. */
|
||||
export class HistoricalCaptureDecoder {
|
||||
constructor(
|
||||
readonly adapters: readonly HistoricalCaptureFormatAdapter[],
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>,
|
||||
readonly createRuntime: () => Promise<
|
||||
Pick<PrivateRuntimeRoot, "path" | "close">
|
||||
> = () => PrivateRuntimeRoot.create({ prefix: "rea-web-capture-" }),
|
||||
) {}
|
||||
|
||||
/** Snapshot the selected artifact, decode it offline, and release private credentials and processes. */
|
||||
async inspect(
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>> {
|
||||
let runtime: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
|
||||
let result: Result<WebNetworkCapture, AnalysisError>;
|
||||
let phase: "capture-read" | "decoder" = "capture-read";
|
||||
try {
|
||||
const adapter = this.adapters.find(
|
||||
(candidate) => candidate.format === input.format,
|
||||
);
|
||||
if (adapter === undefined)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
input.format,
|
||||
OPERATION,
|
||||
"No adapter is configured for the selected capture format.",
|
||||
);
|
||||
const snapshot = await readStableArtifact(
|
||||
input.capture_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "decoder";
|
||||
runtime = await this.createRuntime();
|
||||
const snapshotPath = join(runtime.path, "capture.snapshot");
|
||||
const requestPath = join(runtime.path, "request.json");
|
||||
const replyPath = join(runtime.path, "reply.json");
|
||||
await writeFile(snapshotPath, snapshot.bytes, {
|
||||
mode: 0o600,
|
||||
flag: "wx",
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
await writeFile(
|
||||
requestPath,
|
||||
JSON.stringify({
|
||||
snapshot_path: snapshotPath,
|
||||
reply_path: replyPath,
|
||||
sensitive_values: input.sensitive_values,
|
||||
}),
|
||||
{ mode: 0o600, flag: "wx" },
|
||||
);
|
||||
const command = await adapter.command(requestPath, runtime.path);
|
||||
const environment: NodeJS.ProcessEnv = {
|
||||
...this.environment,
|
||||
UV_THREADPOOL_SIZE: "1",
|
||||
};
|
||||
delete environment.NODE_OPTIONS;
|
||||
await runOwnedCommand(
|
||||
{
|
||||
...command,
|
||||
runId: `rea-web-capture-${randomUUID()}`,
|
||||
cwd: runtime.path,
|
||||
hostEnvironment: environment,
|
||||
},
|
||||
{
|
||||
timeoutMs: WEB_NETWORK_CAPTURE_LIMITS.timeoutMs,
|
||||
diagnosticBytes: 1024 * 1024,
|
||||
},
|
||||
options?.signal === undefined ? {} : { signal: options.signal },
|
||||
);
|
||||
let reply: z.output<typeof replySchema>;
|
||||
try {
|
||||
const replyFile = await readStableArtifact(
|
||||
replyPath,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
reply = replySchema.parse(JSON.parse(replyFile.bytes.toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
if (options?.signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION);
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
`Owned capture decoder reply failed for ${input.capture_path}: ${replyFailureReason(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
if (!reply.ok) {
|
||||
if (reply.reason === "format")
|
||||
throw new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["capture_path", reply.pointer],
|
||||
reason: "invalid_format",
|
||||
message: reply.message,
|
||||
},
|
||||
]);
|
||||
if (reply.reason === "input-limit")
|
||||
throw new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["capture_path", reply.pointer],
|
||||
reason: "out_of_range",
|
||||
message: reply.message,
|
||||
expected: {
|
||||
maximum_capture_nesting: WEB_NETWORK_CAPTURE_LIMITS.depth,
|
||||
},
|
||||
},
|
||||
]);
|
||||
if (reply.reason === "decoder" || reply.reason === "resource-limit")
|
||||
throw new ProviderAdapterError(input.format, OPERATION, {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
failure_kind: reply.reason,
|
||||
reason: reply.message,
|
||||
pointer: reply.pointer,
|
||||
},
|
||||
});
|
||||
if (reply.reason === "unsupported")
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
input.format,
|
||||
OPERATION,
|
||||
reply.message,
|
||||
);
|
||||
throw new AnalysisOutputError(OPERATION, reply.message);
|
||||
}
|
||||
if (
|
||||
reply.value.decoder.id !== adapter.identity.id ||
|
||||
reply.value.decoder.name !== adapter.identity.name ||
|
||||
reply.value.decoder.version !== adapter.identity.version
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture decoder changed the selected upstream profile identity.",
|
||||
);
|
||||
result = ok({
|
||||
...reply.value,
|
||||
artifact: {
|
||||
path: input.capture_path,
|
||||
sha256: snapshot.sha256,
|
||||
bytes: snapshot.bytes.length,
|
||||
},
|
||||
format: input.format,
|
||||
runtime_attribution: "unknown",
|
||||
limitations: [
|
||||
"This is retained producer evidence, without live browser transaction IDs, scenario provenance, execution attribution or deployment authenticity. Recorded URLs are never fetched.",
|
||||
"Every record is decoded before selection; no partial success is returned on malformed input or a resource limit.",
|
||||
"Known authentication headers/cookies and explicitly marked literal values are excluded. Unknown extension names do not establish sensitivity.",
|
||||
"A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. HAR uses a 192 MiB Node old-generation heap; native decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.",
|
||||
],
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
result = err(
|
||||
redactExplicitFailure(
|
||||
historicalCaptureFailure(input, cause, phase, options),
|
||||
input.sensitive_values,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (runtime !== undefined) {
|
||||
try {
|
||||
await runtime.close();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
redactExplicitFailure(
|
||||
new ProviderCleanupError(
|
||||
input.format,
|
||||
[runtime.path],
|
||||
{
|
||||
capture_path: input.capture_path,
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ operation: OPERATION },
|
||||
),
|
||||
input.sensitive_values,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return result.ok && options?.signal?.aborted
|
||||
? err(new AnalysisCancelledError(OPERATION))
|
||||
: result;
|
||||
}
|
||||
}
|
||||
|
||||
const replyFailureReason = (cause: unknown): string => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause.message;
|
||||
if (cause instanceof z.ZodError)
|
||||
return `Reply violates its schema at ${cause.issues[0]?.path.map(String).join(".") ?? "root"}.`;
|
||||
if (cause instanceof SyntaxError) return "Reply is malformed JSON.";
|
||||
if (cause instanceof Error && "code" in cause)
|
||||
return `Reply file could not be read (${String(cause.code)}).`;
|
||||
return "Reply could not be validated.";
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { InspectWebNetworkCaptureInput } from "../../domain/webNetworkCapture.js";
|
||||
|
||||
/** Format-specific process profile keeps mature upstream code behind a replaceable adapter seam. */
|
||||
export interface HistoricalCaptureFormatAdapter {
|
||||
readonly format: InspectWebNetworkCaptureInput["format"];
|
||||
readonly identity: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
command(
|
||||
requestPath: string,
|
||||
runtimePath: string,
|
||||
): Promise<{ command: string; arguments: readonly string[] }>;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { access } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import { MITMPROXY_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
/** Native mitmproxy decoding is offline and uses only an explicitly configured Linux tool. */
|
||||
export class MitmproxyCaptureAdapter implements HistoricalCaptureFormatAdapter {
|
||||
readonly format = "mitmproxy";
|
||||
readonly identity = MITMPROXY_CAPTURE_PROVIDER_IDENTITY;
|
||||
constructor(readonly environment: Readonly<NodeJS.ProcessEnv>) {}
|
||||
async command(
|
||||
requestPath: string,
|
||||
runtimePath: string,
|
||||
): Promise<{ command: string; arguments: readonly string[] }> {
|
||||
const command = this.environment.REA_MITMDUMP_COMMAND;
|
||||
if (
|
||||
process.platform !== "linux" ||
|
||||
command === undefined ||
|
||||
!isAbsolute(command)
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
OPERATION,
|
||||
"Native capture decoding requires Linux and an absolute REA_MITMDUMP_COMMAND path to caller-supplied mitmdump 12.2.3; HAR needs no external engine.",
|
||||
);
|
||||
try {
|
||||
await access(command, constants.R_OK | constants.X_OK);
|
||||
} catch (cause: unknown) {
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
OPERATION,
|
||||
`Configured mitmdump executable is unavailable: ${command}.`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
return {
|
||||
command,
|
||||
arguments: [
|
||||
"--no-server",
|
||||
"-q",
|
||||
"--set",
|
||||
`confdir=${runtimePath}`,
|
||||
"--set",
|
||||
`rea_request_path=${requestPath}`,
|
||||
"-s",
|
||||
fileURLToPath(
|
||||
new URL("../../../bridge/mitmproxy/capture.py", import.meta.url),
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user