Files
reverse-engineering-anything/src/application/WebNetworkCaptureService.ts
T
Abhishek SharmaandClaude Sonnet 5.5 3c7ea1ce85 feat(browser): count credential-named members in HAR capture inspection (#8708)
* feat(browser): count credential-named members in HAR capture inspection

inspect_web_network_capture now runs the credential-name scan that
environment-build already applies over the selected HAR records and
reports matches as limitations by pointer, never by value, together with
the bodies the scan could not read. Values the decoder already excluded
are not counted, and nothing is excluded on a name.

Refs #8207

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(browser): bound the listed credential-name pointers

The limitation lists the pointers that fit within 1 KiB of text and says
how many counted names are not listed, so one long body member name
cannot inflate the limitation that summaries and record pages repeat.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(environment): bound the credential scan's values before parsing a body

A body under the scan's 4 MiB text limit could still expand into millions
of JSON values or form fields when parsed in the application process, and
the inspection now runs the scan on every HAR capture. The scan counts the
characters that can start a value (`[`, `{`, `,` for JSON, `&` for forms)
before parsing and skips a body that could hold more than 524288, reporting
it like a body over the text limit. Both consumers' messages and docs name
the bound.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(web): charge every body and name/value list to one credential-scan budget

The credential-name scan bounded each body's values on its own, so a
capture of many compact bodies still expanded millions of values in the
application process, and HAR header, query and form-parameter lists were
copied twice without any bound. One 524288-value budget now covers the
whole scan: a body's values are bounded from its text before it is parsed
and a list is charged by its length before it is read in place, so what
would pass the budget is reported as not scanned instead.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(web): read credential names in place and charge nothing for empty text

The credential-name scan split each member, header and query name with
two regex replacements, a lowercase copy and a split into a segment
array before matching. A near-4 MiB alternating-case member name
(`x-aAaA…`) therefore expanded into about two million segments: more
than 192 MiB of heap in the application process after the decoder's
containment had ended. `credentialNamed` now reads the name once in
place with the same segmentation (case changes, digits, separators, and
`toLowerCase`'s KELVIN SIGN and dotted capital I), keeping at most two
segments no longer than the longest credential word, so a name of any
length allocates no copies.

`valueBound` started every text at one value, so an empty query, a bare
`?`, an empty form and whitespace-only JSON were each charged a value
they do not hold; once earlier content spent the budget, they were
reported as unscanned in `credential-scan-incomplete`. JSON now holds its
first value only after a non-whitespace character, and a form holds one
field per non-empty `&`-separated piece after an optional leading `?`,
as `URLSearchParams` and the query reader split it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(browser): point the environment build link at the physical guide

The guide lives at docs/agent-environments.md, so the relative link from
docs/guides/web must climb two levels. The Documentation job failed on the
dead link; vitepress build now completes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test: drop the hard-coded timeout from the heap-bound name test

The test finishes in about half a second, so the shared test deadline is
enough, and a literal 60_000 bypasses the CI and coverage deadline scaling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(web-network-capture): name an unavailable response source in the scan limitation

The credential-name scan counts a response body whose retained source is
unavailable as not scanned, and WebNetworkCaptureService reuses that scan. Its
limitation text still listed only a cut body, text over 4 MiB, or past the value
budget, so CLI and MCP reports gave none of those reasons for such a body.

Name the unavailable source in the text, matching the environment-build warning,
and cover it with a test that fails on the old wording.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-22 15:42:13 +08:00

352 lines
13 KiB
TypeScript

import { unknownTarget } from "../domain/targetIdentity.js";
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
import { excludeCaptureCoordinates } from "../domain/webNetworkCaptureCoordinates.js";
import { redactExplicitText } from "../domain/explicitSensitiveValues.js";
import type { ExecutionOptions } from "../ports/AnalysisProvider.js";
import type { WebNetworkCapturePort } from "./WebNetworkCapturePort.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisInputError,
AnalysisOutputError,
cancelledBy,
} from "../domain/analysisErrorCore.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
inspectWebNetworkCaptureInputSchema,
captureSensitiveValues,
webNetworkCaptureSchema,
type InspectWebNetworkCaptureInput,
type WebNetworkCapture,
} from "../domain/webNetworkCapture.js";
import { completeProviderEvidence } from "./ProviderOperationExecution.js";
import { scanCredentialNames } from "./environment/environmentBuildReport.js";
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.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) {}
/** Release resources retained by the selected capture adapter. */
close(): Promise<void> {
return this.port.close?.() ?? Promise.resolve();
}
/** 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(cancelledBy(OPERATION, options.signal));
const failure = (error: AnalysisError): Result<never, AnalysisError> =>
err(redactExplicitFailure(error, captureSensitiveValues(rawInput)));
const parsed = inspectWebNetworkCaptureInputSchema.safeParse(rawInput);
if (!parsed.success)
return failure(
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput, {
cause: parsed.error,
}),
);
const input = parsed.data;
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.",
},
]),
);
if (input.protobuf !== undefined && input.record_ordinals === undefined)
return failure(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["record_ordinals"],
reason: "invalid_format",
message:
"Protobuf options require explicit producer record ordinals.",
},
]),
);
const loaded = await this.port.inspect(input, options);
if (!loaded.ok) {
const partial = webNetworkCaptureSchema.safeParse(
loaded.error.partialObservation,
);
let partialFailure: AnalysisError | undefined;
if (partial.success) {
const projected = this.#projectCapture(input, partial.data);
if (projected.ok) loaded.error.partialObservation = projected.value;
else partialFailure = projected.error;
} else if (isCapturePartialCandidate(loaded.error.partialObservation)) {
partialFailure = new AnalysisOutputError(
OPERATION,
"Capture adapter retained malformed historical evidence.",
{ cause: partial.error },
);
}
if (partialFailure !== undefined) {
const rejected = loaded.error.partialObservation;
for (
let owner: AnalysisError | undefined = loaded.error;
owner !== undefined;
owner = owner.cleanupPrimary
) {
if (owner.partialObservation === rejected)
owner.partialObservation = undefined;
}
partialFailure.retainSecondaryFailure(loaded.error);
return failure(
loaded.error.cleanupIncomplete
? analysisErrorWithCleanupDependencies(
partialFailure,
loaded.error,
OPERATION,
)
: partialFailure,
);
}
return failure(loaded.error);
}
const report = webNetworkCaptureSchema.safeParse(loaded.value);
if (!report.success)
return failure(
new AnalysisOutputError(
OPERATION,
"Capture adapter returned malformed historical evidence.",
),
);
const projected = this.#projectCapture(input, report.data);
if (!projected.ok) return failure(projected.error);
return completeProviderEvidence(projected.value, options?.signal);
}
#projectCapture(
input: InspectWebNetworkCaptureInput,
value: WebNetworkCapture,
): Result<Evidence, AnalysisError> {
const artifactSha256 = value.artifact.sha256;
if (artifactSha256 === null)
return err(
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 err(
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 isSensitive = (text: string): boolean =>
input.sensitive_values.some((literal) => text.includes(literal));
const selected =
input.record_ordinals ?? value.records.map(({ ordinal }) => ordinal);
const records = [];
for (const [index, ordinal] of selected.entries()) {
const record = safeValue.records[ordinal];
// A selection past the capture's records is a caller range fault.
if (record === undefined)
return err(
new AnalysisInputError(OPERATION, undefined, [
value.total_records === 0
? {
path: ["record_ordinals", index],
reason: "invalid_value",
message: "The selected capture contains no records.",
}
: {
path: ["record_ordinals", index],
reason: "out_of_range",
minimum: 0,
maximum: value.total_records - 1,
message: `Producer ordinal ${ordinal} is outside the retained capture (${value.total_records} records).`,
},
]),
);
records.push({
...record,
limitations: record.limitations.map(redactText),
});
}
const safePath = isSensitive(input.capture_path) ? "" : input.capture_path;
const safeSha256 = isSensitive(artifactSha256) ? 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.",
]
: []),
...(safeValue.format === "har"
? credentialNameLimitations(scanCredentialNames(records))
: []),
].map(redactText);
const parameters = jsonObjectSchema.parse({
capture_path: safePath,
...(isSensitive(input.format) ? {} : { format: input.format }),
record_ordinals: selected,
...(input.protobuf === undefined
? {}
: {
protobuf: {
framing: input.protobuf.framing,
...(input.protobuf.body_pointers === undefined
? {}
: {
body_pointers: input.protobuf.body_pointers.map(redactText),
}),
...(input.protobuf.schema === undefined
? {}
: {
schema: {
descriptor_set_path: redactText(
input.protobuf.schema.descriptor_set_path,
),
message_type: redactText(
input.protobuf.schema.message_type,
),
},
}),
},
}),
sensitive_value_count: input.sensitive_values.length,
...(input.max_input_bytes === undefined
? {}
: { max_input_bytes: input.max_input_bytes }),
...(input.max_reply_bytes === undefined
? {}
: { max_reply_bytes: input.max_reply_bytes }),
...(input.max_nesting_depth === undefined
? {}
: { max_nesting_depth: input.max_nesting_depth }),
...(input.capture_timeout_ms === undefined
? {}
: { capture_timeout_ms: input.capture_timeout_ms }),
});
const evidence = createEvidence(
safeSha256 === null
? unknownTarget("not-observed")
: {
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,
},
...(safeValue.format !== "qlog"
? {}
: {
analysisProfile: createAnalysisProfile(value.decoder, {
qlog_profile: safeValue.qlog.profile,
clock: safeValue.qlog.clock,
scope: safeValue.qlog.scope,
}),
}),
confidence: "observed",
authority: "historical-reference",
limitations:
safeSha256 === null
? [subjectUnavailableReason, ...limitations]
: limitations,
locations:
safePath === "" ? [] : [{ kind: "artifact-path", path: safePath }],
},
);
return ok(evidence);
}
}
/** A count with its first pointers, as the credential-name scan tallies them. */
type ScanTally = {
readonly count: number;
readonly pointers: readonly string[];
};
/** Listed pointers stay within this many characters, so one long member name cannot inflate a limitation. */
const LISTED_POINTER_CHARACTERS = 1024;
/** The pointers that fit the sample in order, then how many of the counted names are not listed. */
const listedPointers = (tally: ScanTally): string => {
const listed: string[] = [];
let length = 0;
for (const pointer of tally.pointers) {
const added = pointer.length + (listed.length > 0 ? 2 : 0);
if (length + added > LISTED_POINTER_CHARACTERS) break;
length += added;
listed.push(pointer);
}
const unlisted = tally.count - listed.length;
if (unlisted === 0) return listed.join(", ");
const rest = `${String(unlisted)} ${listed.length > 0 ? "more " : ""}not listed`;
return listed.length > 0 ? `${listed.join(", ")}; ${rest}` : rest;
};
/**
* The credential-name scan environment-build runs over selected HAR records,
* as limitations: counts and pointers to names that hold a retained value,
* never the values, and what the scan did not read.
*/
const credentialNameLimitations = (
scan: ReturnType<typeof scanCredentialNames>,
): string[] => [
...(scan.count > 0
? [
`${String(scan.count)} recorded header, query parameter or body member names look like credentials and hold a retained value (${listedPointers(scan)}); names do not establish sensitivity, so declare the values as explicitly sensitive to exclude them.`,
]
: []),
...(scan.skipped.count > 0
? [
`${String(scan.skipped.count)} recorded bodies, header lists or query strings were not scanned: each is cut, over 4 MiB of text, past the 524288 values the credential-name scan reads in all, or a response body whose retained source is unavailable (${listedPointers(scan.skipped)}).`,
]
: []),
];
const isCapturePartialCandidate = (value: unknown): boolean => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return false;
const candidate = value as Record<string, unknown>;
return (
"artifact" in candidate &&
["format", "records", "decoder"].some((field) => field in candidate)
);
};