feat(browser): inspect retained aioquic qlog JSON captures

Inspect bounded offline aioquic1.5.0 JSON qlog0.3 and page retained event/transport facts with explicit trace and stream selectors. Preserve producer coordinates, exact numeric lexemes, global pre-selection fact scope and endpoint declaration uncertainty.

Verified four real HTTP/3 recordings with an independent interval oracle, public CLI/MCP/schema parity, auth exclusions, source-deletion views and actual decoder heap exhaustion. Unverified producer platforms and qlog-specific lifecycle induction remain documented.

Co-authored-by: LuisTaffelli <86675342+LuisTaffelli@users.noreply.github.com>
Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
Luis
2026-10-13 03:24:05 +00:00
committed by GitHub
co-authored by N0zoM1z0
parent a2d8b94dd5
commit bb154d1067
30 changed files with 2206 additions and 151 deletions
+1 -1
View File
@@ -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,
);
}
@@ -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.`,
);
}
};
+8
View File
@@ -35,3 +35,11 @@ export const SAZ_CAPTURE_PROVIDER_IDENTITY = {
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 (
@@ -198,15 +198,14 @@ 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.",
@@ -214,7 +213,22 @@ export class HistoricalCaptureDecoder {
"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. ${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(
@@ -255,10 +269,10 @@ export class HistoricalCaptureDecoder {
/** 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 `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 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`;
? "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 => {
@@ -8,8 +8,11 @@ vi.mock("./CaptureRelease.js", async (original) => ({
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);
});
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);
},
);
+7 -4
View File
@@ -4,6 +4,7 @@ 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";
@@ -13,11 +14,13 @@ import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCo
export class NodeCaptureAdapter implements HistoricalCaptureFormatAdapter {
readonly identity;
readonly limitations;
constructor(readonly format: "har" | "saz") {
constructor(readonly format: "har" | "saz" | "qlog") {
this.identity =
format === "har"
? HAR_CAPTURE_PROVIDER_IDENTITY
: SAZ_CAPTURE_PROVIDER_IDENTITY;
: format === "saz"
? SAZ_CAPTURE_PROVIDER_IDENTITY
: QLOG_CAPTURE_PROVIDER_IDENTITY;
this.limitations =
format === "saz"
? [
@@ -30,14 +33,14 @@ export class NodeCaptureAdapter implements HistoricalCaptureFormatAdapter {
}
async command(requestPath: string) {
if (
this.format === "saz" &&
this.format !== "har" &&
!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.",
`${this.format} decoding requires an enforced decoder memory limit. Run REA with Node.js on this host.`,
);
return {
command: process.execPath,
+9 -6
View File
@@ -12,22 +12,25 @@ const requestSchema = z.strictObject({
/** 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 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 {
let value;
if (format === "har") {
const { decodeHarCapture, decodeHarText } =
await import("./HarCapture.js");
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 = decodeHarCapture(
decodeHarText(snapshot.bytes),
value = decoder(
decodeCaptureText(snapshot.bytes, format === "har" ? "HAR" : "qlog"),
request.sensitive_values,
);
} else {
+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;
};