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,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,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user