feat(fiddler): inspect native SAZ captures

Inspect bounded recorded raw HTTP/XML SAZ archives and page retained capture Evidence. Preserve exact stored bytes and provenance, validate ZIP/XML integrity, and require an enforceable decoder memory bound.

Verified 356 real recorded sessions against independent byte and metadata oracles, public CLI/MCP parity, retained pages, and related interface checks. Current Fiddler Everywhere GUI and non-Linux producer workflows remain unverified.

Co-authored-by: zahhak <1792039+zahhak@users.noreply.github.com>
Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
Ilian Iliev
2026-10-13 02:51:14 +00:00
committed by GitHub
co-authored by zahhak N0zoM1z0
parent f254f5ac2b
commit a2d8b94dd5
61 changed files with 2237 additions and 285 deletions
+2 -14
View File
@@ -16,6 +16,7 @@ import { jsonObjectSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
inspectWebNetworkCaptureInputSchema,
captureSensitiveValues,
webNetworkCaptureSchema,
} from "../domain/webNetworkCapture.js";
@@ -32,21 +33,8 @@ export class WebNetworkCaptureService {
): 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 : [],
),
);
err(redactExplicitFailure(error, captureSensitiveValues(rawInput)));
const parsed = inspectWebNetworkCaptureInputSchema.safeParse(rawInput);
if (!parsed.success)
return failure(
@@ -47,14 +47,8 @@ export const inspectAnalysisViewValidated = (
input: InspectAnalysisViewInput,
lookup?: EvidenceLookup,
): Result<Evidence, AnalysisError> => {
const inline = input.source.kind === "inline" ? input.source.evidence : null;
const inlineCapture =
typeof inline === "object" &&
inline !== null &&
Object.getOwnPropertyDescriptor(inline, "operation")?.value ===
"inspect_web_network_capture";
const accumulator =
input.view.kind === "api-surface" || inlineCapture
input.view.kind === "api-surface"
? new WebNetworkApiSurfaceAccumulator()
: undefined;
if (input.source.kind === "inline" && accumulator !== undefined) {
+4 -4
View File
@@ -4,7 +4,7 @@ import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
import { inspectWebNetworkCaptureInputSchema } from "../../domain/webNetworkCapture.js";
import { historicalCaptureFailure } from "./CaptureFailures.js";
import { HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "./CaptureRelease.js";
import { NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "./CaptureRelease.js";
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
@@ -118,7 +118,7 @@ it.each([
},
});
// The enforced limit is reported only where Bun runs on Windows.
if (HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null)
if (NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null)
expect(JSON.stringify(projected)).not.toContain(
"process_memory_limit_bytes",
);
@@ -126,12 +126,12 @@ it.each([
expect(projected).toMatchObject({
details: {
reported_limits: {
process_memory_limit_bytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
process_memory_limit_bytes: NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
},
},
remediation: {
action: expect.stringContaining(
`${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes`,
`${String(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes`,
),
},
});
+13 -11
View File
@@ -18,9 +18,9 @@ import {
} from "../../domain/webNetworkCapture.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
HAR_CAPTURE_HEAP_ENFORCED,
HAR_CAPTURE_HEAP_LIMITS,
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
NODE_CAPTURE_HEAP_ENFORCED,
NODE_CAPTURE_HEAP_LIMITS,
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "./CaptureRelease.js";
const OPERATION = "inspect_web_network_capture";
@@ -78,7 +78,7 @@ export const historicalCaptureFailure = (
);
if (
phase === "decoder" &&
input.format === "har" &&
input.format !== "mitmproxy" &&
cause.reason === "process" &&
(cause.snapshot?.signal === "SIGABRT" ||
(cause.snapshot?.signal === null && cause.snapshot.exitCode === 134)) &&
@@ -195,15 +195,17 @@ export const captureMemoryFailure = (
format: input.format,
maximum_input_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
maximum_reply_bytes: WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
...(input.format === "har" && HAR_CAPTURE_HEAP_ENFORCED
...(input.format !== "mitmproxy" && NODE_CAPTURE_HEAP_ENFORCED
? {
old_generation_heap_mib: HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB,
semi_space_heap_mib: HAR_CAPTURE_HEAP_LIMITS.semiSpaceMiB,
old_generation_heap_mib: NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB,
semi_space_heap_mib: NODE_CAPTURE_HEAP_LIMITS.semiSpaceMiB,
}
: {}),
...(input.format === "har" &&
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null
? { process_memory_limit_bytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }
...(input.format !== "mitmproxy" &&
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null
? {
process_memory_limit_bytes: NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
}
: {}),
...(cause instanceof OwnedCommandFailure
? {
@@ -214,7 +216,7 @@ export const captureMemoryFailure = (
},
{
cause,
remediationAction: `Use a smaller capture exported by its producer, or another decoder with sufficient capacity for the original capture. Preserve the original for provenance; a subset does not establish complete-capture coverage.${input.format === "har" && HAR_CAPTURE_HEAP_ENFORCED ? ` REA's HAR old-generation heap is fixed at ${HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB} MiB; inherited NODE_OPTIONS cannot raise it.` : ""}${input.format === "har" && HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null ? ` REA's HAR decoder process commit limit is fixed at ${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes.` : ""}`,
remediationAction: `Use a smaller capture exported by its producer, or another decoder with sufficient capacity for the original capture. Preserve the original for provenance; a subset does not establish complete-capture coverage.${input.format !== "mitmproxy" && NODE_CAPTURE_HEAP_ENFORCED ? ` REA's Node capture old-generation heap is fixed at ${NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB} MiB; inherited NODE_OPTIONS cannot raise it.` : ""}${input.format !== "mitmproxy" && NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null ? ` REA's Node capture decoder process commit limit is fixed at ${String(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)} bytes.` : ""}`,
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
? {
capturedOutput: {
+1 -1
View File
@@ -1,7 +1,7 @@
/** Expected malformed, unsupported or oversized producer data at a historical decoder boundary. */
export class CaptureFormatError extends Error {
constructor(
readonly reason: "format" | "unsupported" | "input-limit",
readonly reason: "format" | "unsupported" | "input-limit" | "limit",
message: string,
readonly pointer = "",
) {
+13 -6
View File
@@ -8,19 +8,19 @@ export const HAR_CAPTURE_PROVIDER_IDENTITY = {
version: "har-schema@2.0.0;jsonc-parser@3.3.1;lossless-json@4.3.1",
} as const;
/** Fixed V8 heap settings used by the owned HAR decoder process. */
export const HAR_CAPTURE_HEAP_LIMITS = {
/** Fixed V8 heap settings used by the owned Node capture decoder process. */
export const NODE_CAPTURE_HEAP_LIMITS = {
oldGenerationMiB: 192,
semiSpaceMiB: 8,
} as const;
/** The HAR decoder runs on this executable; Bun accepts but ignores V8 heap flags. */
export const HAR_CAPTURE_HEAP_ENFORCED =
/** The Node capture decoder runs on this executable; Bun accepts but ignores V8 heap flags. */
export const NODE_CAPTURE_HEAP_ENFORCED =
javaScriptRuntime(process.versions).id === "node";
/** Windows Job Object commit limit replacing the ignored heap flags under Bun; otherwise null. */
export const HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES =
javaScriptWorkerMemoryLimitBytes(HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB);
export const NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES =
javaScriptWorkerMemoryLimitBytes(NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB);
/** Native executable profile verified with unchanged mitmproxy raw-state decoding. */
export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
@@ -28,3 +28,10 @@ export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
name: "REA offline native mitmproxy adapter",
version: "12.2.3",
} as const;
/** Native SAZ member decoding with the existing ZIP and XML package profiles. */
export const SAZ_CAPTURE_PROVIDER_IDENTITY = {
id: "fiddler-saz",
name: "REA Fiddler SAZ capture adapter",
version: "1;zip.js@2.15.0;xmldom@0.9.12",
} as const;
-33
View File
@@ -1,33 +0,0 @@
import { fileURLToPath } from "node:url";
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
import {
HAR_CAPTURE_PROVIDER_IDENTITY,
HAR_CAPTURE_HEAP_LIMITS,
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} 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[];
memoryLimitBytes?: number;
}> {
return {
command: process.execPath,
arguments: [
`--max-old-space-size=${HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB}`,
`--max-semi-space-size=${HAR_CAPTURE_HEAP_LIMITS.semiSpaceMiB}`,
"--v8-pool-size=1",
"--single-threaded",
fileURLToPath(new URL("./HarCaptureProcess.js", import.meta.url)),
requestPath,
],
...(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? {}
: { memoryLimitBytes: HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }),
};
}
}
+12 -11
View File
@@ -4,9 +4,9 @@ import {
captureMemoryFailure,
} from "./CaptureFailures.js";
import {
HAR_CAPTURE_HEAP_ENFORCED,
HAR_CAPTURE_HEAP_LIMITS,
HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
NODE_CAPTURE_HEAP_ENFORCED,
NODE_CAPTURE_HEAP_LIMITS,
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "./CaptureRelease.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
@@ -208,10 +208,11 @@ export class HistoricalCaptureDecoder {
format: input.format,
runtime_attribution: "unknown",
limitations: [
...(adapter.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. ${harMemoryLimitation()}; native decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.`,
`A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. ${nodeMemoryLimitation()}; mitmproxy decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.`,
],
});
} catch (cause: unknown) {
@@ -251,13 +252,13 @@ export class HistoricalCaptureDecoder {
}
}
/** The HAR decoder runs on this executable; only Node.js enforces its V8 heap flags. */
const harMemoryLimitation = (): string => {
if (HAR_CAPTURE_HEAP_ENFORCED)
return `HAR uses a ${String(HAR_CAPTURE_HEAP_LIMITS.oldGenerationMiB)} MiB Node old-generation heap`;
return HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? "HAR runs on Bun, which does not enforce REA's V8 heap flags"
: `HAR runs on Bun, which does not enforce REA's V8 heap flags, under a ${String(HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)}-byte Windows Job Object commit limit`;
/** The Node capture decoder runs on this executable; only Node.js enforces its V8 heap flags. */
const nodeMemoryLimitation = (): string => {
if (NODE_CAPTURE_HEAP_ENFORCED)
return `HAR/SAZ use a ${String(NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB)} MiB Node old-generation heap`;
return NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? "HAR/SAZ run on Bun, which does not enforce REA's V8 heap flags"
: `HAR/SAZ run on Bun, which does not enforce REA's V8 heap flags, under a ${String(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES)}-byte Windows Job Object commit limit`;
};
const replyFailureReason = (cause: unknown): string => {
@@ -3,6 +3,7 @@ import type { InspectWebNetworkCaptureInput } from "../../domain/webNetworkCaptu
/** Format-specific process profile keeps mature upstream code behind a replaceable adapter seam. */
export interface HistoricalCaptureFormatAdapter {
readonly format: InspectWebNetworkCaptureInput["format"];
readonly limitations?: readonly string[];
readonly identity: {
readonly id: string;
readonly name: string;
@@ -0,0 +1,15 @@
import { expect, it, vi } from "vitest";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { NodeCaptureAdapter } from "./NodeCaptureAdapter.js";
vi.mock("./CaptureRelease.js", async (original) => ({
...(await original<typeof import("./CaptureRelease.js")>()),
NODE_CAPTURE_HEAP_ENFORCED: false,
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES: null,
}));
it("refuses a SAZ worker when the runtime has no enforceable memory bound", async () => {
await expect(
new NodeCaptureAdapter("saz").command("/owned/request.json"),
).rejects.toBeInstanceOf(AnalysisCapabilityUnavailableError);
});
+58
View File
@@ -0,0 +1,58 @@
import { fileURLToPath } from "node:url";
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
import {
NODE_CAPTURE_HEAP_ENFORCED,
HAR_CAPTURE_PROVIDER_IDENTITY,
SAZ_CAPTURE_PROVIDER_IDENTITY,
NODE_CAPTURE_HEAP_LIMITS,
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "./CaptureRelease.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
/** Package-backed capture decoders share one bounded offline Node process profile. */
export class NodeCaptureAdapter implements HistoricalCaptureFormatAdapter {
readonly identity;
readonly limitations;
constructor(readonly format: "har" | "saz") {
this.identity =
format === "har"
? HAR_CAPTURE_PROVIDER_IDENTITY
: SAZ_CAPTURE_PROVIDER_IDENTITY;
this.limitations =
format === "saz"
? [
"SAZ ordinals follow first session-member occurrence in ZIP directory order, not chronology or numeric session ID.",
"HTTP fields use byte-preserving Latin-1 text; start-line separators and header delimiters are not projected. Bodies retain stored bytes without transfer/content decoding. Absent members are null, distinct from empty bodies.",
"XML preserves node order and attribute/text values, not its original byte serialization. WebSocket and gRPC members retain opaque message-file bytes, not decoded protocol events.",
"Non-session archive members are inventoried but their content is not decoded.",
]
: [];
}
async command(requestPath: string) {
if (
this.format === "saz" &&
!NODE_CAPTURE_HEAP_ENFORCED &&
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
)
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
"inspect_web_network_capture",
"SAZ decoding requires an enforced decoder memory limit. Run REA with Node.js on this host.",
);
return {
command: process.execPath,
arguments: [
`--max-old-space-size=${NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB}`,
`--max-semi-space-size=${NODE_CAPTURE_HEAP_LIMITS.semiSpaceMiB}`,
"--v8-pool-size=1",
"--single-threaded",
fileURLToPath(new URL("./NodeCaptureProcess.js", import.meta.url)),
requestPath,
this.format,
],
...(NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? {}
: { memoryLimitBytes: NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES }),
};
}
}
@@ -3,7 +3,6 @@ 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, decodeHarText } from "./HarCapture.js";
const requestSchema = z.strictObject({
snapshot_path: z.string(),
@@ -11,24 +10,34 @@ const requestSchema = z.strictObject({
sensitive_values: z.array(z.string().min(1)),
});
/** Decode untrusted HAR in an owned, bounded heap rather than the long-lived MCP process. */
/** Parse untrusted captures in an owned heap and return one complete bounded reply. */
const main = async (): Promise<void> => {
const format = z.enum(["har", "saz"]).parse(process.argv[3]);
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,
);
reply = {
ok: true,
value: decodeHarCapture(
let value;
if (format === "har") {
const { decodeHarCapture, decodeHarText } =
await import("./HarCapture.js");
const snapshot = await readStableArtifact(
request.snapshot_path,
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
);
value = decodeHarCapture(
decodeHarText(snapshot.bytes),
request.sensitive_values,
),
};
);
} else {
const { decodeSazCapture } = await import("./SazCapture.js");
value = await decodeSazCapture(
request.snapshot_path,
request.sensitive_values,
);
}
reply = { ok: true, value };
} catch (cause: unknown) {
reply =
cause instanceof CaptureFormatError
@@ -41,7 +50,7 @@ const main = async (): Promise<void> => {
: {
ok: false,
reason: "decoder",
message: `HAR decoder failed unexpectedly (${cause instanceof Error ? cause.name : "unknown exception"}).`,
message: `Capture decoder failed unexpectedly (${cause instanceof Error ? cause.name : "unknown exception"}).`,
pointer: "",
};
}
@@ -50,7 +59,7 @@ const main = async (): Promise<void> => {
text = JSON.stringify({
ok: false,
reason: "limit",
message: "HAR reply exceeds the complete-evidence output budget.",
message: "Capture reply exceeds the complete-evidence output budget.",
pointer: "",
});
await writeFile(request.reply_path, text, { flag: "wx", mode: 0o600 });
+174
View File
@@ -0,0 +1,174 @@
import { ZipArtifactReader } from "../../artifacts/ZipArtifactReader.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
} from "../../artifacts/ArtifactReader.js";
import {
WEB_NETWORK_CAPTURE_LIMITS,
type WebNetworkCaptureRecord,
} from "../../domain/webNetworkCapture.js";
import { SAZ_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
import { decodeSazHttp } from "./SazHttp.js";
import { decodeSazMetadata } from "./SazMetadata.js";
import { projectSazRecord, type SazValue } from "./SazProjection.js";
/** Decode native SAZ sessions without extracting files, running Fiddler or converting to HAR. */
export const decodeSazCapture = async (
snapshotPath: string,
sensitiveValues: readonly string[],
) => {
const reader = new ZipArtifactReader(
snapshotPath,
"zip",
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
);
try {
const groups = new Map<string, ArtifactEntry[]>();
const inventory: SazValue[] = [];
const paths = new Set<string>();
let declaredBytes = 0;
for await (const entry of reader.entries()) {
if (paths.has(entry.path))
throw new CaptureFormatError(
"format",
"SAZ contains duplicate archive member names.",
);
paths.add(entry.path);
if (entry.encrypted)
throw new CaptureFormatError(
"unsupported",
"Encrypted SAZ archives are unsupported; export an unencrypted copy from Fiddler Everywhere.",
);
if (entry.kind !== "file" && entry.kind !== "directory")
throw new CaptureFormatError(
"unsupported",
"SAZ archive links are unsupported.",
);
if (entry.declaredSize !== null) {
if (!Number.isSafeInteger(entry.declaredSize) || entry.declaredSize < 0)
throw new CaptureFormatError("format", "SAZ member size is invalid.");
declaredBytes += entry.declaredSize;
}
if (declaredBytes > WEB_NETWORK_CAPTURE_LIMITS.inputBytes)
throw new CaptureFormatError(
"limit",
"SAZ expanded members exceed the 32 MiB complete-evidence budget.",
);
inventory.push({
path: entry.path,
kind: entry.kind,
bytes: entry.declaredSize,
});
if (entry.kind !== "file") continue;
const match = /^raw\/(\d+)_(c\.txt|s\.txt|m\.xml|w\.txt|g\.txt)$/.exec(
entry.path,
);
if (match?.[1] !== undefined) {
const group = groups.get(match[1]) ?? [];
group.push(entry);
groups.set(match[1], group);
} else if (entry.path.startsWith("raw/")) {
throw new CaptureFormatError(
"unsupported",
"SAZ contains an unrecognized raw session member.",
);
}
}
if (groups.size === 0)
throw new CaptureFormatError(
"format",
"Archive contains no SAZ session members.",
);
const records: WebNetworkCaptureRecord[] = [];
for (const [session_id, entries] of groups) {
const source: Record<string, SazValue> = {
session_id,
request: null,
response: null,
metadata: null,
websocket: null,
grpc: null,
};
for (const entry of entries) {
const stream = await reader.open(entry);
const chunks: Buffer[] = [];
let length = 0;
for await (const chunk of stream) {
if (!Buffer.isBuffer(chunk))
throw new CaptureFormatError(
"format",
"SAZ member stream returned non-byte data.",
);
length += chunk.length;
if (length > (entry.declaredSize ?? 0))
throw new CaptureFormatError(
"format",
"SAZ member exceeds its declared size.",
);
chunks.push(chunk);
}
if (length !== entry.declaredSize)
throw new CaptureFormatError(
"format",
"SAZ member does not match its declared size.",
);
const bytes = Buffer.concat(chunks, length);
if (entry.path.endsWith("_c.txt"))
source.request = {
member: entry.path,
...decodeSazHttp(bytes, true),
};
else if (entry.path.endsWith("_s.txt"))
source.response = {
member: entry.path,
...decodeSazHttp(bytes, false),
};
else if (entry.path.endsWith("_m.xml"))
source.metadata = {
member: entry.path,
document: decodeSazMetadata(bytes),
};
else
source[entry.path.endsWith("_w.txt") ? "websocket" : "grpc"] = {
member: entry.path,
messages: bytes,
};
}
records.push({
ordinal: records.length,
location: {
kind: "archive-members",
members: entries.map((entry) => entry.path),
},
...projectSazRecord(source, sensitiveValues),
limitations: [],
});
}
const container = projectSazRecord({ members: inventory }, sensitiveValues);
return {
decoder: { ...SAZ_CAPTURE_PROVIDER_IDENTITY },
container: {
reported: container.reported,
numeric_literals: container.numeric_literals,
redactions: container.redactions,
records_pointer: null,
},
total_records: records.length,
records,
};
} catch (cause: unknown) {
if (cause instanceof CaptureFormatError) throw cause;
if (cause instanceof ArtifactReaderFailure && cause.reason === "limit")
throw new CaptureFormatError(
"limit",
"SAZ archive exceeds the ZIP reader's resource budget.",
);
throw new CaptureFormatError(
"format",
"SAZ archive or session data is malformed or fails ZIP integrity validation.",
);
} finally {
await reader.close();
}
};
+72
View File
@@ -0,0 +1,72 @@
import { CaptureFormatError } from "./CaptureFormatError.js";
/** Preserve ordered HTTP fields and the stored body; never dechunk, decompress or fetch. */
export const decodeSazHttp = (bytes: Buffer, request: boolean) => {
const crlfSplit = bytes.indexOf("\r\n\r\n");
// Once a CRLF separator is found, only an earlier LF separator can win.
// Avoid searching an otherwise unrelated large body a second time.
const lfSplit = bytes
.subarray(0, crlfSplit < 0 ? bytes.length : crlfSplit)
.indexOf("\n\n");
// The first separator ends the headers. Later separators belong to the
// stored body, which may use different line endings or contain binary data.
const split =
crlfSplit >= 0 && (lfSplit < 0 || crlfSplit < lfSplit) ? crlfSplit : -1;
const boundary = split < 0 ? lfSplit : split;
if (boundary < 0)
throw new CaptureFormatError(
"format",
"SAZ HTTP message has no header/body separator.",
);
const lines = bytes
.subarray(0, boundary)
.toString("latin1")
.split(split < 0 ? "\n" : "\r\n");
const first = lines.shift() ?? "";
const fields = request
? /^(\S+) +(\S+) +(HTTP\/\d+(?:\.\d+)?)$/.exec(first)
: /^(HTTP\/\d+(?:\.\d+)?) +(\d{3})(?: (.*))?$/.exec(first);
if (fields === null)
throw new CaptureFormatError("format", "SAZ HTTP start line is malformed.");
const headers: { name: string; value: string }[] = [];
for (const line of lines) {
if (/^[ \t]/.test(line)) {
const previous = headers.at(-1);
if (previous === undefined)
throw new CaptureFormatError(
"format",
"SAZ HTTP header continuation has no field.",
);
previous.value += `${split < 0 ? "\n" : "\r\n"}${line}`;
continue;
}
const colon = line.indexOf(":");
// HTTP/2 pseudo-headers use the second colon as the delimiter.
const delimiter = colon === 0 ? line.indexOf(":", 1) : colon;
if (delimiter < 1)
throw new CaptureFormatError("format", "SAZ HTTP header is malformed.");
const name = line.slice(0, delimiter);
if (!/^:?[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name))
throw new CaptureFormatError(
"format",
"SAZ HTTP header name is malformed.",
);
headers.push({ name, value: line.slice(delimiter + 1) });
}
const start = request
? {
method: fields[1] ?? "",
url: fields[2] ?? "",
http_version: fields[3] ?? "",
}
: {
http_version: fields[1] ?? "",
status: fields[2] ?? "",
reason: fields[3] ?? "",
};
return {
...start,
headers,
body: bytes.subarray(boundary + (split < 0 ? 2 : 4)),
};
};
+83
View File
@@ -0,0 +1,83 @@
import { DOMParser, ParseError, type Node } from "@xmldom/xmldom";
import type { JsonValue } from "../../domain/jsonValue.js";
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
/** Preserve XML node order, attribute names and text without interpreting producer-specific flags. */
export const decodeSazMetadata = (bytes: Buffer): JsonValue => {
let xml: string;
try {
const encoding =
bytes[0] === 0xff && bytes[1] === 0xfe
? "utf-16le"
: bytes[0] === 0xfe && bytes[1] === 0xff
? "utf-16be"
: "utf-8";
xml = new TextDecoder(encoding, { fatal: true }).decode(bytes);
} catch {
throw new CaptureFormatError(
"unsupported",
"SAZ metadata must use UTF-8 or BOM-marked UTF-16.",
);
}
let parseFailed = false;
let document: ReturnType<DOMParser["parseFromString"]>;
try {
document = new DOMParser({
normalizeLineEndings: (source) => source,
onError: () => {
parseFailed = true;
},
}).parseFromString(xml, "application/xml");
} catch (cause: unknown) {
if (!(cause instanceof ParseError)) throw cause;
throw new CaptureFormatError(
"format",
"SAZ metadata is not well-formed XML.",
);
}
// The pinned parser does not resolve external or DTD-defined entities.
// Inspect its parsed node; text inside comments/CDATA is ordinary evidence.
if (document.doctype !== null)
throw new CaptureFormatError(
"unsupported",
"SAZ metadata DTDs are unsupported.",
);
if (parseFailed)
throw new CaptureFormatError(
"format",
"SAZ metadata is not well-formed XML.",
);
if (document.documentElement?.tagName !== "Session")
throw new CaptureFormatError(
"format",
"SAZ metadata must have a Session document element.",
);
const visit = (node: Node, depth: number): JsonValue => {
if (depth > WEB_NETWORK_CAPTURE_LIMITS.depth)
throw new CaptureFormatError(
"input-limit",
"SAZ metadata exceeds the complete-evidence nesting budget.",
);
const children: JsonValue[] = [];
for (let child = node.firstChild; child !== null; child = child.nextSibling)
children.push(visit(child, depth + 1));
const attributes: JsonValue[] = [];
if (node.nodeType === 1) {
const element = node as import("@xmldom/xmldom").Element;
for (let i = 0; i < element.attributes.length; i++) {
const attribute = element.attributes.item(i);
if (attribute !== null)
attributes.push({ name: attribute.name, value: attribute.value });
}
}
return {
name: node.nodeName,
type: node.nodeType,
value: node.nodeValue,
attributes,
children,
};
};
return visit(document, 0);
};
+131
View File
@@ -0,0 +1,131 @@
import { createHash } from "node:crypto";
import { isUtf8 } from "node:buffer";
import type { JsonValue } from "../../domain/jsonValue.js";
import {
WEB_NETWORK_CAPTURE_LIMITS,
type WebNetworkCaptureRecord,
} from "../../domain/webNetworkCapture.js";
import { CaptureRedaction, capturePointer } from "./CaptureRedaction.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
export type SazValue =
| JsonValue
| Buffer
| { readonly [key: string]: SazValue }
| readonly SazValue[];
/** Project native byte fields with the same credential and explicit-literal exclusions as HAR. */
export const projectSazRecord = (
source: SazValue,
sensitiveValues: readonly string[],
) => {
const redactor = new CaptureRedaction(sensitiveValues);
const binary_fields: WebNetworkCaptureRecord["binary_fields"] = [];
const visit = (
value: SazValue,
pointer: string,
depth: number,
parent?: Readonly<Record<string, SazValue>>,
): JsonValue => {
if (depth > WEB_NETWORK_CAPTURE_LIMITS.depth)
throw new CaptureFormatError(
"input-limit",
"SAZ projection exceeds the complete-evidence nesting budget.",
pointer,
);
if (parent !== undefined && redactor.harCredential(pointer, parent))
return redactor.credential(pointer);
if (Buffer.isBuffer(value)) {
const base64 = value.toString("base64");
const sha256 = createHash("sha256").update(value).digest("hex");
const hidden =
redactor.sensitiveBytes(value) ||
sensitiveValues.some(
(literal) =>
base64.includes(literal) ||
sha256.includes(literal) ||
String(value.length).includes(literal),
);
if (hidden) {
binary_fields.push({
pointer,
representation: "producer-bytes",
state: "redacted",
content_base64: null,
bytes: null,
sha256: null,
});
redactor.redactions.push({
pointer,
reason: "explicit-sensitive-value",
});
return null;
}
binary_fields.push({
pointer,
representation: "producer-bytes",
state: "retained",
content_base64: base64,
bytes: value.length,
sha256,
});
return isUtf8(value) ? value.toString("utf8") : null;
}
if (typeof value === "string") {
// HTTP fields are Latin-1 views of bytes. A UTF-8 declaration must also
// exclude its byte spelling, even when its display is mojibake.
if (
/^\/(request|response)\//.test(pointer) &&
!pointer.endsWith("/member") &&
redactor.sensitiveBytes(Buffer.from(value, "latin1"))
) {
redactor.redactions.push({
pointer,
reason: "explicit-sensitive-value",
});
return null;
}
return redactor.text(
value,
pointer,
redactor.harTransportUrl(pointer, parent),
);
}
if (value === null || typeof value === "boolean") return value;
if (typeof value === "number")
return redactor.text(String(value), pointer) === null ? null : value;
if (Array.isArray(value))
return value.map((child: SazValue, i: number) =>
visit(child, capturePointer(pointer, String(i)), depth + 1),
);
return Object.fromEntries(
Object.entries(value).flatMap(([key, child]) => {
if (sensitiveValues.some((literal) => key.includes(literal))) {
redactor.redactions.push({
pointer,
reason: "explicit-sensitive-value",
scope: "property-name",
});
return [];
}
return [
[
key,
visit(
child,
capturePointer(pointer, key),
depth + 1,
value as Readonly<Record<string, SazValue>>,
),
],
];
}),
);
};
return {
reported: visit(source, "", 0),
binary_fields,
numeric_literals: [],
redactions: redactor.redactions,
};
};
+5 -2
View File
@@ -1,4 +1,5 @@
import { z } from "incur";
import { WEB_NETWORK_CAPTURE_FORMATS } from "../domain/webNetworkCapture.js";
import { createWebNetworkCaptureService } from "../composition/webNetworkCaptures.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
@@ -16,10 +17,12 @@ export const registerWebNetworkCaptureCommands = (
const service = createWebNetworkCaptureService(environment);
cli.command(CLI_COMMANDS.inspectWebNetworkCapture, {
description:
"Inspect retained HAR or native mitmproxy records without fetching recorded URLs",
"Inspect retained HAR, native mitmproxy, or Fiddler SAZ records without fetching recorded URLs",
args: z.object({
capturePath: z.string().describe("Absolute local capture path"),
format: z.enum(["har", "mitmproxy"]).describe("Producer capture format"),
format: z
.enum(WEB_NETWORK_CAPTURE_FORMATS)
.describe("Producer capture format"),
}),
options: z.object({
record: z
+6 -2
View File
@@ -1,6 +1,6 @@
import { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
import { HistoricalCaptureDecoder } from "../browser/history/HistoricalCaptureDecoder.js";
import { HarCaptureAdapter } from "../browser/history/HarCaptureAdapter.js";
import { NodeCaptureAdapter } from "../browser/history/NodeCaptureAdapter.js";
import { MitmproxyCaptureAdapter } from "../browser/history/MitmproxyCaptureAdapter.js";
/** Compose offline format adapters without import-time reads, installation or process startup. */
@@ -9,7 +9,11 @@ export const createWebNetworkCaptureService = (
): WebNetworkCaptureService =>
new WebNetworkCaptureService(
new HistoricalCaptureDecoder(
[new HarCaptureAdapter(), new MitmproxyCaptureAdapter(environment)],
[
new NodeCaptureAdapter("har"),
new NodeCaptureAdapter("saz"),
new MitmproxyCaptureAdapter(environment),
],
environment,
),
);
+1 -1
View File
@@ -16,7 +16,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_analysis_view"),
kind: "application",
description:
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_evm_interface, inspect_managed_artifact, inspect_android_package or inspect_web_network_capture Evidence without repeating analysis. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. For layout, JavaScript, native, inventory, WASM, EVM, managed artifact and Android package sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions; occurrence logical_paths matches exact recorded strings (omitted means all available, [] means none). source_complete distinguishes complete inventories from partial source records; page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Android package summaries retain all declarations, engine identity and counts without decoded manifest text. Android manifest pages use kind android, facet manifest, offset and limit in UTF-16 code units; source_status preserves partial decoded coverage even when the retained text page is exhausted. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.',
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_evm_interface, inspect_managed_artifact, inspect_android_package or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. For layout, JavaScript, native, inventory, WASM, EVM, managed artifact and Android package sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Inventory uses view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json"], offset: 0, limit: 64}. Inventory views page nodes, occurrences, edges or integrity contradictions; occurrence logical_paths matches exact recorded strings (omitted means all available, [] means none). source_complete distinguishes complete inventories from partial source records; page exhaustion does not prove absence in a partial source. WASM views use kind wasm and facet sections/imports/exports/candidates/glue/wat/headers/details/tool_profile; text facets use UTF-16 code units and source forms remain exact. EVM summary returns all inferred interface candidates, carrier/decoded identities and explicit unknowns without hex or duplicate stdout. EVM views use kind evm and facet functions/bytecode_hex/stdout/stderr; function pages preserve the original candidate rows, and text offsets/limits count UTF-16 code units (hex has two characters per decoded byte). Exhausting candidate pages does not establish global interface completeness. Managed artifact summaries preserve complete identity/classification, metadata status, module/MVID, frameworks, coverage and limitations without unrelated inventories. Managed pages use kind managed and collection references/resources/attributes, retaining source coverage and build-local token scope; page exhaustion does not establish complete metadata. Android package summaries retain all declarations, engine identity and counts without decoded manifest text. Android manifest pages use kind android, facet manifest, offset and limit in UTF-16 code units; source_status preserves partial decoded coverage even when the retained text page is exhausted. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.',
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
@@ -4,7 +4,11 @@ import {
} from "../domain/webNetworkCapture.js";
import type { ToolContract } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
import {
analysisDetailSchema,
analysisDetailOutputSchemaOf,
} from "./analysisDetail.js";
import { webNetworkCaptureSummaryViewResultSchema } from "../domain/analysisView/analysisView.js";
/** Historical inspection is distinct from live browser capture and runtime authority. */
export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [
@@ -12,10 +16,15 @@ export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [
name: "inspect_web_network_capture",
...toolContractMetadata("inspect_web_network_capture"),
description:
"Inspect retained local HAR 1.2 or native mitmproxy capture records without contacting recorded URLs. Returns original ordinals, pointers/byte ranges, preserved producer fields, precise numeric representations and exact exposed binary bytes inline. Excludes known transport credentials and explicitly marked values. Decodes every record before optional ordinal selection; malformed or oversized captures return no partial success. Duplicate HAR members are invalid; prototype-named members such as __proto__ are preserved as ordinary own JSON members without prototype mutation. Uses pinned upstream parsers, owned temporary files and bounded offline processes. Native mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Browser transaction IDs, runtime attribution and original bytes of HAR Unicode text remain unknown.",
"Request detail summary for capture identity and counts; then page retained records with inspect_analysis_view kind capture (preview or complete), avoiding repeated decoding. Default detail complete preserves existing inline delivery. Inspect retained local HAR 1.2, native mitmproxy, or Fiddler SAZ capture records without contacting recorded URLs. Returns original ordinals, pointers/byte ranges/archive member names, preserved producer fields, precise numeric representations and exact exposed binary bytes inline. Excludes known transport credentials and explicitly marked values. Decodes every record before optional ordinal selection; malformed or oversized captures return no partial success. Duplicate HAR members are invalid; prototype-named members such as __proto__ are preserved as ordinary own JSON members without prototype mutation. Uses pinned upstream parsers, owned temporary files and bounded offline processes. SAZ preserves HTTP fields, XML metadata and encoded body/message bytes without replay or HAR conversion; encrypted archives are unsupported. Native mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Browser transaction IDs, runtime attribution and original bytes of HAR Unicode text remain unknown.",
kind: "browser-provider",
inputSchema: inspectWebNetworkCaptureInputSchema,
outputSchema: evidenceResultOf(webNetworkCaptureSchema),
inputSchema: inspectWebNetworkCaptureInputSchema.extend({
detail: analysisDetailSchema,
}),
outputSchema: analysisDetailOutputSchemaOf(
webNetworkCaptureSchema,
webNetworkCaptureSummaryViewResultSchema,
),
examples: [
{
title: "Inspect historical HAR entries",
+33 -5
View File
@@ -55,6 +55,12 @@ import {
wasmViewItemSchema,
wasmSummarySchema,
} from "./wasmArtifactView.js";
import {
projectWebNetworkCaptureView,
captureViewRequestSchema,
captureViewItemsSchema,
captureSummarySchema,
} from "./webNetworkCaptureView.js";
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
import {
projectAndroidPackageView,
@@ -177,6 +183,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
managedViewRequestSchema,
androidViewRequestSchema,
apiSurfaceViewSchema,
captureViewRequestSchema,
]);
// The application owns admission and authenticated Evidence parsing. SDK and
@@ -216,7 +223,7 @@ const artifactSchema = z.strictObject({
path: z
.string()
.describe("Exact recorded artifact path, including an empty string."),
sha256: digestSchema,
sha256: digestSchema.nullable(),
});
const layoutSummarySchema = z.strictObject({
@@ -290,6 +297,7 @@ const viewResultBase = {
"inspect_wasm_artifact",
"inspect_evm_interface",
"inspect_managed_artifact",
"inspect_web_network_capture",
"inspect_android_package",
]),
parent_digest: digestSchema,
@@ -348,6 +356,13 @@ export const managedArtifactSummaryViewResultSchema = z.strictObject({
summary: managedSummarySchema,
});
/** Exact historical capture summary, with no body or member-inventory payload. */
export const webNetworkCaptureSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
summary: captureSummarySchema,
});
/** Exact package declarations with retained decoded manifest text. */
export const androidPackageSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -377,9 +392,17 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
wasmSummarySchema,
evmSummarySchema,
managedSummarySchema,
captureSummarySchema,
androidPackageSummarySchema,
]),
}),
z.strictObject({
kind: z.literal("capture"),
view: captureViewRequestSchema,
items: captureViewItemsSchema,
...viewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
}),
z.strictObject({
kind: z.literal("facet"),
view: facetViewSchema,
@@ -500,6 +523,10 @@ export type UnsignedAnalysisView =
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "capture" }>,
"view_digest"
>
| Omit<
Extract<AnalysisViewResult, { readonly kind: "managed" }>,
"view_digest"
@@ -603,10 +630,7 @@ export const projectAnalysisView = (
},
]),
);
if (
view.kind === "api-surface" ||
parent.operation === "inspect_web_network_capture"
) {
if (view.kind === "api-surface") {
const projected = projectWebNetworkApiSurfaceView(
parent,
view,
@@ -614,6 +638,10 @@ export const projectAnalysisView = (
);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_web_network_capture") {
const projected = projectWebNetworkCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_binary_layout") {
const layout = binaryLayoutSchema.safeParse(parent.normalizedResult);
if (!layout.success)
@@ -241,22 +241,14 @@ export const projectJavaScriptApplicationView = (
analysis: JavaScriptApplicationAnalysisResult,
view: Exclude<AnalysisViewRequest, { kind: "api-surface" }>,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "item" && view.kind !== "page")
return err(
jsIncompatible(
"JavaScript application Evidence supports summary, module item or module page views.",
),
);
const shared = parentFields(parent, analysis);
const modules = moduleEntries(analysis.graph.nodes);
if (view.kind === "native")
return err(
jsIncompatible("Native views require analyze_function Evidence."),
);
if (view.kind === "inventory")
return err(jsIncompatible("Inventory views require artifact Evidence."));
if (view.kind === "wasm")
return err(
jsIncompatible("WASM views require inspect_wasm_artifact Evidence."),
);
if (view.kind === "evm")
return err(
jsIncompatible("EVM views require inspect_evm_interface Evidence."),
);
if (view.kind === "summary")
return ok({
kind: "summary",
@@ -291,12 +283,6 @@ export const projectJavaScriptApplicationView = (
coverage: completeCoverage(modules.length, analysis.graph.nodes.length),
...shared,
});
if (view.kind === "facet")
return err(
jsIncompatible(
"facet views apply to inspect_binary_layout Evidence (mitigations or linkage).",
),
);
if (view.kind === "item") {
if (view.collection !== "modules")
return err(
@@ -85,11 +85,13 @@ it("pages groups independently of record completeness and preserves null digests
});
it("rejects native captures and malformed parents with typed errors", () => {
const capture = analysisViewCaptureFixture();
capture.format = "mitmproxy";
expect(project(capture)).toMatchObject({
ok: false,
error: { _tag: "AnalysisUnsupportedTargetError" },
});
for (const format of ["mitmproxy", "saz"] as const) {
capture.format = format;
expect(project(capture)).toMatchObject({
ok: false,
error: { _tag: "AnalysisUnsupportedTargetError" },
});
}
expect(
projectAnalysisView(
{
@@ -0,0 +1,176 @@
import { expect, it } from "vitest";
import { createHash } from "node:crypto";
import { createEvidence } from "../evidence.js";
import { webNetworkCaptureSchema } from "../webNetworkCapture.js";
import { projectAnalysisView } from "./analysisView.js";
const capture = () => {
const body = Buffer.from("original body");
const artifact = {
path: "/recordings/input.saz",
sha256: "b".repeat(64),
bytes: 100,
};
const decoder = { id: "fixture", name: "Fixture", version: "1" };
const report = webNetworkCaptureSchema.parse({
artifact,
decoder,
format: "saz",
runtime_attribution: "unknown",
limitations: [],
container: {
reported: { members: [] },
numeric_literals: [],
redactions: [],
records_pointer: null,
},
total_records: 9,
records: [7, 2].map((ordinal) => ({
ordinal,
location: { kind: "archive-members", members: [`raw/${ordinal}_c.txt`] },
reported: {
session_id: String(ordinal),
time: null,
request: {
method: "POST",
url: "https://example.invalid/a",
body: body.toString(),
},
},
binary_fields: [
{
pointer: "/request/body",
representation: "producer-bytes",
state: "retained",
content_base64: body.toString("base64"),
bytes: body.length,
sha256: createHash("sha256").update(body).digest("hex"),
},
],
numeric_literals: [
{
pointer: "/time",
producer_type: "json-number",
literal: "9007199254740993",
},
],
redactions: [],
limitations: [],
})),
});
const evidence = createEvidence({ ...artifact, format: "file" }, decoder, {
operation: "inspect_web_network_capture",
parameters: { record_ordinals: [7, 2] },
result: report,
confidence: "observed",
authority: "historical-reference",
});
return {
report,
parent: {
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: report,
subject: evidence.subject,
limitations: evidence.limitations,
},
};
};
it("keeps selected-record page coverage distinct from capture coverage and unsafe number absence", () => {
const { parent, report } = capture();
const summary = projectAnalysisView(parent, { kind: "summary" });
expect(summary.ok && summary.value).toMatchObject({
summary: { total_records: 9, retained_records: 2 },
coverage: { examined: 2, total: 2 },
});
const preview = projectAnalysisView(parent, {
kind: "capture",
detail: "preview",
offset: 0,
limit: 1,
});
expect(preview.ok && preview.value).toMatchObject({
items: [
{
ordinal: 7,
reported: { time: null },
numeric_literals: [{ pointer: "/time", literal: "9007199254740993" }],
},
],
coverage: { total: 2, examined: 1, next_offset: 1, exhausted: false },
});
expect(JSON.stringify(preview)).not.toContain("original body");
expect(JSON.stringify(preview)).not.toContain("content_base64");
const complete = projectAnalysisView(parent, {
kind: "capture",
detail: "complete",
offset: 1,
limit: 1,
});
expect(complete.ok && complete.value).toMatchObject({
items: [report.records[1]],
coverage: { total: 2, examined: 1, next_offset: null, exhausted: true },
});
const empty = projectAnalysisView(parent, {
kind: "capture",
detail: "preview",
offset: 50,
limit: 1,
});
expect(empty.ok && empty.value).toMatchObject({
items: [],
coverage: {
status: "empty",
total: 2,
examined: 0,
next_offset: null,
exhausted: true,
},
});
});
it("retains explicitly unknown digests and rejects a different subject path", () => {
const { parent, report } = capture();
const unknown = projectAnalysisView(
{
...parent,
subject: null,
normalizedResult: {
...report,
artifact: { ...report.artifact, sha256: null },
},
},
{ kind: "summary" },
);
expect(unknown.ok && unknown.value).toMatchObject({
artifact: { sha256: null },
});
expect(unknown.ok && unknown.value.unknowns.join(" ")).toContain(
"excluded artifact digest",
);
if (parent.subject === null) throw new Error("Expected fixture subject");
const mismatched = projectAnalysisView(
{
...parent,
subject: { ...parent.subject, local_path: "/different/source.saz" },
},
{ kind: "summary" },
);
expect(mismatched.ok).toBe(false);
});
it("rejects invalid ordinal coverage in a borrowed parent", () => {
const { parent, report } = capture();
const result = projectAnalysisView(
{
...parent,
normalizedResult: {
...report,
records: [report.records[0], report.records[0]],
},
},
{ kind: "summary" },
);
expect(result.ok).toBe(false);
});
@@ -0,0 +1,212 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import type { JsonValue } from "../jsonValue.js";
import { err, ok, type Result } from "../result.js";
import {
webNetworkCaptureRecordSchema,
webNetworkCaptureBinaryDescriptorSchema,
webNetworkCaptureSchema,
type WebNetworkCaptureRecord,
} from "../webNetworkCapture.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
/** Offsets page the parent's retained record order, preserving producer ordinals. */
export const captureViewRequestSchema = z.strictObject({
kind: z.literal("capture"),
detail: z.enum(["preview", "complete"]).default("preview"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
const previewSchema = webNetworkCaptureRecordSchema.extend({
binary_fields: z.array(webNetworkCaptureBinaryDescriptorSchema),
});
export const captureViewItemsSchema = z.array(
z.union([webNetworkCaptureRecordSchema, previewSchema]),
);
/** Count/identity overview; bodies and the archive member inventory stay in the parent. */
export const captureSummarySchema = z.strictObject({
artifact: webNetworkCaptureSchema.shape.artifact,
decoder: webNetworkCaptureSchema.shape.decoder,
format: webNetworkCaptureSchema.shape.format,
total_records: z.number().int().nonnegative(),
retained_records: z.number().int().nonnegative(),
runtime_attribution: z.literal("unknown"),
});
const object = (
value: JsonValue,
): Readonly<Record<string, JsonValue>> | null =>
value !== null && typeof value === "object" && !Array.isArray(value)
? value
: null;
/** Select already parsed producer facts without interpreting HTTP or payload bytes again. */
const preview = (record: WebNetworkCaptureRecord) => {
const source = object(record.reported);
const reported: Record<string, JsonValue> = {};
const selectedPointers = new Set<string>();
if (source !== null) {
for (const key of ["session_id", "name", "time", "startedDateTime", "type"])
if (Object.hasOwn(source, key) && source[key] !== undefined) {
reported[key] = source[key];
selectedPointers.add(`/${key}`);
}
for (const key of ["request", "response"]) {
const value = source[key];
if (!Object.hasOwn(source, key) || value === undefined) continue;
const fields = object(value);
if (fields === null) {
// Preserve a reported null/scalar instead of inventing HTTP fields.
reported[key] = value;
continue;
}
const selected: Record<string, JsonValue> = {};
for (const field of [
"method",
"url",
"httpVersion",
"http_version",
"status",
"statusText",
"reason",
])
if (Object.hasOwn(fields, field) && fields[field] !== undefined) {
selected[field] = fields[field];
selectedPointers.add(`/${key}/${field}`);
}
reported[key] = selected;
}
}
return {
...record,
reported: source === null ? record.reported : reported,
binary_fields: record.binary_fields.map(
({ content_base64: _content, ...field }) => field,
),
numeric_literals:
source === null
? record.numeric_literals
: record.numeric_literals.filter(({ pointer }) =>
selectedPointers.has(pointer),
),
};
};
/** Page immutable retained facts; no capture file, provider or network is consulted. */
export const projectWebNetworkCaptureView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "capture")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Historical captures support summary, capture record pages, and admitted api-surface views.",
},
]),
);
const parsed = webNetworkCaptureSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
const report = parsed.data;
if (
report.artifact.sha256 !== null &&
(parent.subject == null ||
parent.subject.local_path !== report.artifact.path ||
parent.subject.digest.sha256 !== report.artifact.sha256)
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Capture parent subject must identify the report's exact path and SHA-256.",
},
]),
);
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_web_network_capture" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: [
...new Set([
...parent.limitations,
...report.limitations,
"Pages cover the records selected into the parent Evidence, in that selected order; total_records counts the original decoded capture.",
]),
],
unknowns: [
"Historical records do not establish live runtime attribution or deployment authenticity.",
...(report.artifact.sha256 === null
? ["The explicitly excluded artifact digest remains unknown."]
: []),
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: {
artifact: report.artifact,
decoder: report.decoder,
format: report.format,
total_records: report.total_records,
retained_records: report.records.length,
runtime_attribution: report.runtime_attribution,
},
coverage: completeWithinViewCoverage(
report.records.length,
report.records.length,
),
});
const records = report.records.slice(view.offset, view.offset + view.limit);
return ok({
kind: "capture",
view,
...shared,
items: captureViewItemsSchema.parse(
view.detail === "complete" ? records : records.map(preview),
),
coverage: pageViewCoverage(
view.offset,
records.length,
report.records.length,
),
limitations: [
...shared.limitations,
...(view.detail === "preview"
? [
"Preview selects recorded headline fields and byte descriptors; headers, XML, bodies, message data and other fields remain in complete record pages. Missing preview fields do not establish their absence from the producer record.",
]
: []),
],
});
};
+43 -17
View File
@@ -10,12 +10,14 @@ export const WEB_NETWORK_CAPTURE_LIMITS = {
depth: 64,
} as const;
export const WEB_NETWORK_CAPTURE_FORMATS = ["har", "mitmproxy", "saz"] as const;
/** Inspect an explicit retained capture without contacting its recorded destinations. */
export const inspectWebNetworkCaptureInputSchema = z.strictObject({
capture_path: localPathStringSchema.describe(
"Absolute local HAR or mitmproxy capture path.",
"Absolute local HAR, mitmproxy, or Fiddler SAZ capture path.",
),
format: z.enum(["har", "mitmproxy"]),
format: z.enum(WEB_NETWORK_CAPTURE_FORMATS),
record_ordinals: z
.array(z.number().int().nonnegative())
.min(1)
@@ -31,6 +33,21 @@ export const inspectWebNetworkCaptureInputSchema = z.strictObject({
),
});
/** Read declarations through their owning schema for service and adapter failures. */
export const captureSensitiveValues = (
rawInput: unknown,
): readonly string[] => {
const parsed =
inspectWebNetworkCaptureInputSchema.shape.sensitive_values.safeParse(
typeof rawInput === "object" &&
rawInput !== null &&
"sensitive_values" in rawInput
? rawInput.sensitive_values
: undefined,
);
return parsed.success ? parsed.data : [];
};
const pointerSchema = z
.string()
.describe("RFC 6901 pointer in the producer's reported object.");
@@ -53,21 +70,26 @@ const binaryBase = {
pointer: pointerSchema,
representation: z.enum(["producer-bytes", "har-base64-content"]),
};
const retainedBinaryDescriptorSchema = z.strictObject({
...binaryBase,
state: z.literal("retained"),
bytes: z.number().int().nonnegative(),
sha256: z.string().regex(/^[0-9a-f]{64}$/),
});
const redactedBinaryDescriptorSchema = z.strictObject({
...binaryBase,
state: z.literal("redacted"),
bytes: z.null(),
sha256: z.null(),
});
/** Exact byte facts shared by complete records and previews that omit content. */
export const webNetworkCaptureBinaryDescriptorSchema = z.discriminatedUnion(
"state",
[retainedBinaryDescriptorSchema, redactedBinaryDescriptorSchema],
);
const binarySchema = z.discriminatedUnion("state", [
z.strictObject({
...binaryBase,
state: z.literal("retained"),
content_base64: z.string(),
bytes: z.number().int().nonnegative(),
sha256: z.string().regex(/^[0-9a-f]{64}$/),
}),
z.strictObject({
...binaryBase,
state: z.literal("redacted"),
content_base64: z.null(),
bytes: z.null(),
sha256: z.null(),
}),
retainedBinaryDescriptorSchema.extend({ content_base64: z.string() }),
redactedBinaryDescriptorSchema.extend({ content_base64: z.null() }),
]);
const numberSchema = z.strictObject({
pointer: pointerSchema,
@@ -84,6 +106,10 @@ export const webNetworkCaptureRecordSchema = z.strictObject({
reason: z.literal("explicit-sensitive-value"),
}),
z.strictObject({ kind: z.literal("json-pointer"), pointer: pointerSchema }),
z.strictObject({
kind: z.literal("archive-members"),
members: z.array(z.string()).min(1),
}),
z.strictObject({
kind: z.literal("byte-range"),
offset: z.number().int().nonnegative(),
@@ -156,7 +182,7 @@ export const webNetworkCaptureSchema =
),
bytes: z.number().int().nonnegative(),
}),
format: z.enum(["har", "mitmproxy"]),
format: z.enum(WEB_NETWORK_CAPTURE_FORMATS),
runtime_attribution: z.literal("unknown"),
limitations: z.array(z.string()),
});
@@ -22,6 +22,8 @@ export const excludeCaptureCoordinates = (
const location =
(record.location.kind === "json-pointer" &&
sensitive(record.location.pointer)) ||
(record.location.kind === "archive-members" &&
record.location.members.some(sensitive)) ||
(record.location.kind === "byte-range" &&
(sensitive(String(record.location.offset)) ||
sensitive(String(record.location.bytes))))
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "40",
skillVersion: "41",
} as const;
+1
View File
@@ -617,6 +617,7 @@ const registerConfiguredAnalysisTools = (
toolLogger,
recordEvidence,
withAdmittedAnalysis,
evidenceById,
);
registerJavaScriptRecoveryTool(
server,
+35 -1
View File
@@ -1,5 +1,14 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { StandardSchemaWithJSON } from "@modelcontextprotocol/server";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
import { captureSensitiveValues } from "../domain/webNetworkCapture.js";
import { err } from "../domain/result.js";
import type { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
@@ -15,6 +24,7 @@ export const registerWebNetworkCaptureTool = (
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
evidenceById?: EvidenceLookup,
): void => {
const contract = toolContract("inspect_web_network_capture");
const registration = toolRegistrationOptions(contract);
@@ -30,7 +40,31 @@ export const registerWebNetworkCaptureTool = (
};
const handler = createEvidenceToolHandler(
server,
(input, options) => service.inspect(input, options),
async (rawInput, options) => {
const parsed = contract.inputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
redactExplicitFailure(
analysisInputErrorFromIssues(
contract.name,
parsed.error.issues,
rawInput,
{ cause: parsed.error },
),
captureSensitiveValues(rawInput),
),
);
const { detail, ...input } = parsed.data;
const retention = { recordEvidence, evidenceById };
if (detail === "summary") {
const ready = requireAnalysisViewRetention(contract.name, retention);
if (!ready.ok) return ready;
}
const inspected = await service.inspect(input, options);
return detail === "summary" && inspected.ok
? summarizeRetainedAnalysis(inspected.value, retention)
: inspected;
},
logger,
recordEvidence,
withAdmittedAnalysis,