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:
co-authored by
zahhak
N0zoM1z0
parent
f254f5ac2b
commit
a2d8b94dd5
@@ -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`,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,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 = "",
|
||||
) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 }),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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 }),
|
||||
};
|
||||
}
|
||||
}
|
||||
+22
-13
@@ -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 });
|
||||
@@ -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();
|
||||
}
|
||||
};
|
||||
@@ -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)),
|
||||
};
|
||||
};
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user