feat(browser): inspect historical web network captures (#992)
* feat(browser): inspect retained HAR and mitmproxy capture evidence Add independent offline format adapters, inline CLI/MCP evidence, bounded owned decoder processes, and real producer verification. Refs #882 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): preserve capture boundaries during cancellation and decoding Honor cancellation during owned-command cleanup, retain opaque HAR extension content, and clean verifier resources on every failure path. Refs #882 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): exclude sensitive capture fields across representations Normalize known native transport URLs for both bytes and strings, including backups. Exclude explicitly sensitive text fields with null so redaction markers cannot reintroduce declared literals. Cover both provider identities in catalog conformance. Refs #882 Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis) Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) * fix(browser): exclude sensitive capture identities and bound diagnostics * fix(browser): validate excluded HAR subtrees before projection * fix(browser): distinguish capture input limits from decoder failures * fix(browser): preserve decoder failure categories * fix(browser): validate excluded native credential values * test(browser): report capture verifier assertions directly * fix(browser): classify native representation failures precisely * fix(browser): exclude URL userinfo after header whitespace * fix(browser): preserve capture evidence and failure boundaries * fix(browser): exclude sensitive literals from capture limitations * test(browser): check limitation values without JSON syntax * fix(browser): preserve acquisition integrity and exclude selection diagnostics * fix(browser): preserve capture acquisition and declaration boundaries * fix(mcp): project sensitive capture argument validation * fix: preserve capture bytes and prelaunch cancellation * fix(browser): exclude sensitive HAR record ancestry * fix(browser): preserve transport URL and parameter exclusions * fix(browser): preserve numeric redaction and canonical capture provenance * fix(browser): cover derived capture values and ownership preparation deadlines * fix(browser): exclude explicitly sensitive artifact digests * chore: regenerate generated metadata * fix(browser): reject lossy HAR member normalization * test(browser): assert the advertised unsupported-profile outcome * fix(browser): preserve JSON visitor nesting failure locations * fix(browser): exclude explicitly sensitive native source ranges --------- Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Kaoru0822
github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
parent
6e4535c101
commit
2bf3663f65
@@ -0,0 +1,101 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
|
||||
import { inspectWebNetworkCaptureInputSchema } from "../../domain/webNetworkCapture.js";
|
||||
import { historicalCaptureFailure } from "./CaptureFailures.js";
|
||||
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
|
||||
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
|
||||
|
||||
it.each(["before open", "during read"])(
|
||||
"preserves observed capture changes %s as retryable acquisition integrity failures",
|
||||
(stage) => {
|
||||
const path = "/selected/private-marker.har";
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
});
|
||||
const cause = new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact changed ${stage}: ${path}`,
|
||||
);
|
||||
const error = historicalCaptureFailure(input, cause, "capture-read");
|
||||
const projected = projectAnalysisError(error);
|
||||
expect(analysisErrorProjectionSchema.parse(projected)).toMatchObject({
|
||||
code: "artifact_changed",
|
||||
category: "integrity_mismatch",
|
||||
retryable: true,
|
||||
details: {
|
||||
operation: "inspect_web_network_capture",
|
||||
path,
|
||||
boundary: "stable-artifact-read",
|
||||
reason: cause.message,
|
||||
},
|
||||
});
|
||||
expect(projected.remediation.action).toContain("stable");
|
||||
const redacted = projectAnalysisError(
|
||||
redactExplicitFailure(error, ["private-marker", "REDACTED"]),
|
||||
);
|
||||
expect(redacted.code).toBe("artifact_changed");
|
||||
expect(JSON.stringify(redacted)).not.toContain("private-marker");
|
||||
expect(JSON.stringify(redacted)).not.toContain("REDACTED");
|
||||
},
|
||||
);
|
||||
|
||||
it("retains actual command status and both diagnostic streams when cleanup also fails", () => {
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: "/selected/input.har",
|
||||
format: "har",
|
||||
});
|
||||
const cause = new OwnedCommandFailure(
|
||||
"process",
|
||||
"Observed command failure",
|
||||
{
|
||||
stdout: { text: "original provider output", bytes: 24 },
|
||||
stderr: { text: "private-marker provider reason", bytes: 30 },
|
||||
exitCode: 2,
|
||||
signal: null,
|
||||
},
|
||||
"Observed cleanup failure",
|
||||
undefined,
|
||||
["pid:42"],
|
||||
);
|
||||
const error = historicalCaptureFailure(input, cause, "decoder");
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
previous_error: {
|
||||
failure_kind: "process",
|
||||
exit_code: 2,
|
||||
stdout: "original provider output",
|
||||
stderr: "private-marker provider reason",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const redacted = projectAnalysisError(
|
||||
redactExplicitFailure(error, ["private-marker"]),
|
||||
);
|
||||
expect(JSON.stringify(redacted)).not.toContain("private-marker");
|
||||
expect(redacted.code).toBe("cleanup_incomplete");
|
||||
});
|
||||
it.each(["io", "unavailable"] as const)(
|
||||
"keeps %s read failures separate from malformed capture input",
|
||||
(reason) => {
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: "/selected/input.har",
|
||||
format: "har",
|
||||
});
|
||||
const error = historicalCaptureFailure(
|
||||
input,
|
||||
new ArtifactReaderFailure(reason, "Observed acquisition failure"),
|
||||
"capture-read",
|
||||
);
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
category: "execution_failure",
|
||||
details: { diagnostics: { phase: "capture-read", failure_kind: reason } },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
type InspectWebNetworkCaptureInput,
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
/** Preserve the origin and typed cause of a historical capture failure. */
|
||||
export const historicalCaptureFailure = (
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
cause: unknown,
|
||||
phase: "capture-read" | "decoder",
|
||||
options?: ExecutionOptions,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof OwnedCommandFailure) {
|
||||
if (cause.cleanupFailure !== null)
|
||||
return new ProviderCleanupError(
|
||||
input.format,
|
||||
cause.resources,
|
||||
{
|
||||
reason: cause.cleanupFailure,
|
||||
previous_error: {
|
||||
failure_kind: cause.reason,
|
||||
message: cause.message,
|
||||
exit_code: cause.snapshot?.exitCode ?? null,
|
||||
signal: cause.snapshot?.signal ?? null,
|
||||
stdout: cause.snapshot?.stdout.text ?? null,
|
||||
stderr: cause.snapshot?.stderr.text ?? null,
|
||||
diagnostic_truncated: cause.snapshot?.diagnosticTruncated ?? null,
|
||||
},
|
||||
},
|
||||
{ operation: OPERATION, cause },
|
||||
);
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError(OPERATION);
|
||||
if (cause.reason === "timeout")
|
||||
return new AnalysisTimeoutError(
|
||||
OPERATION,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.timeoutMs,
|
||||
);
|
||||
if (cause.reason === "output-limit")
|
||||
return new AnalysisOutputError(OPERATION, cause.message);
|
||||
}
|
||||
if (options?.signal?.aborted) return new AnalysisCancelledError(OPERATION);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "integrity"
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
input.capture_path,
|
||||
cause.message,
|
||||
{ cause },
|
||||
);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "cancelled"
|
||||
)
|
||||
return new AnalysisCancelledError(OPERATION);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
(cause.reason === "limit" ||
|
||||
cause.reason === "format" ||
|
||||
cause.reason === "path")
|
||||
)
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
|
||||
message:
|
||||
cause.reason === "limit"
|
||||
? `${cause.message}. Select a capture within the ${WEB_NETWORK_CAPTURE_LIMITS.inputBytes}-byte input budget.`
|
||||
: cause.message,
|
||||
...(cause.reason === "limit"
|
||||
? {
|
||||
expected: {
|
||||
maximum_capture_bytes: WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
]);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(
|
||||
OPERATION,
|
||||
input.capture_path,
|
||||
cause.code,
|
||||
{ cause },
|
||||
);
|
||||
if (
|
||||
phase === "capture-read" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
["ENOENT", "ENOTDIR"].includes(String(cause.code))
|
||||
)
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: "invalid_value",
|
||||
message: `Selected capture could not be read (${String(cause.code)}): ${input.capture_path}.`,
|
||||
},
|
||||
]);
|
||||
return new ProviderAdapterError(input.format, OPERATION, {
|
||||
cause,
|
||||
diagnostics: {
|
||||
phase,
|
||||
capture_path: input.capture_path,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
...(cause instanceof ArtifactReaderFailure
|
||||
? { failure_kind: cause.reason }
|
||||
: {}),
|
||||
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
|
||||
? {
|
||||
exit_code: cause.snapshot.exitCode ?? null,
|
||||
signal: cause.snapshot.signal ?? null,
|
||||
stdout: cause.snapshot.stdout.text,
|
||||
stderr: cause.snapshot.stderr.text,
|
||||
diagnostic_truncated: cause.snapshot.diagnosticTruncated ?? false,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Expected malformed, unsupported or oversized producer data at a historical decoder boundary. */
|
||||
export class CaptureFormatError extends Error {
|
||||
constructor(
|
||||
readonly reason: "format" | "unsupported" | "input-limit",
|
||||
message: string,
|
||||
readonly pointer = "",
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { CaptureRedaction } from "./CaptureRedaction.js";
|
||||
|
||||
it.each([
|
||||
{
|
||||
value: " https://user:password@example.test/path ",
|
||||
expected: " https://example.test/path ",
|
||||
},
|
||||
{
|
||||
value: "\tHTTPS://user:password@example.test/path\t",
|
||||
expected: "\tHTTPS://example.test/path\t",
|
||||
},
|
||||
{
|
||||
value: " \t//user:password@example.test/path?token=ordinary#fragment\t ",
|
||||
expected: " \t//example.test/path?token=ordinary#fragment\t ",
|
||||
},
|
||||
{
|
||||
value: "\r\n \v\fhttps://user:password@example.test/path",
|
||||
expected: "\r\n \v\fhttps://example.test/path",
|
||||
},
|
||||
{
|
||||
value: "\u0000\u001f//user:password@example.test/path",
|
||||
expected: "\u0000\u001f//example.test/path",
|
||||
},
|
||||
])(
|
||||
"excludes URL userinfo after optional whitespace while preserving the original header text: $value",
|
||||
({ value, expected }) => {
|
||||
const redactor = new CaptureRedaction([]);
|
||||
expect(redactor.text(value, "/response/headers/0/value", true)).toBe(
|
||||
expected,
|
||||
);
|
||||
expect(redactor.redactions).toEqual([
|
||||
{ pointer: "/response/headers/0/value", reason: "transport-credential" },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the same URL-looking text in an ordinary extension", () => {
|
||||
const redactor = new CaptureRedaction([]);
|
||||
const value = " \thttps://user:password@example.test/path\t ";
|
||||
expect(redactor.text(value, "/_extension")).toBe(value);
|
||||
expect(redactor.redactions).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["\ud800", "\udfff"])(
|
||||
"does not invent replacement UTF-8 bytes for a non-scalar declaration",
|
||||
(literal) => {
|
||||
const redactor = new CaptureRedaction([literal]);
|
||||
expect(redactor.sensitiveBytes(Buffer.from("\ufffd"))).toBe(false);
|
||||
expect(redactor.text(literal, "/reported")).toBe(null);
|
||||
},
|
||||
);
|
||||
|
||||
it("matches scalar UTF-8 declarations and complete surrogate pairs exactly", () => {
|
||||
expect(
|
||||
new CaptureRedaction(["\ufffd"]).sensitiveBytes(Buffer.from("\ufffd")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
new CaptureRedaction(["\ud83d\ude00"]).sensitiveBytes(Buffer.from("😀")),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { WebNetworkCaptureRecord } from "../../domain/webNetworkCapture.js";
|
||||
|
||||
type Redaction = WebNetworkCaptureRecord["redactions"][number];
|
||||
const CREDENTIAL_HEADERS = new Set([
|
||||
"authorization",
|
||||
"proxy-authorization",
|
||||
"cookie",
|
||||
"set-cookie",
|
||||
]);
|
||||
|
||||
/** Literal redaction and structural authentication exclusions preserve unrelated local evidence. */
|
||||
export class CaptureRedaction {
|
||||
readonly redactions: Redaction[] = [];
|
||||
readonly #sensitiveByteValues: readonly Buffer[];
|
||||
constructor(readonly sensitiveValues: readonly string[]) {
|
||||
// An unpaired surrogate has no UTF-8 representation. Buffer.from would
|
||||
// invent replacement-character bytes and incorrectly discard real evidence.
|
||||
this.#sensitiveByteValues = sensitiveValues.flatMap((value) => {
|
||||
const encoded = Buffer.from(value, "utf8");
|
||||
return encoded.toString("utf8") === value ? [encoded] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Preserve exact text unless explicitly sensitive or known transport URL userinfo. */
|
||||
text(value: string, pointer: string, transportUrl = false): string | null {
|
||||
let result = value;
|
||||
if (transportUrl) {
|
||||
const match =
|
||||
/^([\x00-\x20]*(?:[a-z][a-z0-9+.-]*:)?\/\/)([^/?#]*@)/i.exec(result);
|
||||
if (match !== null) {
|
||||
result = `${match[1]}${result.slice(match[0].length)}`;
|
||||
this.redactions.push({ pointer, reason: "transport-credential" });
|
||||
}
|
||||
}
|
||||
if (
|
||||
this.sensitiveValues.some(
|
||||
(literal) => value.includes(literal) || result.includes(literal),
|
||||
)
|
||||
) {
|
||||
this.redactions.push({ pointer, reason: "explicit-sensitive-value" });
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Remove a credential field's value without retaining its digest or encoded form. */
|
||||
credential(pointer: string): null {
|
||||
this.redactions.push({ pointer, reason: "transport-credential" });
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Known HAR credential surfaces; unknown extensions are ordinary caller-selected evidence. */
|
||||
harCredential(
|
||||
pointer: string,
|
||||
parent: Readonly<Record<string, unknown>>,
|
||||
): boolean {
|
||||
return (
|
||||
(/^\/(request|response)\/headers\/\d+\/value$/.test(pointer) &&
|
||||
typeof parent.name === "string" &&
|
||||
CREDENTIAL_HEADERS.has(parent.name.toLowerCase())) ||
|
||||
/^\/(request|response)\/cookies\/\d+\/value$/.test(pointer)
|
||||
);
|
||||
}
|
||||
|
||||
/** Only actual request/redirect fields and known transport header URLs declare URL semantics. */
|
||||
harTransportUrl(
|
||||
pointer: string,
|
||||
parent?: Readonly<Record<string, unknown>>,
|
||||
): boolean {
|
||||
return (
|
||||
pointer === "/request/url" ||
|
||||
pointer === "/response/redirectURL" ||
|
||||
(/^\/(request|response)\/headers\/\d+\/value$/.test(pointer) &&
|
||||
typeof parent?.name === "string" &&
|
||||
["location", "referer", "origin"].includes(parent.name.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
/** Preserve bytes unless an explicitly declared UTF-8 literal occurs in them. */
|
||||
sensitiveBytes(bytes: Buffer): boolean {
|
||||
return this.#sensitiveByteValues.some((value) => bytes.includes(value));
|
||||
}
|
||||
}
|
||||
|
||||
/** Escape a producer property for an RFC 6901 location. */
|
||||
export const capturePointer = (parent: string, key: string): string =>
|
||||
`${parent}/${key.replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
||||
|
||||
/** Structural record guard does not duck-type number/byte sidecar markers. */
|
||||
export const captureObject = (
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Exact upstream package profile for unchanged offline HAR validation and numeric parsing. */
|
||||
export const HAR_CAPTURE_PROVIDER_IDENTITY = {
|
||||
id: "har-schema/lossless-json",
|
||||
name: "REA HAR capture adapter",
|
||||
version: "har-schema@2.0.0;jsonc-parser@3.3.1;lossless-json@4.3.1",
|
||||
} as const;
|
||||
|
||||
/** Native executable profile verified with unchanged mitmproxy raw-state decoding. */
|
||||
export const MITMPROXY_CAPTURE_PROVIDER_IDENTITY = {
|
||||
id: "mitmproxy-native-tnetstring",
|
||||
name: "REA offline native mitmproxy adapter",
|
||||
version: "12.2.3",
|
||||
} as const;
|
||||
@@ -0,0 +1,546 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { historicalHar } from "../../../tests/fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "./HarCapture.js";
|
||||
|
||||
it.each([
|
||||
{ values: [] },
|
||||
{ values: ["response"] },
|
||||
{ values: ["content"] },
|
||||
{ values: ["log"] },
|
||||
{ values: ["entries"] },
|
||||
])(
|
||||
"validates canonical base64 even when its parent property is sensitive: %j",
|
||||
({ values }) => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const input = {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
response: {
|
||||
...first.response,
|
||||
content: {
|
||||
size: 1,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "AR==",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(() => decodeHarCapture(JSON.stringify(input), values)).toThrow(
|
||||
"not valid canonical base64",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["log", "entries", "ntries"])(
|
||||
"excludes extracted record payloads beneath the marked structural property %s",
|
||||
(literal) => {
|
||||
const decoded = decodeHarCapture(JSON.stringify(historicalHar()), [
|
||||
literal,
|
||||
]);
|
||||
expect(decoded.total_records).toBeGreaterThan(0);
|
||||
expect(decoded.container.records_pointer).toBe(null);
|
||||
for (const [ordinal, record] of decoded.records.entries()) {
|
||||
expect(record).toMatchObject({
|
||||
ordinal,
|
||||
location: { kind: "unknown", reason: "explicit-sensitive-value" },
|
||||
reported: null,
|
||||
binary_fields: [],
|
||||
numeric_literals: [],
|
||||
redactions: [{ pointer: "", reason: "explicit-sensitive-value" }],
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes sensitive property identities before emitting keys and sidecar coordinates", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
...fixture,
|
||||
_extension: {
|
||||
"api-secret/~": { numeric: 123, text: "api-secret" },
|
||||
kept: 7,
|
||||
},
|
||||
log: { ...fixture.log, entries: [{ ...first, "api-secret": 42 }] },
|
||||
}),
|
||||
["api-secret"],
|
||||
);
|
||||
expect(JSON.stringify(result)).not.toContain("api-secret");
|
||||
expect(result.container.reported).toMatchObject({ _extension: { kept: 7 } });
|
||||
expect(result.container.redactions).toContainEqual({
|
||||
pointer: "/_extension",
|
||||
reason: "explicit-sensitive-value",
|
||||
scope: "property-name",
|
||||
});
|
||||
expect(result.records[0]?.redactions).toContainEqual({
|
||||
pointer: "",
|
||||
reason: "explicit-sensitive-value",
|
||||
scope: "property-name",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ value: "REDACTED", sensitive: ["REDACTED"] },
|
||||
{ value: "literal[", sensitive: ["["] },
|
||||
{ value: "before secret after", sensitive: ["secret", "REDACTED"] },
|
||||
{ value: "before secret after", sensitive: ["secret", "[RED"] },
|
||||
])(
|
||||
"excludes sensitive text without introducing replacement literals: $value",
|
||||
({ value, sensitive }) => {
|
||||
const fixture = historicalHar();
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({ ...fixture, _sensitive: value, _ordinary: "unmarked" }),
|
||||
sensitive,
|
||||
);
|
||||
expect(result.container.reported).toMatchObject({
|
||||
_sensitive: null,
|
||||
_ordinary: "unmarked",
|
||||
});
|
||||
expect(result.container.redactions).toContainEqual({
|
||||
pointer: "/_sensitive",
|
||||
reason: "explicit-sensitive-value",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes a declared literal introduced by stripping transport URL userinfo", () => {
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const url = "https://example.test/sensitive";
|
||||
const input = {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
request: {
|
||||
...entry.request,
|
||||
url: "https://user:password@example.test/sensitive",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify(input), [url]);
|
||||
expect(result.records[0]?.reported).toMatchObject({ request: { url: null } });
|
||||
});
|
||||
|
||||
it.each([
|
||||
'"_duplicate":1,"_duplicate":1',
|
||||
'"_duplicate":null,"_duplicate":null',
|
||||
'"_duplicate":{"value":1},"_duplicate":{"value":1}',
|
||||
'"_duplicate":1,"\\u005fduplicate":1',
|
||||
])(
|
||||
"rejects equal-valued duplicate JSON members before projection: %s",
|
||||
(members) => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
`"cache":{},${members}`,
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow("duplicate");
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects identical duplicate core fields before schema validation", () => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"version":"1.2"',
|
||||
'"version":"1.2","version":"1.2"',
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow("duplicate");
|
||||
});
|
||||
|
||||
it("reports an unsupported JSON schema boundary instead of dropping a producer property", () => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
'"cache":{},"_extension":{"__proto__":{"preserved":7},"constructor":"ordinary"}',
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow(
|
||||
"JSON schema boundary cannot preserve",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves Unicode, offsets, sizes, duplicate URLs and opaque extensions without inventing bytes", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
fixture.log.entries.push(structuredClone(first));
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
...fixture,
|
||||
_extension: { isLosslessNumber: true, value: "ordinary" },
|
||||
}),
|
||||
[],
|
||||
);
|
||||
expect(result.total_records).toBe(2);
|
||||
expect(result.records[0]?.reported).toEqual(fixture.log.entries[0]);
|
||||
expect(result.records[0]?.binary_fields).toEqual([]);
|
||||
expect(result.records[0]?.numeric_literals).toContainEqual({
|
||||
pointer: "/response/bodySize",
|
||||
producer_type: "json-number",
|
||||
literal: "99",
|
||||
});
|
||||
expect(result.records[1]?.location).toEqual({
|
||||
kind: "json-pointer",
|
||||
pointer: "/log/entries/1",
|
||||
});
|
||||
expect(result.container.reported).toMatchObject({
|
||||
_extension: { isLosslessNumber: true, value: "ordinary" },
|
||||
log: { entries: null },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["9007199254740993", "4740993", "99"])(
|
||||
"excludes explicitly sensitive numeric lexemes and their reported values: %s",
|
||||
(literal) => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
'"cache":{},"_big":9007199254740993',
|
||||
);
|
||||
const result = decodeHarCapture(text, [literal]);
|
||||
for (const record of result.records) {
|
||||
expect(
|
||||
record.numeric_literals.every(
|
||||
(number) => !number.literal.includes(literal),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
const pointer = literal === "99" ? "/response/bodySize" : "/_big";
|
||||
expect(result.records[0]?.redactions).toContainEqual({
|
||||
pointer,
|
||||
reason: "explicit-sensitive-value",
|
||||
});
|
||||
if (literal === "99")
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
response: { bodySize: null },
|
||||
});
|
||||
else expect(result.records[0]?.reported).toMatchObject({ _big: null });
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps unsafe extension numeric lexemes and rejects unsafe mandatory schema numbers", () => {
|
||||
const text = JSON.stringify(historicalHar());
|
||||
const result = decodeHarCapture(
|
||||
text.replace('"cache":{}', '"cache":{},"_big":9007199254740993'),
|
||||
[],
|
||||
);
|
||||
expect(result.records[0]?.numeric_literals).toContainEqual({
|
||||
pointer: "/_big",
|
||||
producer_type: "json-number",
|
||||
literal: "9007199254740993",
|
||||
});
|
||||
expect(result.records[0]?.reported).toMatchObject({ _big: null });
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
text.replace('"bodySize":0', '"bodySize":9007199254740993'),
|
||||
[],
|
||||
),
|
||||
).toThrow("HAR schema validation failed");
|
||||
});
|
||||
|
||||
it.each(["container", "record"] as const)(
|
||||
"retains %s extension content without interpreting it as an HTTP body",
|
||||
(location) => {
|
||||
const fixture = historicalHar();
|
||||
const extension = {
|
||||
response: { content: { encoding: "base64", text: "opaque extension" } },
|
||||
};
|
||||
const input =
|
||||
location === "container"
|
||||
? { ...fixture, _extension: extension }
|
||||
: {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: fixture.log.entries.map((entry) => ({
|
||||
...entry,
|
||||
_extension: extension,
|
||||
})),
|
||||
},
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify(input), []);
|
||||
expect(
|
||||
location === "container"
|
||||
? result.container.reported
|
||||
: result.records[0]?.reported,
|
||||
).toMatchObject({ _extension: extension });
|
||||
expect(result.records[0]?.binary_fields).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains valid base64 bytes independently of declared sizes", () => {
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const text = JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
response: {
|
||||
...entry.response,
|
||||
content: {
|
||||
size: 999,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "AP9B\n",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = decodeHarCapture(text, []);
|
||||
expect(result.records[0]?.binary_fields[0]).toMatchObject({
|
||||
pointer: "/response/content/text",
|
||||
state: "retained",
|
||||
content_base64: "AP9B",
|
||||
bytes: 3,
|
||||
});
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
response: { content: { size: 999, text: "AP9B\n" } },
|
||||
});
|
||||
expect(() => decodeHarCapture(text.replace("AP9B", "AR=="), [])).toThrow(
|
||||
"not valid canonical base64",
|
||||
);
|
||||
});
|
||||
|
||||
it("redacts actual authentication fields and explicit binary values while preserving similarly named extensions", () => {
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const raw = {
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
request: {
|
||||
...entry.request,
|
||||
url: "https://user:password@example.test/a?token=ordinary#fragment",
|
||||
headers: [
|
||||
{ name: "Authorization", value: "Bearer transport-secret" },
|
||||
{ name: "X-Test", value: "a" },
|
||||
{ name: "X-Test", value: "b" },
|
||||
],
|
||||
cookies: [{ name: "session", value: "cookie-secret" }],
|
||||
},
|
||||
response: {
|
||||
...entry.response,
|
||||
content: {
|
||||
size: 5,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: Buffer.from("chosen-private").toString("base64"),
|
||||
},
|
||||
},
|
||||
_extension: {
|
||||
response: {
|
||||
headers: [{ name: "Authorization", value: "ordinary-extension" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify(raw), ["chosen-private"]);
|
||||
const output = JSON.stringify(result);
|
||||
for (const secret of [
|
||||
"password",
|
||||
"transport-secret",
|
||||
"cookie-secret",
|
||||
Buffer.from("chosen-private").toString("base64"),
|
||||
])
|
||||
expect(output).not.toContain(secret);
|
||||
expect(output).toContain("token=ordinary#fragment");
|
||||
expect(output).toContain("ordinary-extension");
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
request: {
|
||||
headers: [
|
||||
{ name: "Authorization", value: null },
|
||||
{ name: "X-Test", value: "a" },
|
||||
{ name: "X-Test", value: "b" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.records[0]?.binary_fields[0]).toMatchObject({
|
||||
state: "redacted",
|
||||
sha256: null,
|
||||
content_base64: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"{",
|
||||
'{"log":{},"log":{}}',
|
||||
JSON.stringify({ log: { version: "1.2", entries: [] } }),
|
||||
])("rejects malformed producer data %s", (text) => {
|
||||
expect(() => decodeHarCapture(text, [])).toThrow();
|
||||
});
|
||||
|
||||
it("preserves observed SaveHar null post-data without broadening arbitrary HAR producers", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const log = {
|
||||
...fixture.log,
|
||||
creator: { name: "mitmproxy", version: "12.2.3" },
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
request: {
|
||||
...first.request,
|
||||
postData: { mimeType: "text/plain", text: null },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
decodeHarCapture(JSON.stringify({ log }), []).records[0]?.reported,
|
||||
).toMatchObject({ request: { postData: { text: null } } });
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: { ...log, creator: { name: "other", version: "1" } },
|
||||
}),
|
||||
[],
|
||||
),
|
||||
).toThrow("HAR schema validation failed");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"c2VjcmV0",
|
||||
"c2Vj",
|
||||
createHash("sha256").update("secret").digest("hex"),
|
||||
])(
|
||||
"excludes sensitive derived byte representations from spaced HAR text: %s",
|
||||
(literal) => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
response: {
|
||||
...first.response,
|
||||
content: {
|
||||
size: 6,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "c2 VjcmV0",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
[literal],
|
||||
);
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
response: { content: { text: null } },
|
||||
});
|
||||
expect(result.records[0]?.binary_fields).toContainEqual({
|
||||
pointer: "/response/content/text",
|
||||
representation: "har-base64-content",
|
||||
state: "redacted",
|
||||
content_base64: null,
|
||||
bytes: null,
|
||||
sha256: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes a declared literal in encoded HAR text from its binary sidecar too", () => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const log = {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
response: {
|
||||
...first.response,
|
||||
content: {
|
||||
size: 3,
|
||||
mimeType: "application/octet-stream",
|
||||
encoding: "base64",
|
||||
text: "AP9B",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = decodeHarCapture(JSON.stringify({ log }), ["AP9B"]);
|
||||
expect(JSON.stringify(result)).not.toContain("AP9B");
|
||||
expect(result.records[0]?.binary_fields[0]?.state).toBe("redacted");
|
||||
});
|
||||
|
||||
it("rejects excessive extension nesting instead of returning a partial capture", () => {
|
||||
let extension: unknown = null;
|
||||
for (let index = 0; index < 66; index++) extension = { child: extension };
|
||||
expect(() =>
|
||||
decodeHarCapture(
|
||||
JSON.stringify({ ...historicalHar(), _extension: extension }),
|
||||
[],
|
||||
),
|
||||
).toThrow("nesting budget");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "Location", side: "response" as const },
|
||||
{ name: "Referer", side: "request" as const },
|
||||
{ name: "Origin", side: "request" as const },
|
||||
])(
|
||||
"excludes leading-OWS userinfo from a producer $name header",
|
||||
({ name, side }) => {
|
||||
const fixture = historicalHar();
|
||||
const first = fixture.log.entries[0];
|
||||
if (first === undefined) throw new Error("fixture missing");
|
||||
const value =
|
||||
" \tHTTPS://user:password@example.test/path?token=ordinary#fragment\t ";
|
||||
const result = decodeHarCapture(
|
||||
JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...first,
|
||||
[side]: { ...first[side], headers: [{ name, value }] },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
expect(result.records[0]?.reported).toMatchObject({
|
||||
[side]: {
|
||||
headers: [
|
||||
{
|
||||
name,
|
||||
value: " \tHTTPS://example.test/path?token=ordinary#fragment\t ",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.records[0]?.redactions).toContainEqual({
|
||||
pointer: `/${side}/headers/0/value`,
|
||||
reason: "transport-credential",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,244 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isSafeNumber, LosslessNumber } from "lossless-json";
|
||||
import { parseHarJson } from "./HarJson.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
type WebNetworkCapture,
|
||||
type WebNetworkCaptureRecord,
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
import {
|
||||
CaptureRedaction,
|
||||
captureObject,
|
||||
capturePointer,
|
||||
} from "./CaptureRedaction.js";
|
||||
import { createHarValidator } from "./HarSchema.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
|
||||
|
||||
type DecodedCapture = Omit<
|
||||
WebNetworkCapture,
|
||||
"artifact" | "format" | "runtime_attribution" | "limitations"
|
||||
>;
|
||||
type Projection = Pick<
|
||||
WebNetworkCaptureRecord,
|
||||
"reported" | "numeric_literals" | "binary_fields" | "redactions"
|
||||
>;
|
||||
|
||||
/** Decode a retained HAR with exact numeric lexemes and unchanged upstream schema validation. */
|
||||
export const decodeHarCapture = (
|
||||
text: string,
|
||||
sensitiveValues: readonly string[],
|
||||
): DecodedCapture => {
|
||||
const raw = parseHarJson(text);
|
||||
const validation = projectHar(raw, [], false);
|
||||
createHarValidator()(validation.reported);
|
||||
if (
|
||||
!captureObject(raw) ||
|
||||
!captureObject(raw.log) ||
|
||||
!Array.isArray(raw.log.entries)
|
||||
)
|
||||
throw new CaptureFormatError("format", "HAR must contain log.entries.");
|
||||
if (raw.log.version !== "1.2")
|
||||
throw new CaptureFormatError(
|
||||
"unsupported",
|
||||
"Only the pinned HAR 1.2 schema profile is supported.",
|
||||
"/log/version",
|
||||
);
|
||||
const entries = raw.log.entries;
|
||||
const recordsExcluded = ["log", "entries"].some((key) =>
|
||||
sensitiveValues.some((literal) => key.includes(literal)),
|
||||
);
|
||||
const container = projectHar(
|
||||
{ ...raw, log: { ...raw.log, entries: null } },
|
||||
sensitiveValues,
|
||||
true,
|
||||
);
|
||||
const records = entries.map((entry, ordinal): WebNetworkCaptureRecord => {
|
||||
// Validate each original record even when a structural ancestor excludes it.
|
||||
const projected = projectHar(entry, sensitiveValues, true);
|
||||
const projection: Projection = recordsExcluded
|
||||
? {
|
||||
reported: null,
|
||||
numeric_literals: [],
|
||||
binary_fields: [],
|
||||
redactions: [{ pointer: "", reason: "explicit-sensitive-value" }],
|
||||
}
|
||||
: projected;
|
||||
return {
|
||||
ordinal,
|
||||
location: recordsExcluded
|
||||
? { kind: "unknown", reason: "explicit-sensitive-value" }
|
||||
: { kind: "json-pointer", pointer: `/log/entries/${ordinal}` },
|
||||
...projection,
|
||||
limitations: [
|
||||
"HAR text is producer-decoded Unicode. Original body bytes remain unknown unless content explicitly uses valid base64; declared sizes are preserved independently of retained bytes. mitmproxy 12.2.3 SaveHar may report null optional postData.text; that null is retained and omitted only from the upstream validation copy.",
|
||||
...(recordsExcluded
|
||||
? [
|
||||
"This record's payload and sidecars are excluded because its structural ancestor property was explicitly marked sensitive.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
});
|
||||
return {
|
||||
decoder: { ...HAR_CAPTURE_PROVIDER_IDENTITY },
|
||||
container: {
|
||||
reported: container.reported,
|
||||
numeric_literals: container.numeric_literals,
|
||||
redactions: container.redactions,
|
||||
records_pointer: recordsExcluded ? null : "/log/entries",
|
||||
},
|
||||
total_records: records.length,
|
||||
records,
|
||||
};
|
||||
};
|
||||
|
||||
const projectHar = (
|
||||
value: unknown,
|
||||
sensitiveValues: readonly string[],
|
||||
redact: boolean,
|
||||
): Projection => {
|
||||
const redactor = new CaptureRedaction(sensitiveValues);
|
||||
const numeric_literals: Projection["numeric_literals"] = [];
|
||||
const binary_fields: Projection["binary_fields"] = [];
|
||||
const visit = (
|
||||
item: unknown,
|
||||
pointer: string,
|
||||
depth: number,
|
||||
parent?: Readonly<Record<string, unknown>>,
|
||||
): JsonValue => {
|
||||
if (depth > WEB_NETWORK_CAPTURE_LIMITS.depth)
|
||||
throw new CaptureFormatError(
|
||||
"input-limit",
|
||||
"HAR exceeds the 64-level complete-evidence nesting budget.",
|
||||
pointer,
|
||||
);
|
||||
if (
|
||||
redact &&
|
||||
parent !== undefined &&
|
||||
redactor.harCredential(pointer, parent)
|
||||
)
|
||||
return redactor.credential(pointer);
|
||||
if (item instanceof LosslessNumber) {
|
||||
if (redact && redactor.text(item.value, pointer) === null) return null;
|
||||
numeric_literals.push({
|
||||
pointer,
|
||||
producer_type: "json-number",
|
||||
literal: item.value,
|
||||
});
|
||||
return isSafeNumber(item.value) ? Number(item.value) : null;
|
||||
}
|
||||
if (typeof item === "string") {
|
||||
if (
|
||||
redact &&
|
||||
pointer === "/response/content/text" &&
|
||||
parent?.encoding === "base64"
|
||||
) {
|
||||
const bytes = decodeHarBase64(item, pointer);
|
||||
const contentBase64 = bytes.toString("base64");
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
const hidden =
|
||||
redactor.sensitiveBytes(bytes) ||
|
||||
sensitiveValues.some(
|
||||
(literal) =>
|
||||
item.includes(literal) ||
|
||||
contentBase64.includes(literal) ||
|
||||
sha256.includes(literal),
|
||||
);
|
||||
binary_fields.push(
|
||||
hidden
|
||||
? {
|
||||
pointer,
|
||||
representation: "har-base64-content",
|
||||
state: "redacted",
|
||||
content_base64: null,
|
||||
bytes: null,
|
||||
sha256: null,
|
||||
}
|
||||
: {
|
||||
pointer,
|
||||
representation: "har-base64-content",
|
||||
state: "retained",
|
||||
content_base64: contentBase64,
|
||||
bytes: bytes.length,
|
||||
sha256,
|
||||
},
|
||||
);
|
||||
if (hidden) {
|
||||
redactor.redactions.push({
|
||||
pointer,
|
||||
reason: "explicit-sensitive-value",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return redact
|
||||
? redactor.text(
|
||||
item,
|
||||
pointer,
|
||||
redactor.harTransportUrl(pointer, parent),
|
||||
)
|
||||
: item;
|
||||
}
|
||||
if (item === null || typeof item === "boolean") return item;
|
||||
if (Array.isArray(item))
|
||||
return item.map((child, index) =>
|
||||
visit(child, capturePointer(pointer, String(index)), depth + 1),
|
||||
);
|
||||
if (captureObject(item))
|
||||
return Object.fromEntries(
|
||||
Object.entries(item).flatMap(([key, child]) => {
|
||||
if (
|
||||
redact &&
|
||||
sensitiveValues.some((literal) => key.includes(literal))
|
||||
) {
|
||||
const beforeNumbers = numeric_literals.length;
|
||||
const beforeBinaries = binary_fields.length;
|
||||
const beforeRedactions = redactor.redactions.length;
|
||||
visit(child, capturePointer(pointer, key), depth + 1, item);
|
||||
numeric_literals.splice(beforeNumbers);
|
||||
binary_fields.splice(beforeBinaries);
|
||||
redactor.redactions.splice(beforeRedactions);
|
||||
redactor.redactions.push({
|
||||
pointer,
|
||||
reason: "explicit-sensitive-value",
|
||||
scope: "property-name",
|
||||
});
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
[key, visit(child, capturePointer(pointer, key), depth + 1, item)],
|
||||
];
|
||||
}),
|
||||
);
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR parser returned a non-JSON value.",
|
||||
pointer,
|
||||
);
|
||||
};
|
||||
return {
|
||||
reported: visit(value, "", 0),
|
||||
numeric_literals,
|
||||
binary_fields,
|
||||
redactions: redactor.redactions,
|
||||
};
|
||||
};
|
||||
|
||||
const decodeHarBase64 = (value: string, pointer: string): Buffer => {
|
||||
const compact = value.replace(/[\t\n\r ]/g, "");
|
||||
const bytes = Buffer.from(compact, "base64");
|
||||
if (
|
||||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
|
||||
compact,
|
||||
) ||
|
||||
bytes.toString("base64") !== compact
|
||||
)
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR content declares base64 but its text is not valid canonical base64 (ASCII whitespace is allowed).",
|
||||
pointer,
|
||||
);
|
||||
return bytes;
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
|
||||
|
||||
/** HAR's parser/schema packages run in one bounded Node heap, without network or target execution. */
|
||||
export class HarCaptureAdapter implements HistoricalCaptureFormatAdapter {
|
||||
readonly format = "har";
|
||||
readonly identity = HAR_CAPTURE_PROVIDER_IDENTITY;
|
||||
async command(
|
||||
requestPath: string,
|
||||
): Promise<{ command: string; arguments: readonly string[] }> {
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"--max-old-space-size=192",
|
||||
"--max-semi-space-size=8",
|
||||
"--v8-pool-size=1",
|
||||
"--single-threaded",
|
||||
fileURLToPath(new URL("./HarCaptureProcess.js", import.meta.url)),
|
||||
requestPath,
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { z } from "zod";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
import { decodeHarCapture } from "./HarCapture.js";
|
||||
|
||||
const requestSchema = z.strictObject({
|
||||
snapshot_path: z.string(),
|
||||
reply_path: z.string(),
|
||||
sensitive_values: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
/** Decode untrusted HAR in an owned, bounded heap rather than the long-lived MCP process. */
|
||||
const main = async (): Promise<void> => {
|
||||
const request = requestSchema.parse(
|
||||
JSON.parse(await readFile(process.argv[2] ?? "", "utf8")),
|
||||
);
|
||||
let reply: unknown;
|
||||
try {
|
||||
const snapshot = await readStableArtifact(
|
||||
request.snapshot_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
);
|
||||
let text: string;
|
||||
try {
|
||||
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
||||
snapshot.bytes,
|
||||
);
|
||||
} catch {
|
||||
throw new CaptureFormatError("format", "HAR is not valid UTF-8 JSON.");
|
||||
}
|
||||
reply = {
|
||||
ok: true,
|
||||
value: decodeHarCapture(text, request.sensitive_values),
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
reply =
|
||||
cause instanceof CaptureFormatError
|
||||
? {
|
||||
ok: false,
|
||||
reason: cause.reason,
|
||||
message: cause.message,
|
||||
pointer: cause.pointer,
|
||||
}
|
||||
: {
|
||||
ok: false,
|
||||
reason: "decoder",
|
||||
message: `HAR decoder failed unexpectedly (${cause instanceof Error ? cause.name : "unknown exception"}).`,
|
||||
pointer: "",
|
||||
};
|
||||
}
|
||||
let text = JSON.stringify(reply);
|
||||
if (Buffer.byteLength(text) > WEB_NETWORK_CAPTURE_LIMITS.outputBytes)
|
||||
text = JSON.stringify({
|
||||
ok: false,
|
||||
reason: "limit",
|
||||
message: "HAR reply exceeds the complete-evidence output budget.",
|
||||
pointer: "",
|
||||
});
|
||||
await writeFile(request.reply_path, text, { flag: "wx", mode: 0o600 });
|
||||
};
|
||||
await main();
|
||||
@@ -0,0 +1,118 @@
|
||||
import { visit } from "jsonc-parser";
|
||||
import { LosslessNumber } from "lossless-json";
|
||||
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
|
||||
type Frame =
|
||||
| {
|
||||
kind: "object";
|
||||
pointer: string;
|
||||
members: Map<string, unknown>;
|
||||
pendingKey?: string;
|
||||
}
|
||||
| { kind: "array"; pointer: string; items: unknown[] };
|
||||
|
||||
/** Materialize upstream JSON events without duplicate folding, prototype setters or numeric rounding. */
|
||||
export const parseHarJson = (text: string): unknown => {
|
||||
const frames: Frame[] = [];
|
||||
let result: unknown;
|
||||
const valuePointer = (): string => {
|
||||
const parent = frames.at(-1);
|
||||
if (parent === undefined) return "";
|
||||
if (parent.kind === "array")
|
||||
return `${parent.pointer}/${parent.items.length}`;
|
||||
return parent.pendingKey === undefined
|
||||
? parent.pointer
|
||||
: `${parent.pointer}/${parent.pendingKey.replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
||||
};
|
||||
const checkDepth = (): void => {
|
||||
if (frames.length > WEB_NETWORK_CAPTURE_LIMITS.depth)
|
||||
throw new CaptureFormatError(
|
||||
"input-limit",
|
||||
"HAR exceeds the 64-level complete-evidence nesting budget.",
|
||||
valuePointer(),
|
||||
);
|
||||
};
|
||||
const append = (value: unknown): void => {
|
||||
const parent = frames.at(-1);
|
||||
if (parent === undefined) result = value;
|
||||
else if (parent.kind === "array") parent.items.push(value);
|
||||
else {
|
||||
if (parent.pendingKey === undefined)
|
||||
throw new TypeError(
|
||||
"JSON visitor omitted an object property identity.",
|
||||
);
|
||||
parent.members.set(parent.pendingKey, value);
|
||||
delete parent.pendingKey;
|
||||
}
|
||||
};
|
||||
visit(
|
||||
text,
|
||||
{
|
||||
onObjectBegin: () => {
|
||||
checkDepth();
|
||||
frames.push({
|
||||
kind: "object",
|
||||
pointer: valuePointer(),
|
||||
members: new Map(),
|
||||
});
|
||||
},
|
||||
onObjectProperty: (key) => {
|
||||
if (key === "__proto__")
|
||||
throw new CaptureFormatError(
|
||||
"unsupported",
|
||||
"HAR object contains a __proto__ member that the current JSON schema boundary cannot preserve.",
|
||||
);
|
||||
const frame = frames.at(-1);
|
||||
if (frame?.kind !== "object")
|
||||
throw new TypeError(
|
||||
"JSON visitor emitted a property outside an object.",
|
||||
);
|
||||
if (frame.members.has(key))
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
"HAR JSON contains duplicate object members.",
|
||||
);
|
||||
frame.pendingKey = key;
|
||||
},
|
||||
onObjectEnd: () => {
|
||||
const frame = frames.pop();
|
||||
if (frame?.kind !== "object")
|
||||
throw new TypeError("JSON visitor ended an unexpected object.");
|
||||
append(Object.fromEntries(frame.members));
|
||||
},
|
||||
onArrayBegin: () => {
|
||||
checkDepth();
|
||||
frames.push({ kind: "array", pointer: valuePointer(), items: [] });
|
||||
},
|
||||
onArrayEnd: () => {
|
||||
const frame = frames.pop();
|
||||
if (frame?.kind !== "array")
|
||||
throw new TypeError("JSON visitor ended an unexpected array.");
|
||||
append(frame.items);
|
||||
},
|
||||
onLiteralValue: (value: unknown, offset, length) => {
|
||||
checkDepth();
|
||||
if (typeof value === "number")
|
||||
append(new LosslessNumber(text.slice(offset, offset + length)));
|
||||
else if (
|
||||
value === null ||
|
||||
typeof value === "boolean" ||
|
||||
typeof value === "string"
|
||||
)
|
||||
append(value);
|
||||
else
|
||||
throw new TypeError("JSON visitor emitted an unsupported literal.");
|
||||
},
|
||||
onError: () => {
|
||||
throw new CaptureFormatError("format", "HAR is malformed JSON.");
|
||||
},
|
||||
},
|
||||
{
|
||||
disallowComments: true,
|
||||
allowTrailingComma: false,
|
||||
allowEmptyContent: false,
|
||||
},
|
||||
);
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { Ajv } from "ajv";
|
||||
import { z } from "zod";
|
||||
import { CaptureFormatError } from "./CaptureFormatError.js";
|
||||
|
||||
/** Validate using the unchanged, pinned upstream HAR 1.2 draft-06 schemas. */
|
||||
export const createHarValidator = (): ((value: unknown) => void) => {
|
||||
const require = createRequire(import.meta.url);
|
||||
const schemas = z
|
||||
.record(z.string(), z.record(z.string(), z.unknown()))
|
||||
.parse(require("har-schema"));
|
||||
const ajv = new Ajv({ strict: false, allErrors: false, ownProperties: true });
|
||||
ajv.addMetaSchema(require("ajv/dist/refs/json-schema-draft-06.json"));
|
||||
const plugin: unknown = require("ajv-formats");
|
||||
if (typeof plugin !== "function")
|
||||
throw new Error("Pinned AJV formats plugin is unavailable");
|
||||
plugin(ajv);
|
||||
for (const schema of Object.values(schemas)) ajv.addSchema(schema);
|
||||
const validate = ajv.getSchema("har.json#");
|
||||
if (validate === undefined)
|
||||
throw new Error("Pinned HAR root schema is unavailable");
|
||||
return (value) => {
|
||||
allowMitmproxyAbsentPostData(value);
|
||||
if (!validate(value)) {
|
||||
const error = validate.errors?.[0];
|
||||
throw new CaptureFormatError(
|
||||
"format",
|
||||
`HAR schema validation failed: ${error?.keyword ?? "unknown constraint"}.`,
|
||||
error?.instancePath ?? "",
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** Observed SaveHar 12.2.3 compatibility: validate omitted optional text while retaining reported null. */
|
||||
const allowMitmproxyAbsentPostData = (value: unknown): void => {
|
||||
const parsed = z
|
||||
.object({
|
||||
log: z.object({
|
||||
creator: z.object({
|
||||
name: z.literal("mitmproxy"),
|
||||
version: z.literal("12.2.3"),
|
||||
}),
|
||||
entries: z.array(z.unknown()),
|
||||
}),
|
||||
})
|
||||
.safeParse(value);
|
||||
if (
|
||||
!parsed.success ||
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!("log" in value)
|
||||
)
|
||||
return;
|
||||
const log = value.log;
|
||||
if (
|
||||
typeof log !== "object" ||
|
||||
log === null ||
|
||||
!("entries" in log) ||
|
||||
!Array.isArray(log.entries)
|
||||
)
|
||||
return;
|
||||
for (const entry of log.entries) {
|
||||
const candidate: unknown = entry;
|
||||
if (
|
||||
typeof candidate !== "object" ||
|
||||
candidate === null ||
|
||||
!("request" in candidate)
|
||||
)
|
||||
continue;
|
||||
const request = candidate.request;
|
||||
if (
|
||||
typeof request !== "object" ||
|
||||
request === null ||
|
||||
!("postData" in request)
|
||||
)
|
||||
continue;
|
||||
const body = request.postData;
|
||||
if (
|
||||
typeof body === "object" &&
|
||||
body !== null &&
|
||||
"text" in body &&
|
||||
body.text === null
|
||||
)
|
||||
delete body.text;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,250 @@
|
||||
import { historicalCaptureFailure } from "./CaptureFailures.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { z } from "zod";
|
||||
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
WEB_NETWORK_CAPTURE_LIMITS,
|
||||
webNetworkCaptureSchema,
|
||||
type InspectWebNetworkCaptureInput,
|
||||
type WebNetworkCapture,
|
||||
} from "../../domain/webNetworkCapture.js";
|
||||
import { runOwnedCommand } from "../../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
|
||||
import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
|
||||
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
const decodedSchema = webNetworkCaptureSchema.omit({
|
||||
artifact: true,
|
||||
format: true,
|
||||
runtime_attribution: true,
|
||||
limitations: true,
|
||||
});
|
||||
const replySchema = z.discriminatedUnion("ok", [
|
||||
z.strictObject({ ok: z.literal(true), value: decodedSchema }),
|
||||
z.strictObject({
|
||||
ok: z.literal(false),
|
||||
reason: z.enum([
|
||||
"format",
|
||||
"unsupported",
|
||||
"input-limit",
|
||||
"resource-limit",
|
||||
"decoder",
|
||||
"limit",
|
||||
]),
|
||||
message: z.string(),
|
||||
pointer: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** One owned snapshot/process/root lifecycle for replaceable historical format decoders. */
|
||||
export class HistoricalCaptureDecoder {
|
||||
constructor(
|
||||
readonly adapters: readonly HistoricalCaptureFormatAdapter[],
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv>,
|
||||
readonly createRuntime: () => Promise<
|
||||
Pick<PrivateRuntimeRoot, "path" | "close">
|
||||
> = () => PrivateRuntimeRoot.create({ prefix: "rea-web-capture-" }),
|
||||
) {}
|
||||
|
||||
/** Snapshot the selected artifact, decode it offline, and release private credentials and processes. */
|
||||
async inspect(
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>> {
|
||||
let runtime: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
|
||||
let result: Result<WebNetworkCapture, AnalysisError>;
|
||||
let phase: "capture-read" | "decoder" = "capture-read";
|
||||
try {
|
||||
const adapter = this.adapters.find(
|
||||
(candidate) => candidate.format === input.format,
|
||||
);
|
||||
if (adapter === undefined)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
input.format,
|
||||
OPERATION,
|
||||
"No adapter is configured for the selected capture format.",
|
||||
);
|
||||
const snapshot = await readStableArtifact(
|
||||
input.capture_path,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "decoder";
|
||||
runtime = await this.createRuntime();
|
||||
const snapshotPath = join(runtime.path, "capture.snapshot");
|
||||
const requestPath = join(runtime.path, "request.json");
|
||||
const replyPath = join(runtime.path, "reply.json");
|
||||
await writeFile(snapshotPath, snapshot.bytes, {
|
||||
mode: 0o600,
|
||||
flag: "wx",
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
await writeFile(
|
||||
requestPath,
|
||||
JSON.stringify({
|
||||
snapshot_path: snapshotPath,
|
||||
reply_path: replyPath,
|
||||
sensitive_values: input.sensitive_values,
|
||||
}),
|
||||
{ mode: 0o600, flag: "wx" },
|
||||
);
|
||||
const command = await adapter.command(requestPath, runtime.path);
|
||||
const environment: NodeJS.ProcessEnv = {
|
||||
...this.environment,
|
||||
UV_THREADPOOL_SIZE: "1",
|
||||
};
|
||||
delete environment.NODE_OPTIONS;
|
||||
await runOwnedCommand(
|
||||
{
|
||||
...command,
|
||||
runId: `rea-web-capture-${randomUUID()}`,
|
||||
cwd: runtime.path,
|
||||
hostEnvironment: environment,
|
||||
},
|
||||
{
|
||||
timeoutMs: WEB_NETWORK_CAPTURE_LIMITS.timeoutMs,
|
||||
diagnosticBytes: 1024 * 1024,
|
||||
},
|
||||
options?.signal === undefined ? {} : { signal: options.signal },
|
||||
);
|
||||
let reply: z.output<typeof replySchema>;
|
||||
try {
|
||||
const replyFile = await readStableArtifact(
|
||||
replyPath,
|
||||
WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
reply = replySchema.parse(JSON.parse(replyFile.bytes.toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
if (options?.signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION);
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
`Owned capture decoder reply failed for ${input.capture_path}: ${replyFailureReason(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
if (!reply.ok) {
|
||||
if (reply.reason === "format")
|
||||
throw new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["capture_path", reply.pointer],
|
||||
reason: "invalid_format",
|
||||
message: reply.message,
|
||||
},
|
||||
]);
|
||||
if (reply.reason === "input-limit")
|
||||
throw new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["capture_path", reply.pointer],
|
||||
reason: "out_of_range",
|
||||
message: reply.message,
|
||||
expected: {
|
||||
maximum_capture_nesting: WEB_NETWORK_CAPTURE_LIMITS.depth,
|
||||
},
|
||||
},
|
||||
]);
|
||||
if (reply.reason === "decoder" || reply.reason === "resource-limit")
|
||||
throw new ProviderAdapterError(input.format, OPERATION, {
|
||||
diagnostics: {
|
||||
phase: "decoder",
|
||||
failure_kind: reply.reason,
|
||||
reason: reply.message,
|
||||
pointer: reply.pointer,
|
||||
},
|
||||
});
|
||||
if (reply.reason === "unsupported")
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
input.format,
|
||||
OPERATION,
|
||||
reply.message,
|
||||
);
|
||||
throw new AnalysisOutputError(OPERATION, reply.message);
|
||||
}
|
||||
if (
|
||||
reply.value.decoder.id !== adapter.identity.id ||
|
||||
reply.value.decoder.name !== adapter.identity.name ||
|
||||
reply.value.decoder.version !== adapter.identity.version
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture decoder changed the selected upstream profile identity.",
|
||||
);
|
||||
result = ok({
|
||||
...reply.value,
|
||||
artifact: {
|
||||
path: input.capture_path,
|
||||
sha256: snapshot.sha256,
|
||||
bytes: snapshot.bytes.length,
|
||||
},
|
||||
format: input.format,
|
||||
runtime_attribution: "unknown",
|
||||
limitations: [
|
||||
"This is retained producer evidence, without live browser transaction IDs, scenario provenance, execution attribution or deployment authenticity. Recorded URLs are never fetched.",
|
||||
"Every record is decoded before selection; no partial success is returned on malformed input or a resource limit.",
|
||||
"Known authentication headers/cookies and explicitly marked literal values are excluded. Unknown extension names do not establish sensitivity.",
|
||||
"A 32 MiB input, 96 MiB reply and 64-level nesting budget bound complete evidence. HAR uses a 192 MiB Node old-generation heap; native decoding uses a 768 MiB Linux address-space limit. Each owned command has a 30-second deadline with independent cleanup.",
|
||||
],
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
result = err(
|
||||
redactExplicitFailure(
|
||||
historicalCaptureFailure(input, cause, phase, options),
|
||||
input.sensitive_values,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (runtime !== undefined) {
|
||||
try {
|
||||
await runtime.close();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
redactExplicitFailure(
|
||||
new ProviderCleanupError(
|
||||
input.format,
|
||||
[runtime.path],
|
||||
{
|
||||
capture_path: input.capture_path,
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ operation: OPERATION },
|
||||
),
|
||||
input.sensitive_values,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return result.ok && options?.signal?.aborted
|
||||
? err(new AnalysisCancelledError(OPERATION))
|
||||
: result;
|
||||
}
|
||||
}
|
||||
|
||||
const replyFailureReason = (cause: unknown): string => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause.message;
|
||||
if (cause instanceof z.ZodError)
|
||||
return `Reply violates its schema at ${cause.issues[0]?.path.map(String).join(".") ?? "root"}.`;
|
||||
if (cause instanceof SyntaxError) return "Reply is malformed JSON.";
|
||||
if (cause instanceof Error && "code" in cause)
|
||||
return `Reply file could not be read (${String(cause.code)}).`;
|
||||
return "Reply could not be validated.";
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { InspectWebNetworkCaptureInput } from "../../domain/webNetworkCapture.js";
|
||||
|
||||
/** Format-specific process profile keeps mature upstream code behind a replaceable adapter seam. */
|
||||
export interface HistoricalCaptureFormatAdapter {
|
||||
readonly format: InspectWebNetworkCaptureInput["format"];
|
||||
readonly identity: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
command(
|
||||
requestPath: string,
|
||||
runtimePath: string,
|
||||
): Promise<{ command: string; arguments: readonly string[] }>;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { access } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import type { HistoricalCaptureFormatAdapter } from "./HistoricalCaptureFormatAdapter.js";
|
||||
import { MITMPROXY_CAPTURE_PROVIDER_IDENTITY } from "./CaptureRelease.js";
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
/** Native mitmproxy decoding is offline and uses only an explicitly configured Linux tool. */
|
||||
export class MitmproxyCaptureAdapter implements HistoricalCaptureFormatAdapter {
|
||||
readonly format = "mitmproxy";
|
||||
readonly identity = MITMPROXY_CAPTURE_PROVIDER_IDENTITY;
|
||||
constructor(readonly environment: Readonly<NodeJS.ProcessEnv>) {}
|
||||
async command(
|
||||
requestPath: string,
|
||||
runtimePath: string,
|
||||
): Promise<{ command: string; arguments: readonly string[] }> {
|
||||
const command = this.environment.REA_MITMDUMP_COMMAND;
|
||||
if (
|
||||
process.platform !== "linux" ||
|
||||
command === undefined ||
|
||||
!isAbsolute(command)
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
OPERATION,
|
||||
"Native capture decoding requires Linux and an absolute REA_MITMDUMP_COMMAND path to caller-supplied mitmdump 12.2.3; HAR needs no external engine.",
|
||||
);
|
||||
try {
|
||||
await access(command, constants.R_OK | constants.X_OK);
|
||||
} catch (cause: unknown) {
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
OPERATION,
|
||||
`Configured mitmdump executable is unavailable: ${command}.`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
return {
|
||||
command,
|
||||
arguments: [
|
||||
"--no-server",
|
||||
"-q",
|
||||
"--set",
|
||||
`confdir=${runtimePath}`,
|
||||
"--set",
|
||||
`rea_request_path=${requestPath}`,
|
||||
"-s",
|
||||
fileURLToPath(
|
||||
new URL("../../../bridge/mitmproxy/capture.py", import.meta.url),
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user