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,15 @@
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type {
|
||||
InspectWebNetworkCaptureInput,
|
||||
WebNetworkCapture,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
/** Replaceable offline capture port; producer protocols remain in format adapters. */
|
||||
export interface WebNetworkCapturePort {
|
||||
inspect(
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { WebNetworkCaptureService } from "./WebNetworkCaptureService.js";
|
||||
import { historicalHar } from "../../tests/fixtures/historicalHar.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { parseEvidence } from "../domain/evidence.js";
|
||||
import {
|
||||
webNetworkCaptureSchema,
|
||||
type WebNetworkCapture,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
it.each(["REDACTED", "[", "]", "/capture.har"])(
|
||||
"excludes sensitive path text even when a replacement marker would collide: %s",
|
||||
async (literal) => {
|
||||
const report = fixture();
|
||||
report.artifact.path = `/capture.har/${literal}`;
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: report.artifact.path,
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject?.local_path).not.toContain(literal);
|
||||
expect(result.value.parameters.capture_path).not.toContain(literal);
|
||||
expect(
|
||||
result.value.locations.every(
|
||||
(location) =>
|
||||
location.kind !== "artifact-path" || !location.path.includes(literal),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps observed artifact identity when the entire sensitive path is excluded", async () => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["/", "[", "REDACTED"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toMatchObject({
|
||||
local_path: "",
|
||||
digest: { sha256: "a".repeat(64) },
|
||||
});
|
||||
expect(result.value.locations).toEqual([]);
|
||||
});
|
||||
|
||||
const fixture = (): WebNetworkCapture => ({
|
||||
decoder: { id: "test-historical-port", name: "test port", version: "1" },
|
||||
container: {
|
||||
reported: null,
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
records_pointer: "/log/entries",
|
||||
},
|
||||
total_records: 1,
|
||||
records: [
|
||||
{
|
||||
ordinal: 0,
|
||||
location: { kind: "json-pointer", pointer: "/log/entries/0" },
|
||||
reported: historicalHar().log.entries[0] ?? null,
|
||||
numeric_literals: [],
|
||||
binary_fields: [],
|
||||
redactions: [],
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
artifact: { path: "/capture.har", sha256: "a".repeat(64), bytes: 10 },
|
||||
format: "har",
|
||||
runtime_attribution: "unknown",
|
||||
limitations: ["historical fixture"],
|
||||
});
|
||||
|
||||
it.each(["a".repeat(64), "aaaa"])(
|
||||
"marks an explicitly sensitive artifact digest unknown without inventing another identity: %s",
|
||||
async (literal) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toBeNull();
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
artifact: { path: "/capture.har", sha256: null, bytes: 10 },
|
||||
});
|
||||
expect(result.value.parameters.capture_path).toBe("/capture.har");
|
||||
expect(result.value.locations).toEqual([
|
||||
{ kind: "artifact-path", path: "/capture.har" },
|
||||
]);
|
||||
expect(parseEvidence(result.value)).toEqual(result.value);
|
||||
},
|
||||
);
|
||||
|
||||
it("projects the unknown-subject explanation before generating its Evidence ID", async () => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["a"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toBeNull();
|
||||
expect(result.value.limitations.every((text) => !text.includes("a"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(parseEvidence(result.value)).toEqual(result.value);
|
||||
});
|
||||
|
||||
it("rejects an adapter omitting its original observed digest before caller projection", async () => {
|
||||
const report = fixture();
|
||||
report.artifact.sha256 = null;
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({ capture_path: report.artifact.path, format: "har" });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["producer"],
|
||||
["artifact"],
|
||||
["coordinates"],
|
||||
["producer", "REDACTED", "…"],
|
||||
["producer", "[", "]"],
|
||||
])(
|
||||
"excludes declared literals from all authored limitations: %j",
|
||||
async (...literals) => {
|
||||
const report = fixture();
|
||||
report.artifact.path = "/artifact/capture.har";
|
||||
report.limitations = [
|
||||
"Historical producer artifact coordinates are retained.",
|
||||
];
|
||||
const first = report.records[0];
|
||||
if (first === undefined) throw new Error("fixture missing record");
|
||||
first.limitations = ["This is producer-decoded artifact evidence."];
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: report.artifact.path,
|
||||
format: "har",
|
||||
sensitive_values: literals,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const projected = webNetworkCaptureSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
const texts = [
|
||||
result.value.limitations,
|
||||
projected.limitations,
|
||||
...projected.records.map((record) => record.limitations),
|
||||
].flat();
|
||||
for (const literal of literals)
|
||||
expect(texts.every((text) => !text.includes(literal))).toBe(true);
|
||||
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
|
||||
expect(projected.decoder).toEqual(report.decoder);
|
||||
expect(projected.records[0]?.reported).toEqual(first.reported);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps explicitly sensitive values out of Evidence parameters and preserves historical authority", async () => {
|
||||
const service = new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
});
|
||||
const result = await service.inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["explicit-private-value"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.parameters).toMatchObject({
|
||||
sensitive_value_count: 1,
|
||||
record_ordinals: [0],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("explicit-private-value");
|
||||
expect(result.value.authority).toBe("historical-reference");
|
||||
expect(result.value.provider).toEqual(fixture().decoder);
|
||||
});
|
||||
|
||||
it.each(["har", "ha"])(
|
||||
"omits a format parameter containing a declared sensitive literal: %s",
|
||||
async (literal) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.parameters).not.toHaveProperty("format");
|
||||
expect(JSON.stringify(result.value.parameters)).not.toContain(literal);
|
||||
expect(result.value.normalized_result).toMatchObject({ format: "har" });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ record_ordinals: [0, 0] },
|
||||
{ record_ordinals: [1] },
|
||||
{ capture_path: "relative.har" },
|
||||
])("rejects invalid caller selection %j", async (extra) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({ capture_path: "/capture.har", format: "har", ...extra });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
|
||||
it("rejects a port changing the artifact identity or producer ordinal sequence", async () => {
|
||||
const report = fixture();
|
||||
report.artifact.path = "/different.har";
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({ capture_path: "/capture.har", format: "har" });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
|
||||
});
|
||||
|
||||
it("applies an explicit sensitive path literal after verifying the selected artifact", async () => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["capture.har"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(JSON.stringify(result.value)).not.toContain("capture.har");
|
||||
expect(result.value.parameters.capture_path).toBe("");
|
||||
});
|
||||
|
||||
it.each(["log", "entries"])(
|
||||
"excludes a sensitive producer coordinate without inventing a replacement: %s",
|
||||
async (literal) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
container: { records_pointer: null },
|
||||
records: [
|
||||
{
|
||||
ordinal: 0,
|
||||
location: { kind: "unknown", reason: "explicit-sensitive-value" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain(literal);
|
||||
},
|
||||
);
|
||||
|
||||
it("excludes an escaped sensitive sidecar coordinate while preserving its reported field", async () => {
|
||||
const report = fixture();
|
||||
report.container.reported = { "field/name": 42 };
|
||||
report.container.numeric_literals = [
|
||||
{ pointer: "/field~1name", producer_type: "json-number", literal: "42" },
|
||||
];
|
||||
report.container.redactions = [
|
||||
{ pointer: "/field~1name", reason: "explicit-sensitive-value" },
|
||||
];
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: ["~1"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
container: {
|
||||
reported: { "field/name": 42 },
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("~1");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ literal: "12345", input: { record_ordinals: [12345] } },
|
||||
{ literal: "Each", input: { record_ordinals: [0, 0] } },
|
||||
{ literal: "absolute", input: { capture_path: "relative.har" } },
|
||||
{ literal: "secret", input: { mysecret: true } },
|
||||
])(
|
||||
"excludes declared text from application-generated input errors: $literal",
|
||||
async ({ literal, input }) => {
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(fixture())),
|
||||
}).inspect({
|
||||
capture_path: "/capture.har",
|
||||
format: "har",
|
||||
sensitive_values: [literal],
|
||||
...input,
|
||||
});
|
||||
if (result.ok) throw new Error("Expected invalid selection");
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
expect(JSON.stringify(projectAnalysisError(result.error))).not.toContain(
|
||||
literal,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["12345", "67890", "234", "789"])(
|
||||
"excludes sensitive native byte-range coordinates: %s",
|
||||
async (literal) => {
|
||||
const report = fixture();
|
||||
report.format = "mitmproxy";
|
||||
report.artifact.path = "/capture.mitm";
|
||||
const record = report.records[0];
|
||||
if (record === undefined) throw new Error("record missing");
|
||||
record.location = { kind: "byte-range", offset: 12345, bytes: 67890 };
|
||||
const result = await new WebNetworkCaptureService({
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
}).inspect({
|
||||
capture_path: report.artifact.path,
|
||||
format: "mitmproxy",
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
records: [
|
||||
{ location: { kind: "unknown", reason: "explicit-sensitive-value" } },
|
||||
],
|
||||
});
|
||||
expect(result.value.raw_result).toBeNull();
|
||||
expect(parseEvidence(result.value)).toEqual(result.value);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,202 @@
|
||||
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
|
||||
import { excludeCaptureCoordinates } from "../domain/webNetworkCaptureCoordinates.js";
|
||||
import { redactExplicitText } from "../domain/explicitSensitiveValues.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { WebNetworkCapturePort } from "./WebNetworkCapturePort.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
webNetworkCaptureSchema,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
|
||||
const OPERATION = "inspect_web_network_capture";
|
||||
|
||||
/** Shared CLI/MCP historical inspection preserves caller selection and producer record identity. */
|
||||
export class WebNetworkCaptureService {
|
||||
constructor(readonly port: WebNetworkCapturePort) {}
|
||||
|
||||
/** Return selected complete records inline, without inventing live browser attribution. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const declarations =
|
||||
inspectWebNetworkCaptureInputSchema.shape.sensitive_values.safeParse(
|
||||
typeof rawInput === "object" &&
|
||||
rawInput !== null &&
|
||||
"sensitive_values" in rawInput
|
||||
? rawInput.sensitive_values
|
||||
: undefined,
|
||||
);
|
||||
const failure = (error: AnalysisError): Result<never, AnalysisError> =>
|
||||
err(
|
||||
redactExplicitFailure(
|
||||
error,
|
||||
declarations.success ? declarations.data : [],
|
||||
),
|
||||
);
|
||||
const parsed = inspectWebNetworkCaptureInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return failure(
|
||||
new AnalysisInputError(
|
||||
OPERATION,
|
||||
{ cause: parsed.error },
|
||||
projectInputIssues(parsed.error.issues, rawInput),
|
||||
),
|
||||
);
|
||||
const input = parsed.data;
|
||||
if (!isAbsolute(input.capture_path))
|
||||
return failure(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["capture_path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute filesystem path on this host.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
if (
|
||||
input.record_ordinals !== undefined &&
|
||||
new Set(input.record_ordinals).size !== input.record_ordinals.length
|
||||
)
|
||||
return failure(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["record_ordinals"],
|
||||
reason: "invalid_format",
|
||||
message: "Each requested producer ordinal must occur once.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const loaded = await this.port.inspect(input, options);
|
||||
if (!loaded.ok) return failure(loaded.error);
|
||||
if (options?.signal?.aborted)
|
||||
return failure(new AnalysisCancelledError(OPERATION));
|
||||
const report = webNetworkCaptureSchema.safeParse(loaded.value);
|
||||
if (!report.success)
|
||||
return failure(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture adapter returned malformed historical evidence.",
|
||||
),
|
||||
);
|
||||
const value = report.data;
|
||||
const artifactSha256 = value.artifact.sha256;
|
||||
if (artifactSha256 === null)
|
||||
return failure(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture adapter omitted its observed artifact digest before explicit projection.",
|
||||
),
|
||||
);
|
||||
if (
|
||||
value.artifact.path !== input.capture_path ||
|
||||
value.format !== input.format ||
|
||||
value.total_records !== value.records.length ||
|
||||
value.records.some((record, index) => record.ordinal !== index)
|
||||
)
|
||||
return failure(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Capture adapter changed the selected artifact, format or original record sequence.",
|
||||
),
|
||||
);
|
||||
const safeValue = excludeCaptureCoordinates(value, input.sensitive_values);
|
||||
const redactText = (text: string): string =>
|
||||
redactExplicitText(text, input.sensitive_values);
|
||||
const selected =
|
||||
input.record_ordinals ?? value.records.map(({ ordinal }) => ordinal);
|
||||
const records = [];
|
||||
for (const ordinal of selected) {
|
||||
const record = safeValue.records[ordinal];
|
||||
if (record === undefined)
|
||||
return failure(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["record_ordinals"],
|
||||
reason: "invalid_format",
|
||||
message: `Producer ordinal ${ordinal} is outside the retained capture (${value.total_records} records).`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
records.push({
|
||||
...record,
|
||||
limitations: record.limitations.map(redactText),
|
||||
});
|
||||
}
|
||||
const safePath = input.sensitive_values.some((literal) =>
|
||||
input.capture_path.includes(literal),
|
||||
)
|
||||
? ""
|
||||
: input.capture_path;
|
||||
const safeSha256 = input.sensitive_values.some((literal) =>
|
||||
artifactSha256.includes(literal),
|
||||
)
|
||||
? null
|
||||
: artifactSha256;
|
||||
const subjectUnavailableReason = redactText(
|
||||
"The explicitly sensitive artifact digest is excluded; its cryptographic identity is unknown in this Evidence.",
|
||||
);
|
||||
const limitations = [
|
||||
...safeValue.limitations,
|
||||
...(safePath === ""
|
||||
? [
|
||||
"The explicitly sensitive artifact path is excluded; its size remains available.",
|
||||
]
|
||||
: []),
|
||||
].map(redactText);
|
||||
const parameters = jsonObjectSchema.parse({
|
||||
capture_path: safePath,
|
||||
...(input.sensitive_values.some((literal) =>
|
||||
input.format.includes(literal),
|
||||
)
|
||||
? {}
|
||||
: { format: input.format }),
|
||||
record_ordinals: selected,
|
||||
sensitive_value_count: input.sensitive_values.length,
|
||||
});
|
||||
return ok(
|
||||
createEvidence(
|
||||
safeSha256 === null
|
||||
? undefined
|
||||
: {
|
||||
path: safePath,
|
||||
sha256: safeSha256,
|
||||
format: "file",
|
||||
},
|
||||
value.decoder,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters,
|
||||
result: {
|
||||
...safeValue,
|
||||
artifact: { ...value.artifact, path: safePath, sha256: safeSha256 },
|
||||
records,
|
||||
limitations:
|
||||
safeSha256 === null
|
||||
? [...limitations, subjectUnavailableReason]
|
||||
: limitations,
|
||||
},
|
||||
confidence: "observed",
|
||||
authority: "historical-reference",
|
||||
limitations,
|
||||
...(safeSha256 === null ? { subjectUnavailableReason } : {}),
|
||||
locations:
|
||||
safePath === "" ? [] : [{ kind: "artifact-path", path: safePath }],
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
open,
|
||||
rm,
|
||||
symlink,
|
||||
unlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, it } from "vitest";
|
||||
import { readStableArtifact } from "./readStableArtifact.js";
|
||||
|
||||
const checkChange = async (
|
||||
stage: "before-open" | "after-read" | "symlink-replacement",
|
||||
): Promise<void> => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-stable-read-"));
|
||||
const path = join(root, "selected");
|
||||
await writeFile(path, "original evidence");
|
||||
let inspected = 0;
|
||||
try {
|
||||
const reading = readStableArtifact(path, 1024, undefined, {
|
||||
async lstat(selected) {
|
||||
inspected++;
|
||||
if (stage === "after-read" && inspected === 2) await unlink(selected);
|
||||
const stat = await lstat(selected, { bigint: true });
|
||||
if (inspected === 1 && stage !== "after-read") {
|
||||
await unlink(selected);
|
||||
if (stage === "symlink-replacement")
|
||||
await symlink("missing", selected);
|
||||
}
|
||||
return stat;
|
||||
},
|
||||
open,
|
||||
});
|
||||
await expect(reading).rejects.toMatchObject({ reason: "integrity" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
it.each(["before-open", "after-read"] as const)(
|
||||
"retains an actual post-validation %s change as integrity failure",
|
||||
checkChange,
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains a post-validation symlink replacement as an integrity failure",
|
||||
() => checkChange("symlink-replacement"),
|
||||
);
|
||||
|
||||
it("keeps initially missing inputs distinguishable from later changes", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-stable-missing-"));
|
||||
try {
|
||||
await expect(
|
||||
readStableArtifact(join(root, "missing"), 1024),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,16 +1,50 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import { constants, type BigIntStats } from "node:fs";
|
||||
import { lstat, open, type FileHandle } from "node:fs/promises";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
|
||||
/** Filesystem boundary for stable reads, including deterministic replacement probes. */
|
||||
export interface StableArtifactFileSystem {
|
||||
lstat(path: string): Promise<BigIntStats>;
|
||||
open(path: string, flags: number): Promise<FileHandle>;
|
||||
}
|
||||
|
||||
const FILE_SYSTEM: StableArtifactFileSystem = {
|
||||
lstat: (path) => lstat(path, { bigint: true }),
|
||||
open,
|
||||
};
|
||||
|
||||
const afterValidation = async <T>(
|
||||
path: string,
|
||||
stage: string,
|
||||
read: () => Promise<T>,
|
||||
): Promise<T> => {
|
||||
try {
|
||||
return await read();
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code))
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact changed ${stage}: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Read one bounded regular file and reject replacement or in-place changes. */
|
||||
export const readStableArtifact = async (
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
signal?: AbortSignal,
|
||||
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
|
||||
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
|
||||
signal?.throwIfAborted();
|
||||
const before = await lstat(path, { bigint: true });
|
||||
const before = await fileSystem.lstat(path);
|
||||
if (!before.isFile() || before.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
@@ -21,9 +55,11 @@ export const readStableArtifact = async (
|
||||
"limit",
|
||||
`Selected artifact exceeds ${String(maximumBytes)} bytes: ${path}`,
|
||||
);
|
||||
const file = await open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
const file = await afterValidation(path, "before open", () =>
|
||||
fileSystem.open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
),
|
||||
);
|
||||
try {
|
||||
const initial = await file.stat({ bigint: true });
|
||||
@@ -59,7 +95,9 @@ export const readStableArtifact = async (
|
||||
chunks.push(bytes);
|
||||
}
|
||||
const after = await file.stat({ bigint: true });
|
||||
const current = await lstat(path, { bigint: true });
|
||||
const current = await afterValidation(path, "during read", () =>
|
||||
fileSystem.lstat(path),
|
||||
);
|
||||
if (
|
||||
[after, current].some(
|
||||
(stat) =>
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { registerWebScriptCommands } from "./cli/webScriptCommands.js";
|
||||
import { registerWebModuleCommands } from "./cli/webModuleCommands.js";
|
||||
import { registerWebSourceLocationCommands } from "./cli/webSourceLocationCommands.js";
|
||||
import { registerWebRuntimeCommands } from "./cli/webRuntimeCommands.js";
|
||||
import { registerWebNetworkCaptureCommands } from "./cli/webNetworkCaptureCommands.js";
|
||||
import { registerJavaScriptRecoveryCommands } from "./cli/javascriptRecoveryCommands.js";
|
||||
import { registerAdvancedBrowserCommands } from "./cli/browserAdvancedCommands.js";
|
||||
import { registerBrowserScenarioCommands } from "./cliBrowserScenarioCommands.js";
|
||||
@@ -65,6 +66,7 @@ export const createCli = (
|
||||
registerWebModuleCommands(cli, logger, environment);
|
||||
registerWebSourceLocationCommands(cli, logger, environment);
|
||||
registerWebRuntimeCommands(cli, logger);
|
||||
registerWebNetworkCaptureCommands(cli, logger, environment);
|
||||
registerJavaScriptRecoveryCommands(cli, logger, environment);
|
||||
registerAdvancedBrowserCommands(cli, logger);
|
||||
registerBrowserScenarioCommands(cli, logger);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from "incur";
|
||||
import { createWebNetworkCaptureService } from "../composition/webNetworkCaptures.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Expose offline historical capture inspection with the same selection contract as MCP. */
|
||||
export const registerWebNetworkCaptureCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createWebNetworkCaptureService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectWebNetworkCapture, {
|
||||
description:
|
||||
"Inspect retained HAR or native mitmproxy records without fetching recorded URLs",
|
||||
args: z.object({
|
||||
capturePath: z.string().describe("Absolute local capture path"),
|
||||
format: z.enum(["har", "mitmproxy"]).describe("Producer capture format"),
|
||||
}),
|
||||
options: z.object({
|
||||
record: z
|
||||
.array(z.coerce.number().int().nonnegative())
|
||||
.optional()
|
||||
.describe("Zero-based producer ordinals; repeat to select several"),
|
||||
sensitiveValue: z
|
||||
.array(z.string().min(1))
|
||||
.default([])
|
||||
.describe(
|
||||
"Literal string values explicitly marked sensitive; repeat as needed",
|
||||
),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.inspectWebNetworkCapture,
|
||||
async () => {
|
||||
const result = await service.inspect(
|
||||
{
|
||||
capture_path: args.capturePath,
|
||||
format: args.format,
|
||||
sensitive_values: options.sensitiveValue,
|
||||
...(options.record === undefined
|
||||
? {}
|
||||
: { record_ordinals: options.record }),
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return result.ok
|
||||
? result.value
|
||||
: projectAnalysisError(result.error);
|
||||
},
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Canonical names used by every one-shot CLI command registration. */
|
||||
export const CLI_COMMANDS = Object.freeze({
|
||||
inspectWebNetworkCapture: "inspect-web-network-capture",
|
||||
observeWebExecution: "observe-web-execution",
|
||||
inspectWebEventListeners: "inspect-web-event-listeners",
|
||||
traceWebSourceLocation: "trace-web-source-location",
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
|
||||
import { HistoricalCaptureDecoder } from "../browser/history/HistoricalCaptureDecoder.js";
|
||||
import { HarCaptureAdapter } from "../browser/history/HarCaptureAdapter.js";
|
||||
import { MitmproxyCaptureAdapter } from "../browser/history/MitmproxyCaptureAdapter.js";
|
||||
|
||||
/** Compose offline format adapters without import-time reads, installation or process startup. */
|
||||
export const createWebNetworkCaptureService = (
|
||||
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
): WebNetworkCaptureService =>
|
||||
new WebNetworkCaptureService(
|
||||
new HistoricalCaptureDecoder(
|
||||
[new HarCaptureAdapter(), new MitmproxyCaptureAdapter(environment)],
|
||||
environment,
|
||||
),
|
||||
);
|
||||
@@ -16,6 +16,7 @@ import { ELECTRON_TOOL_CONTRACTS } from "./javascript/electronToolContracts.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/javascriptRuntimeObservationToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
import { WEB_RUNTIME_TOOL_CONTRACTS } from "./webRuntimeToolContracts.js";
|
||||
import { WEB_NETWORK_CAPTURE_TOOL_CONTRACTS } from "./webNetworkCaptureToolContracts.js";
|
||||
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
|
||||
import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecoveryToolContracts.js";
|
||||
import { TOOL_EFFECTS } from "./toolEffects.js";
|
||||
@@ -80,6 +81,7 @@ describe("tool contract surface", () => {
|
||||
...APPLICATION_TOOL_CONTRACTS,
|
||||
...WEB_SCRIPT_TOOL_CONTRACTS,
|
||||
...WEB_RUNTIME_TOOL_CONTRACTS,
|
||||
...WEB_NETWORK_CAPTURE_TOOL_CONTRACTS,
|
||||
...JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
|
||||
...SESSION_TOOL_CONTRACTS,
|
||||
].map(({ name }) => name);
|
||||
|
||||
@@ -30,6 +30,8 @@ const generic = <Code extends string>(code: Code) =>
|
||||
/** Stable discriminated schema shared by every CLI and MCP error surface. */
|
||||
export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [
|
||||
generic("invalid_request"),
|
||||
generic("access_denied"),
|
||||
generic("artifact_changed"),
|
||||
generic("unreadable_output"),
|
||||
generic("capability_unavailable"),
|
||||
generic("provider_unavailable"),
|
||||
|
||||
@@ -17,6 +17,7 @@ import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecoveryToolContracts.js";
|
||||
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
|
||||
import { WEB_RUNTIME_TOOL_CONTRACTS } from "./webRuntimeToolContracts.js";
|
||||
import { WEB_NETWORK_CAPTURE_TOOL_CONTRACTS } from "./webNetworkCaptureToolContracts.js";
|
||||
|
||||
const GROUPS = {
|
||||
official: OFFICIAL_TOOL_CONTRACTS,
|
||||
@@ -34,6 +35,7 @@ const GROUPS = {
|
||||
javascript_recovery: JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
|
||||
web_script_export: WEB_SCRIPT_TOOL_CONTRACTS,
|
||||
web_runtime: WEB_RUNTIME_TOOL_CONTRACTS,
|
||||
web_network_capture: WEB_NETWORK_CAPTURE_TOOL_CONTRACTS,
|
||||
session: SESSION_TOOL_CONTRACTS,
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascript/java
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
import { WEB_SCRIPT_TOOL_CONTRACTS } from "./webScriptToolContracts.js";
|
||||
import { WEB_RUNTIME_TOOL_CONTRACTS } from "./webRuntimeToolContracts.js";
|
||||
import { WEB_NETWORK_CAPTURE_TOOL_CONTRACTS } from "./webNetworkCaptureToolContracts.js";
|
||||
import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecoveryToolContracts.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
|
||||
import { ENHANCED_TOOL_CONTRACTS } from "./enhancedToolContracts.js";
|
||||
@@ -33,6 +34,7 @@ export const TOOL_CONTRACTS = [
|
||||
...APPLICATION_TOOL_CONTRACTS,
|
||||
...WEB_SCRIPT_TOOL_CONTRACTS,
|
||||
...WEB_RUNTIME_TOOL_CONTRACTS,
|
||||
...WEB_NETWORK_CAPTURE_TOOL_CONTRACTS,
|
||||
...JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
|
||||
...SESSION_TOOL_CONTRACTS,
|
||||
] as const;
|
||||
|
||||
@@ -41,6 +41,11 @@ const sessionEvidence = effects({ mutatesSession: true });
|
||||
|
||||
/** Explicit effect audit for every public tool. */
|
||||
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
inspect_web_network_capture: effects({
|
||||
mutatesSession: true,
|
||||
writesFilesystem: true,
|
||||
launchesProcess: true,
|
||||
}),
|
||||
observe_web_execution: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
inspectWebNetworkCaptureInputSchema,
|
||||
webNetworkCaptureSchema,
|
||||
} from "../domain/webNetworkCapture.js";
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemas.js";
|
||||
|
||||
/** Historical inspection is distinct from live browser capture and runtime authority. */
|
||||
export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_web_network_capture",
|
||||
...toolContractMetadata("inspect_web_network_capture"),
|
||||
description:
|
||||
"Inspect retained local HAR 1.2 or native mitmproxy capture records without contacting recorded URLs. Returns original ordinals, pointers/byte ranges, preserved producer fields, precise numeric representations and exact exposed binary bytes inline. Excludes known transport credentials and explicitly marked values. Decodes every record before optional ordinal selection; malformed or oversized captures return no partial success. Duplicate HAR members are invalid; prototype-named __proto__ members are unsupported by the current shared JSON boundary. Uses pinned upstream parsers, owned temporary files and bounded offline processes. Native mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Browser transaction IDs, runtime attribution and original bytes of HAR Unicode text remain unknown.",
|
||||
kind: "browser-provider",
|
||||
inputSchema: inspectWebNetworkCaptureInputSchema,
|
||||
outputSchema: evidenceResultOf(webNetworkCaptureSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect historical HAR entries",
|
||||
input: {
|
||||
capture_path: "/captures/session.har",
|
||||
format: "har",
|
||||
record_ordinals: [0, 2],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -0,0 +1,29 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { AnalysisAccessDeniedError } from "./analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
|
||||
|
||||
it.each(["EACCES", "EPERM"] as const)(
|
||||
"projects %s as host access denial with correction guidance and a valid public schema",
|
||||
(systemCode) => {
|
||||
const error = new AnalysisAccessDeniedError(
|
||||
"inspect_web_network_capture",
|
||||
"/selected/capture.har",
|
||||
systemCode,
|
||||
{ cause: new Error("internal detail") },
|
||||
);
|
||||
const projected = projectAnalysisError(error);
|
||||
expect(analysisErrorProjectionSchema.parse(projected)).toMatchObject({
|
||||
code: "access_denied",
|
||||
category: "unavailable",
|
||||
retryable: false,
|
||||
details: {
|
||||
path: "/selected/capture.har",
|
||||
system_code: systemCode,
|
||||
boundary: "filesystem-read",
|
||||
},
|
||||
});
|
||||
expect(projected.remediation.action).toContain("read access");
|
||||
expect(JSON.stringify(projected)).not.toContain("internal detail");
|
||||
},
|
||||
);
|
||||
@@ -2,6 +2,8 @@
|
||||
const ANALYSIS_ERROR_TAGS = [
|
||||
"AnalysisProtocolError",
|
||||
"AnalysisInputError",
|
||||
"AnalysisAccessDeniedError",
|
||||
"AnalysisArtifactChangedError",
|
||||
"AnalysisOutputError",
|
||||
"AnalysisCapabilityUnavailableError",
|
||||
"AnalysisCancelledError",
|
||||
|
||||
@@ -90,3 +90,32 @@ export class AnalysisTimeoutError extends AnalysisError {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Host filesystem permissions denied the selected read; this is not malformed caller input. */
|
||||
export class AnalysisAccessDeniedError extends AnalysisError {
|
||||
readonly _tag = "AnalysisAccessDeniedError";
|
||||
constructor(
|
||||
readonly operation: string,
|
||||
readonly path: string,
|
||||
readonly systemCode: "EACCES" | "EPERM",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(
|
||||
`Host filesystem read access denied (${systemCode}) for ${path} during ${operation}`,
|
||||
options,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Selected artifact acquisition observed a change, so no stable identity can be reported. */
|
||||
export class AnalysisArtifactChangedError extends AnalysisError {
|
||||
readonly _tag = "AnalysisArtifactChangedError";
|
||||
constructor(
|
||||
readonly operation: string,
|
||||
readonly path: string,
|
||||
readonly reason: string,
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Selected artifact changed during acquisition: ${reason}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { AnalysisInputError } from "./analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisInputError,
|
||||
} from "./analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "./artifactOperationError.js";
|
||||
import {
|
||||
BinaryTargetError,
|
||||
@@ -47,6 +51,10 @@ export const analysisErrorRemediationAction = (
|
||||
error.constraint === "directory_requires_file"
|
||||
)
|
||||
return "For a JavaScript/Electron application directory, call analyze_javascript_application with input_path or run `rea analyze <directory>`. For binary analysis, select its executable file.";
|
||||
if (error instanceof AnalysisAccessDeniedError)
|
||||
return "Check the current process's read access to the selected path. Retry with a readable local file.";
|
||||
if (error instanceof AnalysisArtifactChangedError)
|
||||
return "Wait until the selected file is stable, then retry this operation.";
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Correct the listed arguments and retry.";
|
||||
if (error instanceof UnknownRegistryError && error.reason === "not-found")
|
||||
@@ -107,6 +115,8 @@ const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
Partial<Record<AnalysisErrorTag, AnalysisErrorProjection["category"]>>
|
||||
> = {
|
||||
AnalysisInputError: "invalid_input",
|
||||
AnalysisAccessDeniedError: "unavailable",
|
||||
AnalysisArtifactChangedError: "integrity_mismatch",
|
||||
AnalysisCapabilityUnavailableError: "unsupported_provider",
|
||||
ProviderSelectionError: "unsupported_provider",
|
||||
EvidenceIntegrityError: "integrity_mismatch",
|
||||
@@ -119,6 +129,10 @@ const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
};
|
||||
|
||||
export const analysisErrorUserMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof AnalysisAccessDeniedError)
|
||||
return "Host filesystem permissions denied read access to the selected path.";
|
||||
if (error instanceof AnalysisArtifactChangedError)
|
||||
return "The selected artifact changed during acquisition; no stable snapshot was decoded.";
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Analysis input is invalid. Check the arguments and try again.";
|
||||
const hopperMessage = hopperErrorUserMessage(error);
|
||||
@@ -243,6 +257,8 @@ const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
|
||||
const KNOWN_ERROR_TAGS = {
|
||||
AnalysisProtocolError: true,
|
||||
AnalysisInputError: true,
|
||||
AnalysisAccessDeniedError: true,
|
||||
AnalysisArtifactChangedError: true,
|
||||
AnalysisOutputError: true,
|
||||
AnalysisCapabilityUnavailableError: true,
|
||||
AnalysisCancelledError: true,
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
assertKnownAnalysisErrorTag,
|
||||
} from "./analysisErrorPresentation.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
@@ -130,6 +132,8 @@ const STATIC_ERROR_CODES = {
|
||||
AnalysisOutputError: "unreadable_output",
|
||||
HopperProtocolError: "unreadable_output",
|
||||
AnalysisInputError: "invalid_request",
|
||||
AnalysisAccessDeniedError: "access_denied",
|
||||
AnalysisArtifactChangedError: "artifact_changed",
|
||||
AnalysisCapabilityUnavailableError: "capability_unavailable",
|
||||
AnalysisCancelledError: "cancelled",
|
||||
HopperCancelledError: "cancelled",
|
||||
@@ -177,6 +181,20 @@ const errorDetails = (
|
||||
const requestErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisArtifactChangedError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
path: error.path,
|
||||
reason: error.reason,
|
||||
boundary: "stable-artifact-read",
|
||||
};
|
||||
if (error instanceof AnalysisAccessDeniedError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
path: error.path,
|
||||
system_code: error.systemCode,
|
||||
boundary: "filesystem-read",
|
||||
};
|
||||
if (error instanceof AnalysisOutputError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof AnalysisInputError && error.issues.length > 0)
|
||||
@@ -372,6 +390,7 @@ const lifecycleErrorDetails = (
|
||||
};
|
||||
|
||||
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
|
||||
"artifact_changed",
|
||||
"invalid_request",
|
||||
"provider_timeout",
|
||||
"cancelled",
|
||||
@@ -384,6 +403,8 @@ export interface AnalysisErrorProjection extends Readonly<
|
||||
> {
|
||||
readonly code:
|
||||
| "invalid_request"
|
||||
| "access_denied"
|
||||
| "artifact_changed"
|
||||
| "unreadable_output"
|
||||
| "capability_unavailable"
|
||||
| "provider_unavailable"
|
||||
|
||||
@@ -156,6 +156,23 @@ describe("analysis evidence identity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("binds an explicit unknown-subject reason into the semantic Evidence identity", () => {
|
||||
const reason = "Caller excluded the observed digest.";
|
||||
const observation = { operation: "health", parameters: {}, result: true };
|
||||
const explicit = createEvidence(undefined, PROVIDER, {
|
||||
...observation,
|
||||
subjectUnavailableReason: reason,
|
||||
});
|
||||
const defaulted = createEvidence(undefined, PROVIDER, observation);
|
||||
expect(explicit.subject).toBeNull();
|
||||
expect(explicit.limitations).toEqual([reason]);
|
||||
expect(defaulted.limitations).toEqual([
|
||||
"Artifact identity is unavailable for this observation.",
|
||||
]);
|
||||
expect(explicit.evidence_id).not.toBe(defaulted.evidence_id);
|
||||
expect(parseEvidence(explicit)).toEqual(explicit);
|
||||
});
|
||||
|
||||
it("derives byte-stable bundle manifests independent of record order", () => {
|
||||
const artifactEvidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
|
||||
@@ -169,6 +169,8 @@ export interface EvidenceObservation {
|
||||
readonly authority?: EvidenceAuthority;
|
||||
readonly environment?: ExecutionEnvironment | null;
|
||||
readonly limitations?: readonly string[];
|
||||
/** Reason the subject identity is unavailable, when no target identity is supplied. */
|
||||
readonly subjectUnavailableReason?: string;
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly evidenceLinks?: readonly string[];
|
||||
}
|
||||
@@ -229,7 +231,7 @@ export const createEvidence = (
|
||||
target === undefined
|
||||
? null
|
||||
: {
|
||||
name: target.path.split("/").at(-1) ?? target.path,
|
||||
name: target.path.split("/").at(-1) || "artifact",
|
||||
digest: { sha256: target.sha256 },
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
@@ -262,7 +264,10 @@ export const createEvidence = (
|
||||
environment: observation.environment ?? null,
|
||||
limitations: [
|
||||
...(target === undefined
|
||||
? ["Artifact identity is unavailable for this observation."]
|
||||
? [
|
||||
observation.subjectUnavailableReason ??
|
||||
"Artifact identity is unavailable for this observation.",
|
||||
]
|
||||
: []),
|
||||
...(observation.limitations ?? []),
|
||||
],
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { AnalysisAccessDeniedError } from "./analysisErrorCore.js";
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "./analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
import { ProviderCleanupError } from "./providerCleanupError.js";
|
||||
import {
|
||||
redactExplicitFailure,
|
||||
redactExplicitPointer,
|
||||
} from "./explicitSensitiveFailure.js";
|
||||
|
||||
it.each([
|
||||
["/metadata/private~1~0/numeric", ["private/~"], "/metadata"],
|
||||
["/metadata/private/child", ["private"], "/metadata"],
|
||||
["/ordinary/path", [], "/ordinary/path"],
|
||||
])(
|
||||
"preserves a real parent for excluded pointer identities: %s",
|
||||
(pointer, values, expected) => {
|
||||
expect(redactExplicitPointer(pointer, values)).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves cleanup failure authority and resources while excluding diagnostics", () => {
|
||||
const error = new ProviderCleanupError(
|
||||
"har",
|
||||
["/root/private/capture", "pid:123"],
|
||||
{
|
||||
capture_path: "/root/private/capture",
|
||||
nested: { "private-key": 5, ordinary: "private ordinary" },
|
||||
exit_code: 2,
|
||||
},
|
||||
{ operation: "inspect_web_network_capture" },
|
||||
);
|
||||
const projected = projectAnalysisError(
|
||||
redactExplicitFailure(error, ["private", "REDACTED"]),
|
||||
);
|
||||
expect(projected.code).toBe("cleanup_incomplete");
|
||||
expect(JSON.stringify(projected)).not.toContain("private");
|
||||
expect(JSON.stringify(projected)).not.toContain("REDACTED");
|
||||
expect(JSON.stringify(projected)).toContain("pid:123");
|
||||
expect(JSON.stringify(projected)).toContain('"exit_code":2');
|
||||
});
|
||||
|
||||
it("keeps unsupported profile reasons distinct from malformed input", () => {
|
||||
const error = new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
"inspect_web_network_capture",
|
||||
"Unsupported private profile",
|
||||
{ userMessage: "Select private-compatible profile" },
|
||||
);
|
||||
const result = redactExplicitFailure(error, ["private"]);
|
||||
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect(projectAnalysisError(result).code).toBe("capability_unavailable");
|
||||
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
|
||||
});
|
||||
|
||||
it("coarsens format issue pointers without creating replacement coordinates", () => {
|
||||
const error = new AnalysisInputError(
|
||||
"inspect_web_network_capture",
|
||||
undefined,
|
||||
[
|
||||
{
|
||||
path: ["capture_path", "/metadata/private~1~0/nested"],
|
||||
reason: "invalid_format",
|
||||
message: "Malformed private field",
|
||||
},
|
||||
],
|
||||
);
|
||||
const result = redactExplicitFailure(error, ["private/~", "private"]);
|
||||
expect(result).toBeInstanceOf(AnalysisInputError);
|
||||
if (!(result instanceof AnalysisInputError))
|
||||
throw new Error("Input error required");
|
||||
expect(result.issues[0]?.path).toEqual(["capture_path", "/metadata"]);
|
||||
});
|
||||
|
||||
it("excludes a marked permission-denied path without losing its host error code", () => {
|
||||
const error = redactExplicitFailure(
|
||||
new AnalysisAccessDeniedError(
|
||||
"inspect_web_network_capture",
|
||||
"/declared-path-value/capture.har",
|
||||
"EACCES",
|
||||
),
|
||||
["declared-path-value"],
|
||||
);
|
||||
expect(error._tag).toBe("AnalysisAccessDeniedError");
|
||||
const projected = projectAnalysisError(error);
|
||||
expect(projected).toMatchObject({
|
||||
code: "access_denied",
|
||||
category: "unavailable",
|
||||
details: { system_code: "EACCES" },
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("declared-path-value");
|
||||
});
|
||||
|
||||
it("coarsens ordinary sensitive issue-path segments to their real parent", () => {
|
||||
const input = new AnalysisInputError(
|
||||
"inspect_web_network_capture",
|
||||
undefined,
|
||||
[
|
||||
{
|
||||
path: ["input", "mysecret", "child"],
|
||||
reason: "unknown_argument",
|
||||
message: "Unrecognized mysecret",
|
||||
},
|
||||
],
|
||||
);
|
||||
const result = redactExplicitFailure(input, ["secret"]);
|
||||
if (!(result instanceof AnalysisInputError))
|
||||
throw new Error("Input error required");
|
||||
expect(result.issues[0]?.path).toEqual(["input"]);
|
||||
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("secret");
|
||||
});
|
||||
|
||||
it("does not reinterpret an unknown argument name as a JSON pointer", () => {
|
||||
const input = new AnalysisInputError(
|
||||
"inspect_web_network_capture",
|
||||
undefined,
|
||||
[{ path: ["/ordinary/secret"], reason: "unknown_argument" }],
|
||||
);
|
||||
const result = redactExplicitFailure(input, ["secret"]);
|
||||
if (!(result instanceof AnalysisInputError))
|
||||
throw new Error("Input error required");
|
||||
expect(result.issues[0]?.path).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { AnalysisError } from "./analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "./analysisErrorCore.js";
|
||||
import { redactExplicitText } from "./explicitSensitiveValues.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { ProviderAdapterError } from "./providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "./providerCleanupError.js";
|
||||
|
||||
/** Keep a real JSON-pointer ancestor when a property identity is explicitly excluded. */
|
||||
export const redactExplicitPointer = (
|
||||
pointer: string,
|
||||
values: readonly string[],
|
||||
): string => {
|
||||
let parent = "";
|
||||
for (const segment of pointer.split("/").slice(1)) {
|
||||
const decoded = segment.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
const child = `${parent}/${segment}`;
|
||||
if (
|
||||
values.some(
|
||||
(literal) => decoded.includes(literal) || child.includes(literal),
|
||||
)
|
||||
)
|
||||
return parent;
|
||||
parent = child;
|
||||
}
|
||||
return parent;
|
||||
};
|
||||
|
||||
/** Exclude explicit literals from common acquisition/decoder failures, preserving typed diagnostics. */
|
||||
export const redactExplicitFailure = (
|
||||
error: AnalysisError,
|
||||
values: readonly string[],
|
||||
): AnalysisError => {
|
||||
if (values.length === 0) return error;
|
||||
const text = (value: string): string => redactExplicitText(value, values);
|
||||
const path = (
|
||||
parts: readonly (string | number)[],
|
||||
ordinaryNames: boolean,
|
||||
): (string | number)[] => {
|
||||
const retained: (string | number)[] = [];
|
||||
for (const part of parts) {
|
||||
if (typeof part !== "string") {
|
||||
retained.push(part);
|
||||
} else if (!ordinaryNames && part.startsWith("/")) {
|
||||
const pointer = redactExplicitPointer(part, values);
|
||||
retained.push(pointer);
|
||||
if (pointer !== part) break;
|
||||
} else {
|
||||
if (values.some((literal) => part.includes(literal))) break;
|
||||
retained.push(part);
|
||||
}
|
||||
}
|
||||
return retained;
|
||||
};
|
||||
const diagnostics = (
|
||||
value: Readonly<Record<string, JsonValue>>,
|
||||
): Record<string, JsonValue> =>
|
||||
Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([key]) => !values.some((literal) => key.includes(literal)))
|
||||
.map(([key, item]) => [key, visit(item)]),
|
||||
);
|
||||
const visit = (value: JsonValue): JsonValue => {
|
||||
if (typeof value === "string") return text(value);
|
||||
if (Array.isArray(value)) return value.map(visit);
|
||||
if (typeof value === "object" && value !== null) return diagnostics(value);
|
||||
return value;
|
||||
};
|
||||
if (error instanceof AnalysisAccessDeniedError)
|
||||
return new AnalysisAccessDeniedError(
|
||||
error.operation,
|
||||
text(error.path),
|
||||
error.systemCode,
|
||||
{ cause: error },
|
||||
);
|
||||
if (error instanceof AnalysisArtifactChangedError)
|
||||
return new AnalysisArtifactChangedError(
|
||||
error.operation,
|
||||
text(error.path),
|
||||
text(error.reason),
|
||||
{ cause: error },
|
||||
);
|
||||
if (error instanceof AnalysisInputError)
|
||||
return new AnalysisInputError(
|
||||
error.operation,
|
||||
{ cause: error },
|
||||
error.issues.map((issue) => ({
|
||||
...issue,
|
||||
// Unknown-argument paths contain literal field names, including names
|
||||
// beginning with '/'; they are not producer JSON-pointer coordinates.
|
||||
path: path(issue.path, issue.reason === "unknown_argument"),
|
||||
...(issue.message === undefined
|
||||
? {}
|
||||
: { message: text(issue.message) }),
|
||||
...(issue.expected === undefined
|
||||
? {}
|
||||
: { expected: visit(issue.expected) }),
|
||||
})),
|
||||
);
|
||||
if (error instanceof AnalysisOutputError)
|
||||
return new AnalysisOutputError(error.operation, text(error.reason), {
|
||||
cause: error,
|
||||
});
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
error.providerId,
|
||||
error.operation,
|
||||
text(error.reason),
|
||||
{
|
||||
cause: error,
|
||||
...(error.userMessage === undefined
|
||||
? {}
|
||||
: { userMessage: text(error.userMessage) }),
|
||||
},
|
||||
);
|
||||
if (error instanceof ProviderCleanupError)
|
||||
return new ProviderCleanupError(
|
||||
error.providerId,
|
||||
error.cleanupResources.map(text),
|
||||
diagnostics(error.diagnostics ?? {}),
|
||||
{ operation: error.operation, cause: error },
|
||||
);
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return new ProviderAdapterError(error.providerId, error.operation, {
|
||||
cause: error,
|
||||
...(error.diagnostics === undefined
|
||||
? {}
|
||||
: { diagnostics: diagnostics(error.diagnostics) }),
|
||||
});
|
||||
return error;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { redactExplicitText } from "./explicitSensitiveValues.js";
|
||||
|
||||
it.each([
|
||||
["secret context", ["secret"]],
|
||||
["secret context", ["secret", "REDACTED"]],
|
||||
["secret context", ["secret", "[", "…"]],
|
||||
["secretable context", ["secret", "able", "table"]],
|
||||
["secretsecret context", ["secret", "…", "REDACTED"]],
|
||||
] as const)(
|
||||
"keeps declared literals out of replacement text: %s",
|
||||
(input, values) => {
|
||||
const result = redactExplicitText(input, values);
|
||||
for (const value of values) expect(result).not.toContain(value);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not guess sensitivity or treat empty declarations as matches", () => {
|
||||
expect(redactExplicitText("API_SECRET ordinary evidence", [""])).toBe(
|
||||
"API_SECRET ordinary evidence",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Replace caller-declared literal text values without guessing sensitivity from names. */
|
||||
export const redactExplicitText = (
|
||||
value: string,
|
||||
sensitiveValues: readonly string[],
|
||||
): string => {
|
||||
const literals = [...new Set(sensitiveValues)].filter(
|
||||
(literal) => literal !== "",
|
||||
);
|
||||
const replacement =
|
||||
["[REDACTED]", "…", ""].find((candidate) =>
|
||||
literals.every((literal) => !candidate.includes(literal)),
|
||||
) ?? "";
|
||||
let result = value;
|
||||
for (const literal of literals.sort(
|
||||
(left, right) => right.length - left.length,
|
||||
))
|
||||
result = result.replaceAll(literal, replacement);
|
||||
// Replacement boundaries can form another declaration; exclude that text.
|
||||
return literals.some((literal) => result.includes(literal)) ? "" : result;
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
/** Complete historical evidence budgets; exceeding a budget returns no partial capture. */
|
||||
export const WEB_NETWORK_CAPTURE_LIMITS = {
|
||||
inputBytes: 32 * 1024 * 1024,
|
||||
outputBytes: 96 * 1024 * 1024,
|
||||
timeoutMs: 30_000,
|
||||
depth: 64,
|
||||
} as const;
|
||||
|
||||
/** Inspect an explicit retained capture without contacting its recorded destinations. */
|
||||
export const inspectWebNetworkCaptureInputSchema = z.strictObject({
|
||||
capture_path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Absolute local HAR or mitmproxy capture path."),
|
||||
format: z.enum(["har", "mitmproxy"]),
|
||||
record_ordinals: z
|
||||
.array(z.number().int().nonnegative())
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"Zero-based producer record ordinals, in caller-selected order. Omit to inspect every record.",
|
||||
),
|
||||
sensitive_values: z
|
||||
.array(z.string().min(1))
|
||||
.default([])
|
||||
.describe(
|
||||
"Literal text excluded from capture payloads, byte/numeric projections, producer coordinates, artifact paths/digests and diagnostic text. Declaration strings are never persisted in Evidence parameters. Canonical contract keys, enums and provider identities remain intact.",
|
||||
),
|
||||
});
|
||||
|
||||
const pointerSchema = z
|
||||
.string()
|
||||
.describe("RFC 6901 pointer in the producer's reported object.");
|
||||
const redactionSchema = z.union([
|
||||
z.strictObject({
|
||||
pointer: pointerSchema,
|
||||
reason: z.enum(["transport-credential", "explicit-sensitive-value"]),
|
||||
}),
|
||||
z.strictObject({
|
||||
pointer: pointerSchema,
|
||||
reason: z.literal("explicit-sensitive-value"),
|
||||
scope: z
|
||||
.literal("property-name")
|
||||
.describe(
|
||||
"An omitted property name; pointer identifies its actual parent, not an invented child coordinate.",
|
||||
),
|
||||
}),
|
||||
]);
|
||||
const binaryBase = {
|
||||
pointer: pointerSchema,
|
||||
representation: z.enum(["producer-bytes", "har-base64-content"]),
|
||||
};
|
||||
const binarySchema = z.discriminatedUnion("state", [
|
||||
z.strictObject({
|
||||
...binaryBase,
|
||||
state: z.literal("retained"),
|
||||
content_base64: z.string(),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
sha256: z.string().regex(/^[0-9a-f]{64}$/),
|
||||
}),
|
||||
z.strictObject({
|
||||
...binaryBase,
|
||||
state: z.literal("redacted"),
|
||||
content_base64: z.null(),
|
||||
bytes: z.null(),
|
||||
sha256: z.null(),
|
||||
}),
|
||||
]);
|
||||
const numberSchema = z.strictObject({
|
||||
pointer: pointerSchema,
|
||||
producer_type: z.enum(["json-number", "integer", "float"]),
|
||||
literal: z.string(),
|
||||
});
|
||||
|
||||
/** Preserve producer representations with independent sidecars rather than invented browser IDs. */
|
||||
export const webNetworkCaptureRecordSchema = z.strictObject({
|
||||
ordinal: z.number().int().nonnegative(),
|
||||
location: z.discriminatedUnion("kind", [
|
||||
z.strictObject({
|
||||
kind: z.literal("unknown"),
|
||||
reason: z.literal("explicit-sensitive-value"),
|
||||
}),
|
||||
z.strictObject({ kind: z.literal("json-pointer"), pointer: pointerSchema }),
|
||||
z.strictObject({
|
||||
kind: z.literal("byte-range"),
|
||||
offset: z.number().int().nonnegative(),
|
||||
bytes: z.number().int().positive(),
|
||||
}),
|
||||
]),
|
||||
reported: jsonValueSchema,
|
||||
binary_fields: z.array(binarySchema),
|
||||
numeric_literals: z.array(numberSchema),
|
||||
redactions: z.array(redactionSchema),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
/** Historical capture inspection has file identity, producer provenance and explicit unknowns. */
|
||||
export const webNetworkCaptureSchema = z.strictObject({
|
||||
artifact: z.strictObject({
|
||||
path: z
|
||||
.string()
|
||||
.describe(
|
||||
"Selected artifact path; empty when explicitly excluded from Evidence.",
|
||||
),
|
||||
sha256: z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{64}$/)
|
||||
.nullable()
|
||||
.describe(
|
||||
"Observed artifact SHA-256; null only when explicitly excluded by a sensitive declaration.",
|
||||
),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
}),
|
||||
format: z.enum(["har", "mitmproxy"]),
|
||||
decoder: z.strictObject({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
version: z.string().min(1),
|
||||
}),
|
||||
container: z.strictObject({
|
||||
reported: jsonValueSchema,
|
||||
numeric_literals: z.array(numberSchema),
|
||||
redactions: z.array(redactionSchema),
|
||||
records_pointer: pointerSchema.nullable(),
|
||||
}),
|
||||
total_records: z.number().int().nonnegative(),
|
||||
records: z.array(webNetworkCaptureRecordSchema),
|
||||
runtime_attribution: z.literal("unknown"),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
export type InspectWebNetworkCaptureInput = z.output<
|
||||
typeof inspectWebNetworkCaptureInputSchema
|
||||
>;
|
||||
export type WebNetworkCapture = z.output<typeof webNetworkCaptureSchema>;
|
||||
export type WebNetworkCaptureRecord = z.output<
|
||||
typeof webNetworkCaptureRecordSchema
|
||||
>;
|
||||
@@ -0,0 +1,68 @@
|
||||
import { redactExplicitText } from "./explicitSensitiveValues.js";
|
||||
import type { WebNetworkCapture } from "./webNetworkCapture.js";
|
||||
|
||||
/** Exclude marked source coordinates without inventing a substitute record identity. */
|
||||
export const excludeCaptureCoordinates = (
|
||||
value: WebNetworkCapture,
|
||||
sensitiveValues: readonly string[],
|
||||
): WebNetworkCapture => {
|
||||
if (sensitiveValues.length === 0) return value;
|
||||
let excluded = false;
|
||||
const sensitive = (pointer: string): boolean =>
|
||||
sensitiveValues.some((literal) => pointer.includes(literal));
|
||||
const sidecars = <T extends { readonly pointer: string }>(
|
||||
items: readonly T[],
|
||||
): T[] =>
|
||||
items.filter((item) => {
|
||||
if (!sensitive(item.pointer)) return true;
|
||||
excluded = true;
|
||||
return false;
|
||||
});
|
||||
const records = value.records.map((record) => {
|
||||
const location =
|
||||
(record.location.kind === "json-pointer" &&
|
||||
sensitive(record.location.pointer)) ||
|
||||
(record.location.kind === "byte-range" &&
|
||||
(sensitive(String(record.location.offset)) ||
|
||||
sensitive(String(record.location.bytes))))
|
||||
? {
|
||||
kind: "unknown" as const,
|
||||
reason: "explicit-sensitive-value" as const,
|
||||
}
|
||||
: record.location;
|
||||
if (location !== record.location) excluded = true;
|
||||
return {
|
||||
...record,
|
||||
location,
|
||||
binary_fields: sidecars(record.binary_fields),
|
||||
numeric_literals: sidecars(record.numeric_literals),
|
||||
redactions: sidecars(record.redactions),
|
||||
};
|
||||
});
|
||||
const recordsPointer = value.container.records_pointer;
|
||||
const records_pointer =
|
||||
recordsPointer !== null && sensitive(recordsPointer)
|
||||
? null
|
||||
: recordsPointer;
|
||||
if (records_pointer !== recordsPointer) excluded = true;
|
||||
const container = {
|
||||
...value.container,
|
||||
records_pointer,
|
||||
numeric_literals: sidecars(value.container.numeric_literals),
|
||||
redactions: sidecars(value.container.redactions),
|
||||
};
|
||||
return {
|
||||
...value,
|
||||
container,
|
||||
records,
|
||||
limitations: excluded
|
||||
? [
|
||||
...value.limitations,
|
||||
redactExplicitText(
|
||||
"Marked source coordinates and their sidecars are excluded; affected record locations remain unknown.",
|
||||
sensitiveValues,
|
||||
),
|
||||
]
|
||||
: value.limitations,
|
||||
};
|
||||
};
|
||||
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.3.1",
|
||||
clientSdkVersion: "2.3.1",
|
||||
coreSdkVersion: "2.3.1",
|
||||
skillVersion: "27",
|
||||
skillVersion: "28",
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import type {
|
||||
OwnedProviderProcessSpawnOptions,
|
||||
ProviderProcessSnapshot,
|
||||
SpawnedOwnedProviderProcess,
|
||||
} from "./ProviderProcess.js";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
spawnOwnedProviderProcess,
|
||||
} from "./ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
|
||||
import {
|
||||
ProviderStartupDeadline,
|
||||
waitForAbortableDelay,
|
||||
} from "./ProviderDeadline.js";
|
||||
|
||||
/** A short-lived command failed its lifecycle or complete-output contract. */
|
||||
export class OwnedCommandFailure extends Error {
|
||||
constructor(
|
||||
readonly reason: "cancelled" | "timeout" | "output-limit" | "process",
|
||||
message: string,
|
||||
readonly snapshot: ProviderProcessSnapshot | null = null,
|
||||
readonly cleanupFailure: string | null = null,
|
||||
options?: ErrorOptions,
|
||||
readonly resources: readonly string[] = [],
|
||||
) {
|
||||
super(message, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Execute a single owned process with independent cleanup and bounded diagnostic retention. */
|
||||
export const runOwnedCommand = async (
|
||||
spawn: OwnedProviderProcessSpawnOptions,
|
||||
limits: { readonly timeoutMs: number; readonly diagnosticBytes: number },
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly launcher?: (
|
||||
input: OwnedProviderProcessSpawnOptions,
|
||||
) => Promise<SpawnedOwnedProviderProcess>;
|
||||
} = {},
|
||||
): Promise<ProviderProcessSnapshot> => {
|
||||
const callerSignal = options.signal ?? spawn.signal;
|
||||
if (callerSignal?.aborted)
|
||||
throw new OwnedCommandFailure(
|
||||
"cancelled",
|
||||
"Command cancelled before launch.",
|
||||
);
|
||||
const deadline = new ProviderStartupDeadline(limits.timeoutMs, callerSignal);
|
||||
try {
|
||||
return await collectOwnedCommand(
|
||||
spawn,
|
||||
limits,
|
||||
options.launcher ?? spawnOwnedProviderProcess,
|
||||
deadline,
|
||||
callerSignal,
|
||||
);
|
||||
} finally {
|
||||
deadline.dispose();
|
||||
}
|
||||
};
|
||||
|
||||
const collectOwnedCommand = async (
|
||||
spawn: OwnedProviderProcessSpawnOptions,
|
||||
limits: { readonly diagnosticBytes: number },
|
||||
launcher: (
|
||||
input: OwnedProviderProcessSpawnOptions,
|
||||
) => Promise<SpawnedOwnedProviderProcess>,
|
||||
deadline: ProviderStartupDeadline,
|
||||
callerSignal?: AbortSignal,
|
||||
): Promise<ProviderProcessSnapshot> => {
|
||||
const signal = deadline.signal;
|
||||
let launched: SpawnedOwnedProviderProcess;
|
||||
try {
|
||||
launched = await launcher({
|
||||
...spawn,
|
||||
signal,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
const interruption = deadline.interruption;
|
||||
if (interruption !== undefined)
|
||||
throw new OwnedCommandFailure(
|
||||
interruption,
|
||||
interruption === "cancelled"
|
||||
? "Command cancelled during ownership preparation."
|
||||
: "Command deadline elapsed during ownership preparation.",
|
||||
null,
|
||||
null,
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
let exceeded = false;
|
||||
let processFailure: string | undefined;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{
|
||||
...launched,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
launched.cleanup ??
|
||||
(() => cleanupOwnedProcessGroup(launched.ownership)),
|
||||
},
|
||||
{
|
||||
maxDiagnosticBytes: limits.diagnosticBytes,
|
||||
onDiagnostic: (event) => {
|
||||
if (event.type === "output" && event.truncated === true)
|
||||
exceeded = true;
|
||||
if (event.type === "error") processFailure = event.message;
|
||||
},
|
||||
},
|
||||
);
|
||||
let failure: OwnedCommandFailure | undefined;
|
||||
try {
|
||||
while (!(await supervisor.waitForOutputClose(10))) {
|
||||
const interruption = deadline.interruption;
|
||||
if (interruption !== undefined)
|
||||
throw new OwnedCommandFailure(
|
||||
interruption,
|
||||
interruption === "cancelled"
|
||||
? "Command cancelled."
|
||||
: "Command deadline elapsed.",
|
||||
);
|
||||
if (exceeded)
|
||||
throw new OwnedCommandFailure(
|
||||
"output-limit",
|
||||
"Command diagnostic output exceeded its complete-output budget.",
|
||||
);
|
||||
if (processFailure !== undefined)
|
||||
throw new OwnedCommandFailure("process", processFailure);
|
||||
await waitForAbortableDelay(25, signal);
|
||||
}
|
||||
const snapshot = supervisor.snapshot();
|
||||
const interruption = deadline.interruption;
|
||||
if (interruption !== undefined)
|
||||
throw new OwnedCommandFailure(
|
||||
interruption,
|
||||
interruption === "cancelled"
|
||||
? "Command cancelled."
|
||||
: "Command deadline elapsed.",
|
||||
snapshot,
|
||||
);
|
||||
if (exceeded)
|
||||
throw new OwnedCommandFailure(
|
||||
"output-limit",
|
||||
"Command diagnostic output exceeded its complete-output budget.",
|
||||
snapshot,
|
||||
);
|
||||
if (
|
||||
processFailure !== undefined ||
|
||||
snapshot.exitCode !== 0 ||
|
||||
snapshot.signal !== null
|
||||
)
|
||||
throw new OwnedCommandFailure(
|
||||
"process",
|
||||
processFailure ??
|
||||
"Command failed; inspect its exit status and diagnostics.",
|
||||
snapshot,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
failure =
|
||||
cause instanceof OwnedCommandFailure
|
||||
? cause
|
||||
: new OwnedCommandFailure(
|
||||
"process",
|
||||
"Command collection failed.",
|
||||
null,
|
||||
null,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
const stopped = await supervisor.stop();
|
||||
const snapshot = supervisor.snapshot();
|
||||
supervisor.dispose();
|
||||
if (stopped.status === "incomplete")
|
||||
throw new OwnedCommandFailure(
|
||||
failure?.reason ?? "process",
|
||||
failure?.message ?? "Command cleanup failed.",
|
||||
snapshot,
|
||||
stopped.reason,
|
||||
failure === undefined ? undefined : { cause: failure },
|
||||
[
|
||||
spawn.runId,
|
||||
...(spawn.cwd === undefined ? [] : [spawn.cwd]),
|
||||
`pid:${launched.ownership.leaderPid}`,
|
||||
`process-group:${launched.ownership.processGroupId}`,
|
||||
],
|
||||
);
|
||||
if (failure !== undefined)
|
||||
throw new OwnedCommandFailure(
|
||||
failure.reason,
|
||||
failure.message,
|
||||
snapshot,
|
||||
failure.cleanupFailure,
|
||||
{ cause: failure },
|
||||
failure.resources,
|
||||
);
|
||||
if (callerSignal?.aborted)
|
||||
throw new OwnedCommandFailure("cancelled", "Command cancelled.", snapshot);
|
||||
return snapshot;
|
||||
};
|
||||
@@ -72,6 +72,8 @@ export type ProviderProcessLaunch =
|
||||
|
||||
/** Detached diagnostics captured for one supervised provider process. */
|
||||
export interface ProviderProcessSnapshot {
|
||||
/** True only when a configured diagnostic budget excluded output bytes. */
|
||||
readonly diagnosticTruncated?: boolean;
|
||||
readonly stdout: {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
@@ -91,6 +93,7 @@ export type ProviderProcessDiagnostic =
|
||||
readonly stream: "stdout" | "stderr";
|
||||
readonly bytes: number;
|
||||
readonly totalBytes: number;
|
||||
readonly truncated?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "exit";
|
||||
@@ -104,6 +107,8 @@ export type ProviderProcessDiagnostic =
|
||||
export interface ProviderProcessSupervisorOptions {
|
||||
/** Retain stdout for diagnostics; disable when it carries a parsed protocol. Defaults to true. */
|
||||
readonly captureStdout?: boolean;
|
||||
/** Aggregate retained stdout/stderr byte budget; overflow is drained and reported, not retained. */
|
||||
readonly maxDiagnosticBytes?: number;
|
||||
readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void;
|
||||
}
|
||||
|
||||
@@ -209,6 +214,9 @@ export class ProviderProcessSupervisor {
|
||||
}>();
|
||||
readonly #outputClose = deferred<void>();
|
||||
#outputClosed = false;
|
||||
#stdoutObservedBytes = 0;
|
||||
#stderrObservedBytes = 0;
|
||||
#diagnosticTruncated = false;
|
||||
readonly #onStdout = (chunk: Buffer | string): void => {
|
||||
this.#capture("stdout", this.#stdout, chunk);
|
||||
};
|
||||
@@ -253,9 +261,10 @@ export class ProviderProcessSupervisor {
|
||||
this.#recordExit(launch.process.exitCode, launch.process.signalCode);
|
||||
}
|
||||
|
||||
/** Latest complete output and exit observation. */
|
||||
/** Latest retained output and exit observation, with explicit configured truncation. */
|
||||
snapshot(): ProviderProcessSnapshot {
|
||||
return {
|
||||
...(this.#diagnosticTruncated ? { diagnosticTruncated: true } : {}),
|
||||
stdout: this.#stdout.snapshot(),
|
||||
stderr: this.#stderr.snapshot(),
|
||||
exitCode: this.#exitObservation?.code,
|
||||
@@ -267,6 +276,9 @@ export class ProviderProcessSupervisor {
|
||||
resetOutput(): void {
|
||||
this.#stdout.reset();
|
||||
this.#stderr.reset();
|
||||
this.#stdoutObservedBytes = 0;
|
||||
this.#stderrObservedBytes = 0;
|
||||
this.#diagnosticTruncated = false;
|
||||
}
|
||||
|
||||
/** Wait for process exit up to a caller-owned bounded interval. */
|
||||
@@ -388,12 +400,29 @@ export class ProviderProcessSupervisor {
|
||||
chunk: Buffer | string,
|
||||
): void {
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
capture.append(bytes);
|
||||
if (stream === "stdout") this.#stdoutObservedBytes += bytes.byteLength;
|
||||
else this.#stderrObservedBytes += bytes.byteLength;
|
||||
const remaining =
|
||||
this.#options.maxDiagnosticBytes === undefined
|
||||
? bytes.byteLength
|
||||
: Math.max(
|
||||
0,
|
||||
this.#options.maxDiagnosticBytes -
|
||||
this.#stdout.bytes -
|
||||
this.#stderr.bytes,
|
||||
);
|
||||
const retained = Math.min(bytes.byteLength, remaining);
|
||||
if (retained < bytes.byteLength) this.#diagnosticTruncated = true;
|
||||
if (retained > 0) capture.append(bytes.subarray(0, retained));
|
||||
this.#options.onDiagnostic?.({
|
||||
type: "output",
|
||||
stream,
|
||||
bytes: bytes.byteLength,
|
||||
totalBytes: capture.bytes,
|
||||
totalBytes:
|
||||
stream === "stdout"
|
||||
? this.#stdoutObservedBytes
|
||||
: this.#stderrObservedBytes,
|
||||
...(retained < bytes.byteLength ? { truncated: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -364,15 +364,30 @@ const filesystemFailure = (cause: unknown): string | undefined => {
|
||||
return `Executable file observation failed: ${cause.message}`;
|
||||
};
|
||||
|
||||
/** Sample the caller-selected executable contents and stable file identity before launch. */
|
||||
/** Metadata IO seam for deterministic prelaunch cancellation and identity checks. */
|
||||
export interface SelectedExecutableFileSystem {
|
||||
open(path: string, flags: number): ReturnType<typeof open>;
|
||||
stat(path: string): Promise<BigIntStats>;
|
||||
}
|
||||
|
||||
const selectedExecutableFileSystem: SelectedExecutableFileSystem = {
|
||||
open,
|
||||
stat: (path) => stat(path, { bigint: true }),
|
||||
};
|
||||
|
||||
/** Sample the selected file without launching it; retain cancellation and file identity. */
|
||||
export const observeSelectedExecutable = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
fileSystem: SelectedExecutableFileSystem = selectedExecutableFileSystem,
|
||||
): Promise<SelectedExecutableObservation> => {
|
||||
assertNotCancelled(signal);
|
||||
let handle: Awaited<ReturnType<typeof open>> | undefined;
|
||||
try {
|
||||
handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
||||
handle = await fileSystem.open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NONBLOCK,
|
||||
);
|
||||
const openedStats = await handle.stat({ bigint: true });
|
||||
if (!openedStats.isFile())
|
||||
return {
|
||||
@@ -381,9 +396,7 @@ export const observeSelectedExecutable = async (
|
||||
reason: "Selected executable is not a regular file.",
|
||||
};
|
||||
const openedIdentity = identityFromStats(openedStats);
|
||||
const selectedPathIdentity = identityFromStats(
|
||||
await stat(path, { bigint: true }),
|
||||
);
|
||||
const selectedPathIdentity = identityFromStats(await fileSystem.stat(path));
|
||||
if (!sameExecutableIdentity(openedIdentity, selectedPathIdentity))
|
||||
return {
|
||||
sha256: null,
|
||||
@@ -391,6 +404,9 @@ export const observeSelectedExecutable = async (
|
||||
reason: "Selected executable path changed while it was being opened.",
|
||||
};
|
||||
|
||||
// IO above can settle after cancellation. Do not construct a stream with an
|
||||
// already-aborted signal: Node can emit a second, unhandled AbortError.
|
||||
assertNotCancelled(signal);
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of handle.createReadStream({
|
||||
autoClose: false,
|
||||
|
||||
@@ -25,6 +25,9 @@ import type { WebSourceLocationService } from "../application/WebSourceLocationS
|
||||
import type { WebRuntimeService } from "../application/WebRuntimeService.js";
|
||||
import { createWebRuntimeService } from "../composition/webRuntime.js";
|
||||
import { registerWebRuntimeTools } from "./registerWebRuntimeTools.js";
|
||||
import type { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
|
||||
import { createWebNetworkCaptureService } from "../composition/webNetworkCaptures.js";
|
||||
import { registerWebNetworkCaptureTool } from "./registerWebNetworkCaptureTool.js";
|
||||
import { registerJavaScriptRecoveryTool } from "./registerJavaScriptRecoveryTool.js";
|
||||
import { JavaScriptRecoveryService } from "../application/javascript/JavaScriptRecoveryService.js";
|
||||
import type { JavaScriptRecoveryPort } from "../application/javascript/JavaScriptRecoveryPort.js";
|
||||
@@ -62,6 +65,7 @@ export interface CreateServerOptions {
|
||||
readonly webModuleTrace?: WebModuleTraceService;
|
||||
readonly webSourceLocation?: WebSourceLocationService;
|
||||
readonly webRuntime?: WebRuntimeService;
|
||||
readonly webNetworkCapture?: WebNetworkCaptureService;
|
||||
readonly androidAnalysis?: AndroidAnalysisPort;
|
||||
readonly browserObservation?: BrowserObservationPort;
|
||||
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
|
||||
@@ -213,6 +217,12 @@ export const createServer = (
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerWebNetworkCaptureTool(
|
||||
server,
|
||||
options.webNetworkCapture ?? createWebNetworkCaptureService(),
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerJavaScriptRecoveryTool(
|
||||
server,
|
||||
new JavaScriptRecoveryService(
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type {
|
||||
McpServer,
|
||||
StandardSchemaWithJSON,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import type { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
|
||||
/** Bind historical inspection to its named contract and caller-owned Evidence writer. */
|
||||
export const registerWebNetworkCaptureTool = (
|
||||
server: McpServer,
|
||||
service: WebNetworkCaptureService,
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
): void => {
|
||||
const contract = toolContract("inspect_web_network_capture");
|
||||
const registration = toolRegistrationOptions(contract);
|
||||
// Keep the exact advertised contract; the shared service validates raw input
|
||||
// before effects so caller-declared sensitivity also covers invalid arguments.
|
||||
// SDK pre-validation otherwise emits unprojected issue paths as plain text.
|
||||
const inputSchema: StandardSchemaWithJSON = {
|
||||
"~standard": {
|
||||
...registration.inputSchema["~standard"],
|
||||
vendor: "rea-application",
|
||||
validate: (value: unknown) => ({ value }),
|
||||
},
|
||||
};
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
{ ...registration, inputSchema },
|
||||
async (input, context) => {
|
||||
const result = await logToolExecution(logger, contract.name, () =>
|
||||
service.inspect(input, { signal: context.mcpReq.signal }),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordEvidence?.(result.value);
|
||||
return recorded !== undefined && !recorded.ok
|
||||
? toCallToolResult(recorded, contract)
|
||||
: toCallToolResult(result, contract);
|
||||
},
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user