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:
Ysopwnable
2026-10-08 07:53:41 +08:00
committed by GitHub
co-authored by Kaoru0822 github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
parent 6e4535c101
commit 2bf3663f65
77 changed files with 6315 additions and 47 deletions
+198
View File
@@ -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;
};
+32 -3
View File
@@ -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 } : {}),
});
}
+21 -5
View File
@@ -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,