chore: reconcile iNES support with current main

This commit is contained in:
64579525
2026-10-13 11:42:47 +08:00
83 changed files with 5172 additions and 399 deletions
+77 -6
View File
@@ -55,7 +55,24 @@ import {
wasmViewItemSchema,
wasmSummarySchema,
} from "./wasmArtifactView.js";
import {
projectWebNetworkCaptureView,
captureViewRequestSchema,
captureViewItemsSchema,
captureSummarySchema,
} from "./webNetworkCaptureView.js";
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
import {
qlogViewRequestSchema,
qlogViewPageSchema,
qlogViewContextSchema,
} from "./qlogCaptureView.js";
import {
projectAndroidPackageView,
androidPackageSummarySchema,
androidViewRequestSchema,
androidManifestViewItemSchema,
} from "./androidPackageView.js";
/** Public name of the selected-view workflow. */
export const INSPECT_ANALYSIS_VIEW_OPERATION = "inspect_analysis_view" as const;
@@ -169,7 +186,10 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
wasmViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
androidViewRequestSchema,
apiSurfaceViewSchema,
captureViewRequestSchema,
qlogViewRequestSchema,
]);
// The application owns admission and authenticated Evidence parsing. SDK and
@@ -209,7 +229,7 @@ const artifactSchema = z.strictObject({
path: z
.string()
.describe("Exact recorded artifact path, including an empty string."),
sha256: digestSchema,
sha256: digestSchema.nullable(),
});
const layoutSummarySchema = z.strictObject({
@@ -283,6 +303,8 @@ const viewResultBase = {
"inspect_wasm_artifact",
"inspect_evm_interface",
"inspect_managed_artifact",
"inspect_web_network_capture",
"inspect_android_package",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -340,6 +362,20 @@ export const managedArtifactSummaryViewResultSchema = z.strictObject({
summary: managedSummarySchema,
});
/** Exact historical capture summary, with no body or member-inventory payload. */
export const webNetworkCaptureSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
summary: captureSummarySchema,
});
/** Exact package declarations with retained decoded manifest text. */
export const androidPackageSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_android_package"),
summary: androidPackageSummarySchema,
});
/** Projected facts for one selected view of retained analysis Evidence. */
export const analysisViewResultSchema = z.discriminatedUnion("kind", [
z.strictObject({
@@ -362,8 +398,25 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
wasmSummarySchema,
evmSummarySchema,
managedSummarySchema,
captureSummarySchema,
androidPackageSummarySchema,
]),
}),
z.strictObject({
kind: z.literal("capture"),
view: captureViewRequestSchema,
items: captureViewItemsSchema,
...viewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
}),
z.strictObject({
kind: z.literal("qlog"),
view: qlogViewRequestSchema,
page: qlogViewPageSchema,
context: qlogViewContextSchema,
...viewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
}),
z.strictObject({
kind: z.literal("facet"),
view: facetViewSchema,
@@ -410,6 +463,13 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...managedViewContextSchema.shape,
parent_operation: z.literal("inspect_managed_artifact"),
}),
z.strictObject({
kind: z.literal("android"),
view: androidViewRequestSchema,
item: androidManifestViewItemSchema,
...viewResultBase,
parent_operation: z.literal("inspect_android_package"),
}),
z.strictObject({
kind: z.literal("inventory"),
view: inventoryViewSchema,
@@ -477,9 +537,18 @@ export type UnsignedAnalysisView =
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "capture" }>,
"view_digest"
>
| Omit<
Extract<AnalysisViewResult, { readonly kind: "managed" }>,
"view_digest"
>
| Omit<
Extract<AnalysisViewResult, { readonly kind: "android" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
@@ -525,7 +594,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -554,6 +623,7 @@ const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_android_package", projectAndroidPackageView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
]);
@@ -575,10 +645,7 @@ export const projectAnalysisView = (
},
]),
);
if (
view.kind === "api-surface" ||
parent.operation === "inspect_web_network_capture"
) {
if (view.kind === "api-surface") {
const projected = projectWebNetworkApiSurfaceView(
parent,
view,
@@ -586,6 +653,10 @@ export const projectAnalysisView = (
);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_web_network_capture") {
const projected = projectWebNetworkCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_binary_layout") {
const layout = binaryLayoutSchema.safeParse(parent.normalizedResult);
if (!layout.success)
@@ -0,0 +1,136 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { androidResultSchemas } from "../android/androidAnalysis.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import { completeWithinViewCoverage } from "./analysisViewCoverage.js";
import { analysisTextPage } from "./analysisViewText.js";
const packageSchema = androidResultSchemas.inspect_android_package;
/** All package declarations remain inline; decoded manifest text stays retained. */
export const androidPackageSummarySchema = packageSchema.extend({
manifest: packageSchema.shape.manifest.omit({ text: true }).extend({
text_code_units: z.number().int().nonnegative(),
text_included: z.literal(false),
}),
});
/** Exact decoded text; offsets and limits count UTF-16 code units. */
export const androidViewRequestSchema = z.strictObject({
kind: z.literal("android"),
facet: z.literal("manifest"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive(),
});
export const androidManifestViewItemSchema = z.strictObject({
text: z.string(),
unit: z.literal("utf16-code-units"),
source_status: packageSchema.shape.manifest.shape.status,
reported_total_bytes: packageSchema.shape.manifest.shape.reported_total_bytes,
});
/** Project an authenticated package record without reopening the APK or engine. */
export const projectAndroidPackageView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "android")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Android package Evidence supports summary and manifest views.",
},
]),
);
const parsed = packageSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
// Engine artifact_sha256 identifies the JAR, never the APK. A missing
// authenticated APK subject cannot be repaired using the engine identity.
if (parent.subject == null)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Android package views require the recorded APK subject identity.",
},
]),
);
const report = parsed.data;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_android_package" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
},
limitations: [...parent.limitations],
unknowns: [
"APK signatures were not verified; package declarations do not establish authenticity or runtime behavior.",
...(report.manifest.status === "partial"
? [
"The decoded manifest is partial; exhausting retained text does not establish complete manifest coverage.",
]
: []),
],
};
if (view.kind === "summary") {
const { text, ...manifest } = report.manifest;
return ok({
kind: "summary",
view,
...shared,
summary: {
...report,
manifest: {
...manifest,
text_code_units: text.length,
text_included: false,
},
},
coverage: completeWithinViewCoverage(1, 1),
});
}
const page = analysisTextPage(
report.manifest.text,
view.offset,
view.limit,
"Manifest",
);
if (!page.ok) return page;
return ok({
kind: "android",
view,
...shared,
item: {
...page.value.item,
source_status: report.manifest.status,
reported_total_bytes: report.manifest.reported_total_bytes,
},
coverage: page.value.coverage,
});
};
@@ -241,22 +241,14 @@ export const projectJavaScriptApplicationView = (
analysis: JavaScriptApplicationAnalysisResult,
view: Exclude<AnalysisViewRequest, { kind: "api-surface" }>,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "item" && view.kind !== "page")
return err(
jsIncompatible(
"JavaScript application Evidence supports summary, module item or module page views.",
),
);
const shared = parentFields(parent, analysis);
const modules = moduleEntries(analysis.graph.nodes);
if (view.kind === "native")
return err(
jsIncompatible("Native views require analyze_function Evidence."),
);
if (view.kind === "inventory")
return err(jsIncompatible("Inventory views require artifact Evidence."));
if (view.kind === "wasm")
return err(
jsIncompatible("WASM views require inspect_wasm_artifact Evidence."),
);
if (view.kind === "evm")
return err(
jsIncompatible("EVM views require inspect_evm_interface Evidence."),
);
if (view.kind === "summary")
return ok({
kind: "summary",
@@ -291,12 +283,6 @@ export const projectJavaScriptApplicationView = (
coverage: completeCoverage(modules.length, analysis.graph.nodes.length),
...shared,
});
if (view.kind === "facet")
return err(
jsIncompatible(
"facet views apply to inspect_binary_layout Evidence (mitigations or linkage).",
),
);
if (view.kind === "item") {
if (view.collection !== "modules")
return err(
@@ -314,7 +300,7 @@ export const projectJavaScriptApplicationView = (
...shared,
});
}
if (view.collection !== "modules")
if (view.kind !== "page" || view.collection !== "modules")
return err(
jsIncompatible(
"Section and symbol collections apply to inspect_binary_layout Evidence.",
+248
View File
@@ -0,0 +1,248 @@
import { z } from "zod";
import {
qlogCaptureFactsSchema,
type QlogCaptureFacts,
} from "../qlogCapture.js";
import { err, ok, type Result } from "../result.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { analysisViewInputError } from "./analysisView.js";
import { pageViewCoverage } from "./analysisViewCoverage.js";
const traceSchema = qlogCaptureFactsSchema.shape.traces.element;
const streamSchema = traceSchema.shape.streams.element;
export const qlogViewContextSchema = qlogCaptureFactsSchema.omit({
traces: true,
});
export const qlogSummarySchema = qlogViewContextSchema.extend({
trace_count: z.number().int().nonnegative(),
retained_stream_count: z.number().int().nonnegative(),
loss_declaration_count: z.number().int().nonnegative(),
incomplete_fact_record_count: z.number().int().nonnegative(),
});
/** Select retained trace facts without copying event inventories or every contribution. */
const pageRequestShape = {
kind: z.literal("qlog"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
};
const traceSelectorShape = { trace_index: z.number().int().nonnegative() };
const streamSelectorShape = {
...traceSelectorShape,
stream_id: streamSchema.shape.stream_id,
direction: streamSchema.shape.direction,
};
export const qlogViewRequestSchema = z.discriminatedUnion("facet", [
z.strictObject({ ...pageRequestShape, facet: z.literal("traces") }),
z.strictObject({
...pageRequestShape,
...traceSelectorShape,
facet: z.literal("streams"),
}),
z.strictObject({
...pageRequestShape,
...traceSelectorShape,
facet: z.literal("loss-declarations"),
}),
z.strictObject({
...pageRequestShape,
...traceSelectorShape,
facet: z.literal("incomplete-records"),
}),
z.strictObject({
...pageRequestShape,
...streamSelectorShape,
facet: z.literal("contributions"),
}),
z.strictObject({
...pageRequestShape,
...streamSelectorShape,
facet: z.literal("ranges"),
}),
z.strictObject({
...pageRequestShape,
...streamSelectorShape,
facet: z.literal("final-sizes"),
}),
]);
export type QlogViewRequest = z.output<typeof qlogViewRequestSchema>;
const traceSummarySchema = traceSchema
.omit({
streams: true,
loss_declarations: true,
incomplete_fact_records: true,
})
.extend({
stream_count: z.number().int().nonnegative(),
loss_declaration_count: z.number().int().nonnegative(),
incomplete_fact_record_count: z.number().int().nonnegative(),
});
const streamSummarySchema = streamSchema
.omit({
contributions: true,
covered_ranges: true,
reported_final_sizes: true,
})
.extend({
contribution_count: z.number().int().nonnegative(),
covered_range_count: z.number().int().nonnegative(),
reported_final_size_count: z.number().int().nonnegative(),
});
/** Each page advertises exactly the retained item contract for its facet. */
export const qlogViewPageSchema = z.discriminatedUnion("facet", [
z.strictObject({
facet: z.literal("traces"),
items: z.array(traceSummarySchema),
}),
z.strictObject({
facet: z.literal("streams"),
items: z.array(streamSummarySchema),
}),
z.strictObject({
facet: z.literal("loss-declarations"),
items: traceSchema.shape.loss_declarations,
}),
z.strictObject({
facet: z.literal("incomplete-records"),
items: traceSchema.shape.incomplete_fact_records,
}),
z.strictObject({
facet: z.literal("contributions"),
items: streamSchema.shape.contributions,
}),
z.strictObject({
facet: z.literal("ranges"),
items: streamSchema.shape.covered_ranges,
}),
z.strictObject({
facet: z.literal("final-sizes"),
items: streamSchema.shape.reported_final_sizes,
}),
]);
type QlogViewPage = z.output<typeof qlogViewPageSchema>;
export const summarizeQlogCapture = (qlog: QlogCaptureFacts) => {
const { traces, ...context } = qlog;
return {
...context,
trace_count: traces.length,
retained_stream_count: traces.reduce(
(sum, trace) => sum + trace.streams.length,
0,
),
loss_declaration_count: traces.reduce(
(sum, trace) => sum + trace.loss_declarations.length,
0,
),
incomplete_fact_record_count: traces.reduce(
(sum, trace) => sum + trace.incomplete_fact_records.length,
0,
),
};
};
const summarizeTrace = ({
streams,
loss_declarations,
incomplete_fact_records,
...trace
}: QlogCaptureFacts["traces"][number]) => ({
...trace,
stream_count: streams.length,
loss_declaration_count: loss_declarations.length,
incomplete_fact_record_count: incomplete_fact_records.length,
});
const summarizeStream = ({
contributions,
covered_ranges,
reported_final_sizes,
...stream
}: QlogCaptureFacts["traces"][number]["streams"][number]) => ({
...stream,
contribution_count: contributions.length,
covered_range_count: covered_ranges.length,
reported_final_size_count: reported_final_sizes.length,
});
/** Array offsets refer to retained facts, whose scope remains all recorded events. */
export const projectQlogCapturePage = (
qlog: QlogCaptureFacts,
view: QlogViewRequest,
): Result<
{
context: z.output<typeof qlogViewContextSchema>;
page: QlogViewPage;
coverage: ReturnType<typeof pageViewCoverage>;
},
AnalysisError
> => {
const invalid = (field: string, message: string) =>
err(
analysisViewInputError([
{ path: ["view", field], reason: "invalid_value", message },
]),
);
const slice = <T>(items: readonly T[]) =>
items.slice(view.offset, view.offset + view.limit);
let page: QlogViewPage;
let total: number;
if (view.facet === "traces") {
total = qlog.traces.length;
page = {
facet: "traces",
items: slice(qlog.traces).map(summarizeTrace),
};
} else {
const matches = qlog.traces.filter(
(trace) => trace.trace_index === view.trace_index,
);
if (matches.length !== 1)
return invalid(
"trace_index",
"Select one unambiguous retained trace index.",
);
const trace = matches[0]!;
if (view.facet === "streams") {
total = trace.streams.length;
page = {
facet: "streams",
items: slice(trace.streams).map(summarizeStream),
};
} else if (view.facet === "loss-declarations") {
total = trace.loss_declarations.length;
page = { facet: view.facet, items: slice(trace.loss_declarations) };
} else if (view.facet === "incomplete-records") {
total = trace.incomplete_fact_records.length;
page = { facet: view.facet, items: slice(trace.incomplete_fact_records) };
} else {
const matches = trace.streams.filter(
(stream) =>
stream.stream_id === view.stream_id &&
stream.direction === view.direction,
);
if (matches.length !== 1)
return invalid(
"stream_id",
"Select one unambiguous retained stream ID and direction within the trace.",
);
const stream = matches[0]!;
if (view.facet === "contributions") {
total = stream.contributions.length;
page = { facet: view.facet, items: slice(stream.contributions) };
} else if (view.facet === "ranges") {
total = stream.covered_ranges.length;
page = { facet: view.facet, items: slice(stream.covered_ranges) };
} else {
total = stream.reported_final_sizes.length;
page = { facet: view.facet, items: slice(stream.reported_final_sizes) };
}
}
}
const { traces: _traces, ...context } = qlog;
return ok({
context,
page,
coverage: pageViewCoverage(view.offset, page.items.length, total),
});
};
@@ -85,11 +85,13 @@ it("pages groups independently of record completeness and preserves null digests
});
it("rejects native captures and malformed parents with typed errors", () => {
const capture = analysisViewCaptureFixture();
capture.format = "mitmproxy";
expect(project(capture)).toMatchObject({
ok: false,
error: { _tag: "AnalysisUnsupportedTargetError" },
});
for (const format of ["mitmproxy", "saz"] as const) {
capture.format = format;
expect(project(capture)).toMatchObject({
ok: false,
error: { _tag: "AnalysisUnsupportedTargetError" },
});
}
expect(
projectAnalysisView(
{
@@ -0,0 +1,176 @@
import { expect, it } from "vitest";
import { createHash } from "node:crypto";
import { createEvidence } from "../evidence.js";
import { webNetworkCaptureSchema } from "../webNetworkCapture.js";
import { projectAnalysisView } from "./analysisView.js";
const capture = () => {
const body = Buffer.from("original body");
const artifact = {
path: "/recordings/input.saz",
sha256: "b".repeat(64),
bytes: 100,
};
const decoder = { id: "fixture", name: "Fixture", version: "1" };
const report = webNetworkCaptureSchema.parse({
artifact,
decoder,
format: "saz",
runtime_attribution: "unknown",
limitations: [],
container: {
reported: { members: [] },
numeric_literals: [],
redactions: [],
records_pointer: null,
},
total_records: 9,
records: [7, 2].map((ordinal) => ({
ordinal,
location: { kind: "archive-members", members: [`raw/${ordinal}_c.txt`] },
reported: {
session_id: String(ordinal),
time: null,
request: {
method: "POST",
url: "https://example.invalid/a",
body: body.toString(),
},
},
binary_fields: [
{
pointer: "/request/body",
representation: "producer-bytes",
state: "retained",
content_base64: body.toString("base64"),
bytes: body.length,
sha256: createHash("sha256").update(body).digest("hex"),
},
],
numeric_literals: [
{
pointer: "/time",
producer_type: "json-number",
literal: "9007199254740993",
},
],
redactions: [],
limitations: [],
})),
});
const evidence = createEvidence({ ...artifact, format: "file" }, decoder, {
operation: "inspect_web_network_capture",
parameters: { record_ordinals: [7, 2] },
result: report,
confidence: "observed",
authority: "historical-reference",
});
return {
report,
parent: {
evidenceId: evidence.evidence_id,
operation: evidence.operation,
normalizedResult: report,
subject: evidence.subject,
limitations: evidence.limitations,
},
};
};
it("keeps selected-record page coverage distinct from capture coverage and unsafe number absence", () => {
const { parent, report } = capture();
const summary = projectAnalysisView(parent, { kind: "summary" });
expect(summary.ok && summary.value).toMatchObject({
summary: { total_records: 9, retained_records: 2 },
coverage: { examined: 2, total: 2 },
});
const preview = projectAnalysisView(parent, {
kind: "capture",
detail: "preview",
offset: 0,
limit: 1,
});
expect(preview.ok && preview.value).toMatchObject({
items: [
{
ordinal: 7,
reported: { time: null },
numeric_literals: [{ pointer: "/time", literal: "9007199254740993" }],
},
],
coverage: { total: 2, examined: 1, next_offset: 1, exhausted: false },
});
expect(JSON.stringify(preview)).not.toContain("original body");
expect(JSON.stringify(preview)).not.toContain("content_base64");
const complete = projectAnalysisView(parent, {
kind: "capture",
detail: "complete",
offset: 1,
limit: 1,
});
expect(complete.ok && complete.value).toMatchObject({
items: [report.records[1]],
coverage: { total: 2, examined: 1, next_offset: null, exhausted: true },
});
const empty = projectAnalysisView(parent, {
kind: "capture",
detail: "preview",
offset: 50,
limit: 1,
});
expect(empty.ok && empty.value).toMatchObject({
items: [],
coverage: {
status: "empty",
total: 2,
examined: 0,
next_offset: null,
exhausted: true,
},
});
});
it("retains explicitly unknown digests and rejects a different subject path", () => {
const { parent, report } = capture();
const unknown = projectAnalysisView(
{
...parent,
subject: null,
normalizedResult: {
...report,
artifact: { ...report.artifact, sha256: null },
},
},
{ kind: "summary" },
);
expect(unknown.ok && unknown.value).toMatchObject({
artifact: { sha256: null },
});
expect(unknown.ok && unknown.value.unknowns.join(" ")).toContain(
"excluded artifact digest",
);
if (parent.subject === null) throw new Error("Expected fixture subject");
const mismatched = projectAnalysisView(
{
...parent,
subject: { ...parent.subject, local_path: "/different/source.saz" },
},
{ kind: "summary" },
);
expect(mismatched.ok).toBe(false);
});
it("rejects invalid ordinal coverage in a borrowed parent", () => {
const { parent, report } = capture();
const result = projectAnalysisView(
{
...parent,
normalizedResult: {
...report,
records: [report.records[0], report.records[0]],
},
},
{ kind: "summary" },
);
expect(result.ok).toBe(false);
});
@@ -0,0 +1,264 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import type { JsonValue } from "../jsonValue.js";
import { err, ok, type Result } from "../result.js";
import {
webNetworkCaptureRecordSchema,
webNetworkCaptureBinaryDescriptorSchema,
webNetworkCaptureSchema,
webNetworkCaptureArtifactSchema,
webNetworkCaptureDecoderSchema,
WEB_NETWORK_CAPTURE_FORMATS,
type WebNetworkCaptureRecord,
type WebNetworkCapture,
} from "../webNetworkCapture.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
import {
qlogSummarySchema,
summarizeQlogCapture,
projectQlogCapturePage,
} from "./qlogCaptureView.js";
/** Offsets page the parent's retained record order, preserving producer ordinals. */
export const captureViewRequestSchema = z.strictObject({
kind: z.literal("capture"),
detail: z.enum(["preview", "complete"]).default("preview"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
const previewSchema = webNetworkCaptureRecordSchema.extend({
binary_fields: z.array(webNetworkCaptureBinaryDescriptorSchema),
});
export const captureViewItemsSchema = z.array(
z.union([webNetworkCaptureRecordSchema, previewSchema]),
);
/** Count/identity overview; bodies and the archive member inventory stay in the parent. */
export const captureSummarySchema = z.strictObject({
artifact: webNetworkCaptureArtifactSchema,
decoder: webNetworkCaptureDecoderSchema,
format: z.enum(WEB_NETWORK_CAPTURE_FORMATS),
total_records: z.number().int().nonnegative(),
retained_records: z.number().int().nonnegative(),
runtime_attribution: z.literal("unknown"),
qlog: qlogSummarySchema.optional(),
});
const object = (
value: JsonValue,
): Readonly<Record<string, JsonValue>> | null =>
value !== null && typeof value === "object" && !Array.isArray(value)
? value
: null;
/** Select already parsed producer facts without interpreting HTTP or payload bytes again. */
const preview = (record: WebNetworkCaptureRecord) => {
const source = object(record.reported);
const reported: Record<string, JsonValue> = {};
const selectedPointers = new Set<string>();
if (source !== null) {
for (const key of ["session_id", "name", "time", "startedDateTime", "type"])
if (Object.hasOwn(source, key) && source[key] !== undefined) {
reported[key] = source[key];
selectedPointers.add(`/${key}`);
}
for (const key of ["request", "response"]) {
const value = source[key];
if (!Object.hasOwn(source, key) || value === undefined) continue;
const fields = object(value);
if (fields === null) {
// Preserve a reported null/scalar instead of inventing HTTP fields.
reported[key] = value;
continue;
}
const selected: Record<string, JsonValue> = {};
for (const field of [
"method",
"url",
"httpVersion",
"http_version",
"status",
"statusText",
"reason",
])
if (Object.hasOwn(fields, field) && fields[field] !== undefined) {
selected[field] = fields[field];
selectedPointers.add(`/${key}/${field}`);
}
reported[key] = selected;
}
}
return {
...record,
reported: source === null ? record.reported : reported,
binary_fields: record.binary_fields.map(
({ content_base64: _content, ...field }) => field,
),
numeric_literals:
source === null
? record.numeric_literals
: record.numeric_literals.filter(({ pointer }) =>
selectedPointers.has(pointer),
),
};
};
/** Authenticate the retained report and its subject at one owning boundary. */
const parseCaptureParent = (
parent: AnalysisViewParent,
): Result<WebNetworkCapture, AnalysisError> => {
const parsed = webNetworkCaptureSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
const report = parsed.data;
if (
report.artifact.sha256 !== null &&
(parent.subject == null ||
parent.subject.local_path !== report.artifact.path ||
parent.subject.digest.sha256 !== report.artifact.sha256)
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Capture parent subject must identify the report's exact path and SHA-256.",
},
]),
);
return ok(report);
};
/** Page immutable retained facts; no capture file, provider or network is consulted. */
export const projectWebNetworkCaptureView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (
view.kind !== "summary" &&
view.kind !== "capture" &&
view.kind !== "qlog"
)
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Historical captures support summary, capture record pages, qlog fact pages and admitted api-surface views.",
},
]),
);
const parsed = parseCaptureParent(parent);
if (!parsed.ok) return parsed;
const report = parsed.value;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_web_network_capture" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: [
...new Set([
...parent.limitations,
...report.limitations,
"Capture record pages cover the records selected into the parent Evidence, in that selected order; total_records counts the original decoded capture.",
]),
],
unknowns: [
"Historical records do not establish live runtime attribution or deployment authenticity.",
...(report.artifact.sha256 === null
? ["The explicitly excluded artifact digest remains unknown."]
: []),
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: {
artifact: report.artifact,
decoder: report.decoder,
format: report.format,
total_records: report.total_records,
retained_records: report.records.length,
runtime_attribution: report.runtime_attribution,
...(report.format === "qlog"
? { qlog: summarizeQlogCapture(report.qlog) }
: {}),
},
coverage: completeWithinViewCoverage(
report.records.length,
report.records.length,
),
});
if (view.kind === "qlog") {
if (report.format !== "qlog")
return err(
analysisViewInputError([
{
path: ["view", "kind"],
reason: "invalid_value",
message: "Qlog fact views require retained qlog Evidence.",
},
]),
);
const projected = projectQlogCapturePage(report.qlog, view);
return projected.ok
? ok({
kind: "qlog",
view,
...shared,
...projected.value,
limitations: [
...shared.limitations,
"Qlog fact pages retain all-recorded-events-before-selection scope. Exhausting a page does not establish network completeness, body recovery, retransmission or actual loss.",
],
})
: projected;
}
const records = report.records.slice(view.offset, view.offset + view.limit);
return ok({
kind: "capture",
view,
...shared,
items: captureViewItemsSchema.parse(
view.detail === "complete" ? records : records.map(preview),
),
coverage: pageViewCoverage(
view.offset,
records.length,
report.records.length,
),
limitations: [
...shared.limitations,
...(view.detail === "preview"
? [
"Preview selects recorded headline fields and byte descriptors; headers, XML, bodies, message data and other fields remain in complete record pages. Missing preview fields do not establish their absence from the producer record.",
]
: []),
],
});
};
+6
View File
@@ -45,6 +45,12 @@ export const androidInputSchemas = {
}),
} as const;
/** Optional retained delivery is separate from the engine's APK request. */
export const androidPackageInspectionInputSchema =
androidInputSchemas.inspect_android_package.extend({
detail: z.enum(["complete", "summary"]).optional(),
});
/** Supported static Android operations. */
export type AndroidOperation = keyof typeof androidInputSchemas;
/** Validated Android requests carry their selected operation. */
+76
View File
@@ -0,0 +1,76 @@
import { z } from "zod";
const decimal = z.string().regex(/^(0|[1-9][0-9]*)$/u);
const unsignedFact = z.discriminatedUnion("state", [
z.strictObject({ state: z.literal("reported"), value: decimal }),
z.strictObject({
state: z.literal("unknown"),
reason: z.literal("omitted-null-or-redacted"),
}),
]);
const traceLocation = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("json-pointer"), pointer: z.string() }),
z.strictObject({
kind: z.literal("unknown"),
reason: z.literal("explicit-sensitive-value"),
}),
]);
/** Exact, source-bound transport facts; coverage never establishes network completeness. */
export const qlogCaptureFactsSchema = z.strictObject({
profile: z.literal("aioquic-1.5.0-json-0.3"),
scope: z.literal("all-recorded-events-before-selection"),
body_bytes: z.literal("not-reported"),
clock: z.strictObject({
unit: z.literal("milliseconds"),
domain: z.literal("unix-epoch"),
basis: z.literal("selected-aioquic-profile-not-producer-authentication"),
}),
traces: z.array(
z.strictObject({
trace_index: z.number().int().nonnegative(),
location: traceLocation,
event_count: z.number().int().nonnegative(),
odcid: z.string().nullable(),
vantage_point: z.enum(["client", "server"]).nullable(),
incomplete_fact_records: z.array(z.number().int().nonnegative()),
loss_declarations: z.array(
z.strictObject({
record_ordinal: z.number().int().nonnegative(),
confidence: z.literal("observed"),
packet_number: unsignedFact,
packet_type: z.string().nullable(),
packet_number_space: z
.enum(["initial", "handshake", "application"])
.nullable(),
}),
),
streams: z.array(
z.strictObject({
stream_id: decimal,
direction: z.enum(["sent", "received"]),
confidence: z.literal("derived"),
scope: z.literal("observed-stream-frame-ranges"),
contributions: z.array(
z.strictObject({
record_ordinal: z.number().int().nonnegative(),
frame_index: z.number().int().nonnegative(),
offset: decimal,
length: decimal,
fin: z.boolean().nullable(),
}),
),
covered_ranges: z.array(
z.strictObject({ start: decimal, end: decimal }),
),
unique_bytes: decimal,
frame_length_sum: decimal,
repeated_bytes: decimal,
reported_final_sizes: z.array(decimal),
}),
),
}),
),
});
export type QlogCaptureFacts = z.output<typeof qlogCaptureFactsSchema>;
+121 -73
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { localPathStringSchema } from "./localPath.js";
import { qlogCaptureFactsSchema } from "./qlogCapture.js";
/** Complete historical evidence budgets; exceeding a budget returns no partial capture. */
export const WEB_NETWORK_CAPTURE_LIMITS = {
@@ -10,12 +11,19 @@ export const WEB_NETWORK_CAPTURE_LIMITS = {
depth: 64,
} as const;
export const WEB_NETWORK_CAPTURE_FORMATS = [
"har",
"mitmproxy",
"saz",
"qlog",
] as const;
/** Inspect an explicit retained capture without contacting its recorded destinations. */
export const inspectWebNetworkCaptureInputSchema = z.strictObject({
capture_path: localPathStringSchema.describe(
"Absolute local HAR or mitmproxy capture path.",
"Absolute local HAR, mitmproxy, Fiddler SAZ or aioquic qlog capture path.",
),
format: z.enum(["har", "mitmproxy"]),
format: z.enum(WEB_NETWORK_CAPTURE_FORMATS),
record_ordinals: z
.array(z.number().int().nonnegative())
.min(1)
@@ -31,6 +39,21 @@ export const inspectWebNetworkCaptureInputSchema = z.strictObject({
),
});
/** Read declarations through their owning schema for service and adapter failures. */
export const captureSensitiveValues = (
rawInput: unknown,
): readonly string[] => {
const parsed =
inspectWebNetworkCaptureInputSchema.shape.sensitive_values.safeParse(
typeof rawInput === "object" &&
rawInput !== null &&
"sensitive_values" in rawInput
? rawInput.sensitive_values
: undefined,
);
return parsed.success ? parsed.data : [];
};
const pointerSchema = z
.string()
.describe("RFC 6901 pointer in the producer's reported object.");
@@ -53,21 +76,26 @@ const binaryBase = {
pointer: pointerSchema,
representation: z.enum(["producer-bytes", "har-base64-content"]),
};
const retainedBinaryDescriptorSchema = z.strictObject({
...binaryBase,
state: z.literal("retained"),
bytes: z.number().int().nonnegative(),
sha256: z.string().regex(/^[0-9a-f]{64}$/),
});
const redactedBinaryDescriptorSchema = z.strictObject({
...binaryBase,
state: z.literal("redacted"),
bytes: z.null(),
sha256: z.null(),
});
/** Exact byte facts shared by complete records and previews that omit content. */
export const webNetworkCaptureBinaryDescriptorSchema = z.discriminatedUnion(
"state",
[retainedBinaryDescriptorSchema, redactedBinaryDescriptorSchema],
);
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(),
}),
retainedBinaryDescriptorSchema.extend({ content_base64: z.string() }),
redactedBinaryDescriptorSchema.extend({ content_base64: z.null() }),
]);
const numberSchema = z.strictObject({
pointer: pointerSchema,
@@ -84,6 +112,10 @@ export const webNetworkCaptureRecordSchema = z.strictObject({
reason: z.literal("explicit-sensitive-value"),
}),
z.strictObject({ kind: z.literal("json-pointer"), pointer: pointerSchema }),
z.strictObject({
kind: z.literal("archive-members"),
members: z.array(z.string()).min(1),
}),
z.strictObject({
kind: z.literal("byte-range"),
offset: z.number().int().nonnegative(),
@@ -97,69 +129,85 @@ export const webNetworkCaptureRecordSchema = z.strictObject({
limitations: z.array(z.string()),
});
/** Decoded records retain unique producer ordinals within their declared coverage. */
export const webNetworkCapturePayloadSchema = z
.strictObject({
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),
})
.superRefine((capture, context) => {
if (capture.records.length > capture.total_records) {
/** The selected offline parser profile, independent of authenticated producer identity. */
export const webNetworkCaptureDecoderSchema = z.strictObject({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().min(1),
});
/** Source coverage is shared by every offline decoder. */
const payloadShape = {
decoder: webNetworkCaptureDecoderSchema,
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),
};
const refineCoverage = (
capture: { total_records: number; records: { ordinal: number }[] },
context: z.RefinementCtx,
): void => {
const seen = new Set<number>();
for (const [index, record] of capture.records.entries()) {
if (record.ordinal >= capture.total_records || seen.has(record.ordinal)) {
context.addIssue({
code: "custom",
path: ["records"],
message: "Retained record count exceeds the declared capture total.",
path: ["records", index, "ordinal"],
message:
"Retained ordinals must be unique and within the declared capture total.",
});
return;
}
const seen = new Set<number>();
for (const [index, record] of capture.records.entries()) {
if (record.ordinal >= capture.total_records || seen.has(record.ordinal)) {
context.addIssue({
code: "custom",
path: ["records", index, "ordinal"],
message:
"Retained ordinals must be unique and within the declared capture total.",
});
return;
}
seen.add(record.ordinal);
}
});
/** Historical capture inspection has file identity, producer provenance and explicit unknowns. */
export const webNetworkCaptureSchema =
webNetworkCapturePayloadSchema.safeExtend({
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(),
seen.add(record.ordinal);
}
};
/** Strict alternatives prevent undefined-valued facets from entering JSON Evidence. */
export const webNetworkCapturePayloadSchema = z
.union([
z.strictObject({ ...payloadShape, qlog: qlogCaptureFactsSchema }),
z.strictObject(payloadShape),
])
.superRefine(refineCoverage);
/** Caller-selected file identity; explicit exclusions remain unknown. */
export const webNetworkCaptureArtifactSchema = 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 SHA-256; null only when explicitly excluded."),
bytes: z.number().int().nonnegative(),
});
const artifactShape = {
artifact: webNetworkCaptureArtifactSchema,
runtime_attribution: z.literal("unknown"),
limitations: z.array(z.string()),
};
/** Qlog transport facts occur exactly on the qlog alternative. */
export const webNetworkCaptureSchema = z
.discriminatedUnion("format", [
z.strictObject({
...payloadShape,
...artifactShape,
format: z.enum(["har", "mitmproxy", "saz"]),
}),
format: z.enum(["har", "mitmproxy"]),
runtime_attribution: z.literal("unknown"),
limitations: z.array(z.string()),
});
z.strictObject({
...payloadShape,
...artifactShape,
format: z.literal("qlog"),
qlog: qlogCaptureFactsSchema,
}),
])
.superRefine(refineCoverage);
export type InspectWebNetworkCaptureInput = z.output<
typeof inspectWebNetworkCaptureInputSchema
@@ -22,6 +22,8 @@ export const excludeCaptureCoordinates = (
const location =
(record.location.kind === "json-pointer" &&
sensitive(record.location.pointer)) ||
(record.location.kind === "archive-members" &&
record.location.members.some(sensitive)) ||
(record.location.kind === "byte-range" &&
(sensitive(String(record.location.offset)) ||
sensitive(String(record.location.bytes))))
@@ -51,8 +53,30 @@ export const excludeCaptureCoordinates = (
numeric_literals: sidecars(value.container.numeric_literals),
redactions: sidecars(value.container.redactions),
};
const qlog =
value.format === "qlog"
? {
...value.qlog,
traces: value.qlog.traces.map((trace) => {
if (
trace.location.kind !== "json-pointer" ||
!sensitive(trace.location.pointer)
)
return trace;
excluded = true;
return {
...trace,
location: {
kind: "unknown" as const,
reason: "explicit-sensitive-value" as const,
},
};
}),
}
: undefined;
return {
...value,
...(qlog === undefined ? {} : { qlog }),
container,
records,
limitations: excluded