chore: reconcile iNES support with current main

This commit is contained in:
64579525
2026-10-13 11:42:47 +08:00
83 changed files with 5172 additions and 399 deletions
+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`,
),
},
});
+14 -12
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)) &&
@@ -86,7 +86,7 @@ export const historicalCaptureFailure = (
)
return captureMemoryFailure(
input,
"The HAR decoder exhausted its fixed V8 heap",
`The ${input.format} decoder exhausted its fixed V8 heap`,
cause,
);
}
@@ -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 = "",
) {
@@ -2,6 +2,7 @@ import { visit } from "jsonc-parser";
import { LosslessNumber } from "lossless-json";
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
import { TextDecoder } from "node:util";
type Frame =
| {
@@ -13,7 +14,10 @@ type Frame =
| { kind: "array"; pointer: string; items: unknown[] };
/** Materialize upstream JSON events without duplicate folding, prototype setters or numeric rounding. */
export const parseHarJson = (text: string): unknown => {
export const parseCaptureJson = (
text: string,
format: "HAR" | "qlog",
): unknown => {
const frames: Frame[] = [];
let result: unknown;
const valuePointer = (): string => {
@@ -29,7 +33,7 @@ export const parseHarJson = (text: string): unknown => {
if (frames.length > WEB_NETWORK_CAPTURE_LIMITS.depth)
throw new CaptureFormatError(
"input-limit",
"HAR exceeds the 64-level complete-evidence nesting budget.",
`${format} exceeds the 64-level complete-evidence nesting budget.`,
valuePointer(),
);
};
@@ -69,7 +73,7 @@ export const parseHarJson = (text: string): unknown => {
if (frame.members.has(key))
throw new CaptureFormatError(
"format",
"HAR JSON contains duplicate object members.",
`${format} JSON contains duplicate object members.`,
);
frame.pendingKey = key;
},
@@ -103,7 +107,7 @@ export const parseHarJson = (text: string): unknown => {
throw new TypeError("JSON visitor emitted an unsupported literal.");
},
onError: () => {
throw new CaptureFormatError("format", "HAR is malformed JSON.");
throw new CaptureFormatError("format", `${format} is malformed JSON.`);
},
},
{
@@ -114,3 +118,18 @@ export const parseHarJson = (text: string): unknown => {
);
return result;
};
/** UTF-8 JSON decoding skips one permitted BOM and rejects malformed bytes. */
export const decodeCaptureText = (
bytes: Uint8Array,
format: "HAR" | "qlog",
): string => {
try {
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
throw new CaptureFormatError(
"format",
`${format} is not valid UTF-8 JSON.`,
);
}
};
+21 -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,18 @@ 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;
/** Fixed offline interpretation profile, not an authenticated producer claim. */
export const QLOG_CAPTURE_PROVIDER_IDENTITY = {
id: "aioquic-qlog-json",
name: "REA aioquic qlog capture adapter",
version:
"aioquic-profile@1.5.0;qlog@0.3;jsonc-parser@3.3.1;lossless-json@4.3.1",
} as const;
+12 -8
View File
@@ -1,7 +1,8 @@
import { createHash } from "node:crypto";
import { expect, it } from "vitest";
import { historicalHar } from "../../../tests/fixtures/historicalHar.js";
import { decodeHarCapture, decodeHarText } from "./HarCapture.js";
import { decodeCaptureText } from "./CaptureJson.js";
import { decodeHarCapture } from "./HarCapture.js";
it.each([
{ values: [] },
@@ -563,18 +564,21 @@ it("ignores one leading byte-order mark, as HAR 1.2 requires of readers", () =>
const text = JSON.stringify(historicalHar());
const body = Buffer.from(text, "utf8");
const marked = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), body]);
expect(decodeHarText(marked)).toBe(text);
expect(decodeHarCapture(decodeHarText(marked), [])).toEqual(
decodeHarCapture(decodeHarText(body), []),
expect(decodeCaptureText(marked, "HAR")).toBe(text);
expect(decodeHarCapture(decodeCaptureText(marked, "HAR"), [])).toEqual(
decodeHarCapture(decodeCaptureText(body, "HAR"), []),
);
// A second mark is content, not an encoding signature.
expect(() =>
decodeHarCapture(
decodeHarText(Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), marked])),
decodeCaptureText(
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), marked]),
"HAR",
),
[],
),
).toThrow("HAR is malformed JSON.");
expect(() => decodeHarText(Buffer.from([0x7b, 0xff, 0x7d]))).toThrow(
"HAR is not valid UTF-8 JSON.",
);
expect(() =>
decodeCaptureText(Buffer.from([0x7b, 0xff, 0x7d]), "HAR"),
).toThrow("HAR is not valid UTF-8 JSON.");
});
+2 -16
View File
@@ -1,7 +1,6 @@
import { createHash } from "node:crypto";
import { TextDecoder } from "node:util";
import { isSafeNumber, LosslessNumber } from "lossless-json";
import { parseHarJson } from "./HarJson.js";
import { parseCaptureJson } from "./CaptureJson.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import {
WEB_NETWORK_CAPTURE_LIMITS,
@@ -26,25 +25,12 @@ type Projection = Pick<
"reported" | "numeric_literals" | "binary_fields" | "redactions"
>;
/**
* Decode retained HAR bytes as UTF-8. HAR 1.2 lets writers emit a byte-order
* mark and requires readers to ignore it, so one leading BOM is skipped.
*/
export const decodeHarText = (bytes: Uint8Array): string => {
try {
// ignoreBOM: false (the default) is what skips the mark; true keeps it.
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
throw new CaptureFormatError("format", "HAR is not valid UTF-8 JSON.");
}
};
/** 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 raw = parseCaptureJson(text, "HAR");
const validation = projectHar(raw, [], false);
createHarValidator()(validation.reported);
if (
-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 }),
};
}
}
+31 -16
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";
@@ -198,22 +198,37 @@ export class HistoricalCaptureDecoder {
OPERATION,
"Capture decoder changed the selected upstream profile identity.",
);
result = ok({
...reply.value,
const common = {
artifact: {
path: input.capture_path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
format: input.format,
runtime_attribution: "unknown",
runtime_attribution: "unknown" as const,
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.`,
],
});
};
if (input.format === "qlog") {
if (!("qlog" in reply.value))
throw new AnalysisOutputError(
OPERATION,
"Capture decoder omitted qlog transport facts.",
);
result = ok({ ...reply.value, ...common, format: "qlog" });
} else {
if ("qlog" in reply.value)
throw new AnalysisOutputError(
OPERATION,
"Capture decoder supplied inapplicable qlog transport facts.",
);
result = ok({ ...reply.value, ...common, format: input.format });
}
} catch (cause: unknown) {
result = err(
redactExplicitFailure(
@@ -251,13 +266,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/qlog use a ${String(NODE_CAPTURE_HEAP_LIMITS.oldGenerationMiB)} MiB Node old-generation heap`;
return NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
? "HAR/SAZ/qlog run on Bun, which does not enforce REA's V8 heap flags"
: `HAR/SAZ/qlog 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,18 @@
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.each(["saz", "qlog"] as const)(
"refuses a %s worker when the runtime has no enforceable memory bound",
async (format) => {
await expect(
new NodeCaptureAdapter(format).command("/owned/request.json"),
).rejects.toBeInstanceOf(AnalysisCapabilityUnavailableError);
},
);
+61
View File
@@ -0,0 +1,61 @@
import { fileURLToPath } from "node:url";
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
import {
NODE_CAPTURE_HEAP_ENFORCED,
HAR_CAPTURE_PROVIDER_IDENTITY,
SAZ_CAPTURE_PROVIDER_IDENTITY,
QLOG_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" | "qlog") {
this.identity =
format === "har"
? HAR_CAPTURE_PROVIDER_IDENTITY
: format === "saz"
? SAZ_CAPTURE_PROVIDER_IDENTITY
: QLOG_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 !== "har" &&
!NODE_CAPTURE_HEAP_ENFORCED &&
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES === null
)
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
"inspect_web_network_capture",
`${this.format} 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,37 @@ 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", "qlog"]).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(
decodeHarText(snapshot.bytes),
let value;
if (format !== "saz") {
const { decodeCaptureText } = await import("./CaptureJson.js");
const decoder =
format === "har"
? (await import("./HarCapture.js")).decodeHarCapture
: (await import("./QlogCapture.js")).decodeQlogCapture;
const snapshot = await readStableArtifact(
request.snapshot_path,
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
);
value = decoder(
decodeCaptureText(snapshot.bytes, format === "har" ? "HAR" : "qlog"),
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 +53,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 +62,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 });
+259
View File
@@ -0,0 +1,259 @@
import { expect, it } from "vitest";
import { decodeQlogCapture } from "./QlogCapture.js";
import { decodeCaptureText } from "./CaptureJson.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
// Synthetic format inputs exercise distinct parser semantics, not producer provenance.
const event = (frames: unknown[], name = "transport:packet_sent") => ({
name,
time: 1791819895000.25,
data: { header: { packet_type: "1RTT", packet_number: 5 }, frames },
});
const frame = (offset: number, length: number, fin = false) => ({
frame_type: "stream",
stream_id: 0,
offset,
length,
fin,
});
const capture = (events: unknown[], extra: Record<string, unknown> = {}) =>
JSON.stringify({
qlog_format: "JSON",
qlog_version: "0.3",
...extra,
traces: [
{
common_fields: { ODCID: "same" },
vantage_point: { name: "aioquic", type: "server" },
events,
},
],
});
const facts = (text: string, sensitive: string[] = []) => {
const decoded = decodeQlogCapture(text, sensitive);
if (!("qlog" in decoded)) throw new Error("qlog facet required");
return { decoded, traces: decoded.qlog.traces };
};
it("derives interval unions per trace/direction while retaining event source order and extensions", () => {
const original = JSON.parse(
capture([
event([frame(10, 10)]),
event([frame(0, 15), frame(30, 5, true)]),
event([frame(0, 4)], "transport:packet_received"),
{
name: "recovery:packet_lost",
time: 1,
data: { packet_number: 5, type: "1RTT" },
},
]),
);
original.traces.push({
...original.traces[0],
events: [event([frame(0, 3)])],
});
Object.defineProperty(original, "__proto__", {
enumerable: true,
value: { ordinary: true },
});
original.extra = "https://example.test/path?token=ordinary";
const { decoded, traces } = facts(JSON.stringify(original));
expect(traces[0]?.streams[0]).toMatchObject({
stream_id: "0",
direction: "sent",
unique_bytes: "25",
frame_length_sum: "30",
repeated_bytes: "5",
covered_ranges: [
{ start: "0", end: "20" },
{ start: "30", end: "35" },
],
reported_final_sizes: ["35"],
});
expect(traces[0]?.streams[1]).toMatchObject({
direction: "received",
unique_bytes: "4",
});
expect(traces[1]?.streams[0]).toMatchObject({ unique_bytes: "3" });
expect(traces[0]?.loss_declarations[0]).toMatchObject({
confidence: "observed",
packet_number: { state: "reported", value: "5" },
packet_number_space: "application",
});
expect(decoded.records.at(-1)?.location).toEqual({
kind: "json-pointer",
pointer: "/traces/1/events/0",
});
expect(decoded.container.reported).toMatchObject({
extra: original.extra,
["__proto__"]: { ordinary: true },
});
expect(Reflect.get(Object.prototype, "ordinary")).toBeUndefined();
});
it("keeps exact 62-bit integers and numeric lexemes without allocating exponent expansion", () => {
const text = capture([event([frame(0, 0, true)])])
.replace('"stream_id":0', '"stream_id":4611686018427387903')
.replace('"offset":0', '"offset":9007199254740993')
.replace('"length":0', '"length":1e3');
const { decoded, traces } = facts(text);
expect(traces[0]?.streams[0]).toMatchObject({
stream_id: "4611686018427387903",
unique_bytes: "1000",
reported_final_sizes: ["9007199254741993"],
});
expect(decoded.records[0]?.numeric_literals).toContainEqual({
pointer: "/data/frames/0/length",
producer_type: "json-number",
literal: "1e3",
});
expect(decoded.records[0]?.reported).toMatchObject({
data: { frames: [{ stream_id: null, offset: null, length: 1000 }] },
});
});
it("keeps incomplete fields unknown and FIN without bytes as metadata", () => {
const { traces } = facts(
capture([
event([{ frame_type: "stream", stream_id: 0, length: 5 }]),
event([frame(10, 0, true)]),
{ name: "recovery:packet_lost", time: 1, data: {} },
{
name: "extension:custom",
time: 0,
data: { body: "ordinary evidence" },
},
]),
);
expect(traces[0]?.incomplete_fact_records).toEqual([0]);
expect(traces[0]?.streams[0]).toMatchObject({
unique_bytes: "0",
covered_ranges: [],
reported_final_sizes: ["10"],
});
expect(traces[0]?.loss_declarations[0]?.packet_number.state).toBe("unknown");
});
it("excludes structural auth material and explicit normalized values without guessing extension secrecy", () => {
const text = capture([
{
name: "http:frame_parsed",
time: 1,
data: {
frame: {
frame_type: "headers",
headers: [
{ name: "authorization", value: "Bearer credential" },
{ name: ":path", value: "/?token=ordinary" },
{ name: "location", value: "https://user:pass@example.test/a" },
],
},
},
},
{
name: "transport:parameters_set",
time: 2,
data: { stateless_reset_token: "reset-credential" },
},
event([
{ frame_type: "new_connection_id", reset_token: "reset-frame" },
{ frame_type: "new_token", token: "new-token" },
frame(0, 100),
]),
{
name: "extension:custom",
time: 3,
data: {
secret: "caller-selected ordinary value",
reset_token: "extension ordinary",
},
},
]).replace('"length":100', '"length":1e2');
const { decoded, traces } = facts(text, ["100"]);
const serialized = JSON.stringify(decoded);
for (const hidden of [
"Bearer credential",
"reset-credential",
"reset-frame",
"new-token",
"100",
"user:pass",
])
expect(serialized).not.toContain(hidden);
expect(serialized).toContain("token=ordinary");
expect(serialized).toContain("caller-selected ordinary value");
expect(traces[0]?.streams).toEqual([]);
expect(traces[0]?.incomplete_fact_records).toContain(2);
});
it("hides marked ancestor keys and safe derived sums while still validating hidden subtrees", () => {
const text = capture([event([frame(0, 3), frame(3, 4)])]);
expect(facts(text, ["7"]).traces[0]?.streams).toEqual([]);
const { decoded, traces } = facts(text, ["events"]);
expect(decoded.records[0]?.reported).toBe(null);
expect(decoded.records[0]?.location.kind).toBe("unknown");
expect(traces[0]?.location.kind).toBe("unknown");
expect(traces[0]?.streams).toEqual([]);
expect(() =>
facts(text.replace('"length":3', '"length":-3'), ["events"]),
).toThrow(CaptureFormatError);
});
it.each([
"-1",
"0.5",
"4611686018427387904",
"1e1000000",
"1e-1000000",
'"3"',
"true",
])("rejects malformed or out-of-range STREAM integer %s", (literal) => {
expect(() =>
facts(
capture([event([frame(0, 3)])]).replace(
'"length":3',
`"length":${literal}`,
),
),
).toThrow(CaptureFormatError);
});
it.each([
'{"qlog_format":"JSON","qlog_format":"JSON","qlog_version":"0.3","traces":[]}',
capture([]).slice(0, -1),
capture([]) + " {}",
capture([{ name: "invalid", time: "1", data: {} }]),
capture([[1, "transport", "packet_sent", {}]]),
capture([event([{ ...frame(0, 1), fin: "true" }])]),
capture([event([{ ...frame(0, 1), offset: 4611686018427388000 }])]),
])(
"rejects malformed JSON/profile events with no partial success: %s",
(text) => {
expect(() => facts(text)).toThrow(CaptureFormatError);
},
);
it("rejects other qlog containers/versions and excessive nesting, accepts empty profiles and UTF-8 BOM", () => {
for (const extra of [{ qlog_format: "JSON-SEQ" }, { qlog_version: "0.4" }])
expect(() => facts(capture([], extra))).toThrow("Only the aioquic");
expect(() =>
facts(
capture([], {
extension: JSON.parse("[".repeat(65) + "0" + "]".repeat(65)),
}),
),
).toThrow("nesting budget");
expect(
facts('{"qlog_format":"JSON","qlog_version":"0.3","traces":[]}').traces,
).toEqual([]);
const raw = Buffer.from(capture([]));
expect(
facts(
decodeCaptureText(
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), raw]),
"qlog",
),
).decoded.total_records,
).toBe(0);
expect(() => decodeCaptureText(Buffer.from([0xff]), "qlog")).toThrow("UTF-8");
});
+503
View File
@@ -0,0 +1,503 @@
import { isSafeNumber, LosslessNumber } from "lossless-json";
import type { JsonValue } from "../../domain/jsonValue.js";
import type { QlogCaptureFacts } from "../../domain/qlogCapture.js";
import {
webNetworkCapturePayloadSchema,
type WebNetworkCaptureRecord,
} from "../../domain/webNetworkCapture.js";
import type { z } from "zod";
import { parseCaptureJson } from "./CaptureJson.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
import {
CaptureRedaction,
captureObject,
capturePointer,
} from "./CaptureRedaction.js";
import { QLOG_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
const MAX_VARINT = (1n << 62n) - 1n;
const credentials = new Set([
"authorization",
"proxy-authorization",
"cookie",
"set-cookie",
]);
type Projection = Pick<
WebNetworkCaptureRecord,
"reported" | "numeric_literals" | "binary_fields" | "redactions"
>;
type Trace = QlogCaptureFacts["traces"][number];
type Stream = Trace["streams"][number];
/** Inspect the selected aioquic JSON profile without authenticating its producer or interpreting other qlog layouts. */
export const decodeQlogCapture = (
text: string,
sensitiveValues: readonly string[],
): z.output<typeof webNetworkCapturePayloadSchema> => {
const raw = parseCaptureJson(text, "qlog");
if (!object(raw) || raw.qlog_format !== "JSON" || raw.qlog_version !== "0.3")
throw new CaptureFormatError(
"unsupported",
"Only the aioquic 1.5.0 JSON qlog 0.3 profile is supported.",
);
if (!Array.isArray(raw.traces))
return invalid("qlog must contain a traces array.", "/traces");
const traces = raw.traces.map(validateTrace);
const container = project(
{ ...raw, traces: traces.map((trace) => ({ ...trace, events: null })) },
sensitiveValues,
);
const records: WebNetworkCaptureRecord[] = [];
const facts: Trace[] = [];
const excluded = (value: string): boolean =>
sensitiveValues.some((literal) => value.includes(literal));
const ancestorsHidden = excluded("traces") || excluded("events");
for (const [traceIndex, trace] of traces.entries()) {
const tracePointer = `/traces/${traceIndex}`;
const fact = createTraceFact(
trace,
traceIndex,
sensitiveValues,
ancestorsHidden,
);
const streams = new Map<string, Stream>();
for (const [eventIndex, event] of trace.events.entries()) {
const ordinal = records.length;
const projection: Projection = ancestorsHidden
? {
reported: null,
numeric_literals: [],
binary_fields: [],
redactions: [{ pointer: "", reason: "explicit-sensitive-value" }],
}
: project(event, sensitiveValues);
records.push({
ordinal,
location: ancestorsHidden
? { kind: "unknown", reason: "explicit-sensitive-value" }
: {
kind: "json-pointer",
pointer: `${tracePointer}/events/${eventIndex}`,
},
...projection,
limitations: [
"Record ordinal is derived from trace/event source traversal, not global time order. Qlog lengths and FIN do not expose original HTTP body bytes or establish network completeness.",
],
});
collectTransportFacts(projection, ordinal, { fact, streams, excluded });
}
for (const stream of streams.values()) {
summarizeStream(stream);
const numericValues = [
stream.frame_length_sum,
stream.unique_bytes,
stream.repeated_bytes,
...stream.reported_final_sizes,
...stream.covered_ranges.flatMap((r) => [r.start, r.end]),
];
if (numericValues.some(excluded))
fact.incomplete_fact_records.push(
...stream.contributions.map((c) => c.record_ordinal),
);
else fact.streams.push(stream);
}
fact.incomplete_fact_records = [...new Set(fact.incomplete_fact_records)];
facts.push(fact);
}
return {
decoder: { ...QLOG_CAPTURE_PROVIDER_IDENTITY },
container: {
reported: container.reported,
numeric_literals: container.numeric_literals,
redactions: container.redactions,
records_pointer: null,
},
total_records: records.length,
records,
qlog: {
profile: "aioquic-1.5.0-json-0.3",
scope: "all-recorded-events-before-selection",
body_bytes: "not-reported",
clock: {
unit: "milliseconds",
domain: "unix-epoch",
basis: "selected-aioquic-profile-not-producer-authentication",
},
traces: facts,
},
};
};
const createTraceFact = (
trace: Record<string, unknown> & { events: unknown[] },
traceIndex: number,
sensitiveValues: readonly string[],
ancestorsHidden: boolean,
): Trace => {
const tracePointer = `/traces/${traceIndex}`;
const metadata = project(
{ ...trace, events: null },
sensitiveValues,
).reported;
const meta = !ancestorsHidden && object(metadata) ? metadata : null;
const common =
meta !== null && object(meta.common_fields) ? meta.common_fields : null;
const vantage =
meta !== null && object(meta.vantage_point)
? meta.vantage_point.type
: null;
return {
trace_index: traceIndex,
location: ancestorsHidden
? { kind: "unknown", reason: "explicit-sensitive-value" }
: { kind: "json-pointer", pointer: tracePointer },
event_count: trace.events.length,
odcid: typeof common?.ODCID === "string" ? common.ODCID : null,
vantage_point:
vantage === "client" || vantage === "server" ? vantage : null,
loss_declarations: [],
streams: [],
incomplete_fact_records: [],
};
};
const validateTrace = (
trace: unknown,
index: number,
): Record<string, unknown> & { events: unknown[] } => {
const pointer = `/traces/${index}`;
if (!object(trace) || !Array.isArray(trace.events))
return invalid("qlog trace must contain an events array.", pointer);
for (const [eventIndex, event] of trace.events.entries()) {
const eventPointer = `${pointer}/events/${eventIndex}`;
if (
!object(event) ||
typeof event.name !== "string" ||
!(event.time instanceof LosslessNumber) ||
!Number.isFinite(Number(event.time.value)) ||
!object(event.data)
)
invalid(
"qlog events must be objects with name, finite numeric time and object data.",
eventPointer,
);
// Validate interpretable fields on ORIGINAL values even when a declaration
// subsequently hides them. Missing fields remain meaningful unknowns.
if (event.name === "recovery:packet_lost")
unsigned(event.data.packet_number, `${eventPointer}/data/packet_number`);
if (packetEvent(event.name) && Array.isArray(event.data.frames)) {
for (const [frameIndex, frame] of event.data.frames.entries()) {
if (object(frame) && frame.frame_type === "stream") {
validateStreamFrame(
frame,
`${eventPointer}/data/frames/${frameIndex}`,
);
}
}
}
}
return { ...trace, events: trace.events };
};
const validateStreamFrame = (
frame: Record<string, unknown>,
p: string,
): void => {
unsigned(frame.stream_id, `${p}/stream_id`);
const offset = unsigned(frame.offset, `${p}/offset`);
const length = unsigned(frame.length, `${p}/length`);
if (offset !== null && length !== null && offset + length > MAX_VARINT)
invalid("qlog stream final offset exceeds the QUIC varint range.", p);
if (
frame.fin !== undefined &&
frame.fin !== null &&
typeof frame.fin !== "boolean"
)
invalid("qlog STREAM fin must be boolean when reported.", `${p}/fin`);
};
const collectTransportFacts = (
projection: Projection,
ordinal: number,
state: {
fact: Trace;
streams: Map<string, Stream>;
excluded: (value: string) => boolean;
},
): void => {
const { fact, streams, excluded } = state;
if (!object(projection.reported) || !object(projection.reported.data)) {
fact.incomplete_fact_records.push(ordinal);
return;
}
const visible = projection.reported;
const data = visible.data;
if (!object(data)) return;
const literals = new Map(
projection.numeric_literals.map((n) => [n.pointer, n.literal]),
);
const read = (value: unknown, pointer: string): bigint | null => {
const literal = literals.get(pointer);
const number = unsigned(
literal === undefined ? value : new LosslessNumber(literal),
pointer,
);
return number !== null && excluded(number.toString()) ? null : number;
};
if (visible.name === "recovery:packet_lost") {
fact.loss_declarations.push(lossDeclaration(data, ordinal, read));
}
if (!packetEvent(visible.name)) return;
if (!Array.isArray(data.frames)) {
fact.incomplete_fact_records.push(ordinal);
return;
}
for (const [frameIndex, frame] of data.frames.entries()) {
if (
!object(frame) ||
frame.frame_type === undefined ||
frame.frame_type === null
) {
fact.incomplete_fact_records.push(ordinal);
continue;
}
if (frame.frame_type !== "stream") continue;
const p = `/data/frames/${frameIndex}`;
const id = read(frame.stream_id, `${p}/stream_id`),
offset = read(frame.offset, `${p}/offset`),
length = read(frame.length, `${p}/length`);
if (id === null || offset === null || length === null) {
fact.incomplete_fact_records.push(ordinal);
continue;
}
const direction =
visible.name === "transport:packet_sent" ? "sent" : "received";
const key = `${direction}/${id}`;
let stream = streams.get(key);
if (stream === undefined) {
stream = {
stream_id: id.toString(),
direction,
confidence: "derived",
scope: "observed-stream-frame-ranges",
contributions: [],
covered_ranges: [],
unique_bytes: "0",
frame_length_sum: "0",
repeated_bytes: "0",
reported_final_sizes: [],
};
streams.set(key, stream);
}
stream.contributions.push({
record_ordinal: ordinal,
frame_index: frameIndex,
offset: offset.toString(),
length: length.toString(),
fin: typeof frame.fin === "boolean" ? frame.fin : null,
});
}
};
const lossDeclaration = (
data: Record<string, unknown>,
ordinal: number,
read: (value: unknown, pointer: string) => bigint | null,
): Trace["loss_declarations"][number] => {
const pn = read(data.packet_number, "/data/packet_number");
const type = typeof data.type === "string" ? data.type : null;
return {
record_ordinal: ordinal,
confidence: "observed",
packet_number:
pn === null
? {
state: "unknown",
reason: "omitted-null-or-redacted",
}
: { state: "reported", value: pn.toString() },
packet_type: type,
packet_number_space:
type === "initial"
? "initial"
: type === "handshake"
? "handshake"
: type === "0RTT" || type === "1RTT"
? "application"
: null,
};
};
const summarizeStream = (stream: Stream): void => {
const spans = stream.contributions
.map(
(c) => [BigInt(c.offset), BigInt(c.offset) + BigInt(c.length)] as const,
)
.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
const merged: { start: bigint; end: bigint }[] = [];
for (const [start, end] of spans) {
if (start === end) continue;
const last = merged.at(-1);
if (last !== undefined && start <= last.end)
last.end = end > last.end ? end : last.end;
else merged.push({ start, end });
}
const sum = stream.contributions.reduce((s, c) => s + BigInt(c.length), 0n);
const unique = merged.reduce((s, r) => s + r.end - r.start, 0n);
stream.covered_ranges = merged.map((r) => ({
start: r.start.toString(),
end: r.end.toString(),
}));
stream.frame_length_sum = sum.toString();
stream.unique_bytes = unique.toString();
stream.repeated_bytes = (sum - unique).toString();
stream.reported_final_sizes = [
...new Set(
stream.contributions
.filter((c) => c.fin === true)
.map((c) => (BigInt(c.offset) + BigInt(c.length)).toString()),
),
];
};
const packetEvent = (name: unknown): boolean =>
name === "transport:packet_sent" || name === "transport:packet_received";
const object = (value: unknown): value is Record<string, unknown> =>
captureObject(value) && !(value instanceof LosslessNumber);
const invalid = (message: string, pointer: string): never => {
throw new CaptureFormatError("format", message, pointer);
};
/** Canonicalize JSON integer notation exactly, checking expansion before allocation. */
const unsigned = (value: unknown, pointer: string): bigint | null => {
if (value === undefined || value === null) return null;
const literal =
value instanceof LosslessNumber
? value.value
: typeof value === "number"
? String(value)
: "";
const m = /^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/u.exec(
literal,
);
if (m === null)
return invalid("qlog QUIC integer must be a JSON number.", pointer);
const digits = `${m[2]}${m[3] ?? ""}`.replace(/^0+/u, "");
if (digits === "") return 0n;
const exponent = m[4] === undefined ? 0 : Number(m[4]);
const shift = exponent - (m[3]?.length ?? 0);
const count = digits.length + shift;
if (m[1] === "-" || !Number.isSafeInteger(shift) || count > 19 || count <= 0)
return invalid(
"qlog QUIC integer is negative, fractional or outside the 62-bit range.",
pointer,
);
if (shift < 0 && /[1-9]/u.test(digits.slice(count)))
return invalid("qlog QUIC integer is fractional.", pointer);
const canonical =
shift < 0 ? digits.slice(0, count) : digits + "0".repeat(shift);
const result = BigInt(canonical);
if (result > MAX_VARINT)
return invalid("qlog QUIC integer exceeds the 62-bit range.", pointer);
return result;
};
/** Preserve JSON values/lexemes and structurally exclude only transport credentials and declared values. */
const project = (
value: unknown,
sensitiveValues: readonly string[],
): Projection => {
const redactor = new CaptureRedaction(sensitiveValues);
const numeric_literals: Projection["numeric_literals"] = [];
const eventName = object(value) ? value.name : null;
const visit = (
item: unknown,
pointer: string,
parent?: Record<string, unknown>,
): JsonValue => {
const header =
(eventName === "http:frame_created" ||
eventName === "http:frame_parsed") &&
/^\/data\/frame\/headers\/\d+\/value$/u.test(pointer) &&
typeof parent?.name === "string";
if (
(header && credentials.has(String(parent?.name).toLowerCase())) ||
qlogToken(eventName, pointer, parent)
)
return redactor.credential(pointer);
if (item instanceof LosslessNumber) {
if (
redactor.text(item.value, pointer) === null ||
(isSafeNumber(item.value) &&
redactor.text(String(Number(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")
return redactor.text(
item,
pointer,
header &&
["location", "referer", "origin"].includes(
String(parent?.name).toLowerCase(),
),
);
if (item === null || typeof item === "boolean") return item;
if (Array.isArray(item))
return item.map((child, index) =>
visit(child, capturePointer(pointer, String(index))),
);
if (object(item))
return Object.fromEntries(
Object.entries(item).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), item)]];
}),
);
return invalid("qlog parser returned a non-JSON value.", pointer);
};
return {
reported: visit(value, ""),
numeric_literals,
binary_fields: [],
redactions: redactor.redactions,
};
};
const qlogToken = (
eventName: unknown,
pointer: string,
parent?: Record<string, unknown>,
): boolean => {
if (
packetEvent(eventName) &&
/^\/data\/frames\/\d+\/reset_token$/u.test(pointer) &&
parent?.frame_type === "new_connection_id"
)
return true;
if (
packetEvent(eventName) &&
/^\/data\/frames\/\d+\/token$/u.test(pointer) &&
parent?.frame_type === "new_token"
)
return true;
if (
eventName === "transport:parameters_set" &&
pointer === "/data/stateless_reset_token"
)
return true;
return false;
};
+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,
};
};