Files
rea/src/domain/evidence.ts
T
40e18b2e37 fix(domain): preserve prototype-named JSON members through Evidence boundaries (#1049)
* fix(domain): preserve prototype-named JSON members through Evidence boundaries

Zod's z.json() record projection drops own __proto__ members as a
prototype-pollution guard, so provider replies carrying them lost evidence
before hashing/serialization and CLI/MCP output. The shared schema now
validates with z.json() as before, then rebuilds the value keeping
prototype-named own members as ordinary data properties (__proto__ via
Object.defineProperty, so the prototype is never mutated).

parseHarJson no longer rejects __proto__ members; the explicit unsupported
case from #992 is replaced with a preservation regression, and the
inspect_web_network_capture contract text is updated to match.

Fixes #1036

* fix(domain): bound JSON depth and oversized payloads at parsing boundaries

jsonValueSchema re-walked hostile input through z.json()'s recursive core, so a deeply nested payload from an MCP tool argument, inline evidence, provider result, or keyed archive threw RangeError: Maximum call stack size exceeded instead of a validation issue. The schema now runs an iterative depth guard first and keeps z.json() for full JSON semantics behind it, which also turns cyclic values into validation errors. The 1000-edge limit stays far below the range where the recursive core overflows its stack (measured between 2000 and 3000 on Node 24) while leaving room for legitimately deep target-derived trees such as compiled NIB view hierarchies, and the guard narrows with a typed record check instead of any or unchecked casts. The non-recursive JSON Schema advertisement stays intact on both the public and standard projection paths. Two payload sizes get explicit budgets tied to their producer constraints: web text artifacts reject beyond the 16 MiB source budget the web tooling already advertises, and native UI screenshot base64 beyond the 64 MiB helper output budget. Regenerated product catalog, skill catalog digest, and completion-ledger manifest follow the schema-boundary change.

* fix(validation): preserve depth diagnostics across process inputs

---------

Co-authored-by: DeryFerd <deryferdikao125@gmail.com>
Co-authored-by: N0zoM1z0 <1705004398@qq.com>
2026-10-08 21:32:48 +08:00

301 lines
9.6 KiB
TypeScript

import { z } from "zod";
import { digestCanonicalValue } from "./canonicalDigest.js";
import {
analysisProfileSchema,
type AnalysisProfileCommitment,
} from "./analysisProfile.js";
import type { BinaryTarget } from "./binaryTarget.js";
import {
jsonObjectSchema,
jsonValueSchema,
type JsonValue,
} from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
/** Provider identity schema shared by evidence-bearing persistence formats. */
export const providerSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.object({
name: z.string().min(1),
digest: z.object({ sha256: digestSchema }),
format: z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"zip",
"ipa",
"apk",
"msix",
"appx",
"asar",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
local_path: z.string(),
});
/** Source location attached to an evidence observation. */
/** Source-location schema shared by evidence-bearing persistence formats. */
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("address"), address: z.string().min(1) }),
z.object({
kind: z.literal("address-range"),
start: z.string().min(1),
end: z.string().min(1),
}),
z.object({ kind: z.literal("artifact-path"), path: z.string().min(1) }),
z.object({ kind: z.literal("file-offset"), offset: z.number().int().min(0) }),
z.object({
kind: z.literal("file-offset-range"),
start: z.number().int().min(0),
end: z.number().int().min(0),
}),
]);
const evidenceAuthoritySchema = z.enum([
"shipped-artifact",
"controlled-replay",
"historical-reference",
"external-service",
"analyst-inference",
]);
const executionEnvironmentSchema = z.object({
id: z.string().min(1),
platform: z.string().min(1),
architecture: z.string().min(1),
isolation: z.enum(["none", "process", "container", "virtual-machine"]),
});
const evidenceBaseSchema = z
.object({
evidence_id: prefixedDigestSchema("ev"),
subject: subjectSchema.nullable(),
provider: providerSchema,
predicate_type: z.string().min(1),
operation: z.string().min(1),
parameters: jsonObjectSchema,
raw_result: jsonValueSchema.nullable(),
normalized_result: jsonValueSchema,
confidence: z.enum(["observed", "derived", "inferred"]),
authority: evidenceAuthoritySchema,
environment: executionEnvironmentSchema.nullable(),
limitations: z.array(z.string()),
locations: z.array(evidenceLocationSchema),
evidence_links: z.array(prefixedDigestSchema("ev")),
})
.strict();
/** Object envelope used to specialize caller-visible Evidence result schemas. */
export const evidenceEnvelopeSchema = evidenceBaseSchema.extend({
analysis_profile: analysisProfileSchema.optional(),
});
const validateAnalysisProfileProvider = (
evidence: z.infer<typeof evidenceEnvelopeSchema>,
context: z.RefinementCtx,
): void => {
const profile = evidence.analysis_profile;
if (
profile !== undefined &&
(profile.provider.id !== evidence.provider.id ||
profile.provider.name !== evidence.provider.name ||
profile.provider.version !== evidence.provider.version)
)
context.addIssue({
code: "custom",
path: ["analysis_profile", "provider"],
message: "Analysis profile provider does not match Evidence provider",
});
};
/** Strict, provider-neutral record for one successful public observation. */
export const evidenceSchema = evidenceEnvelopeSchema.superRefine(
validateAnalysisProfileProvider,
);
const profiledEvidenceSchema = evidenceBaseSchema
.extend({ analysis_profile: analysisProfileSchema })
.superRefine(validateAnalysisProfileProvider);
/** JSON-exact union used where Evidence participates in larger schemas. */
export const evidenceRecordSchema = z.union([
profiledEvidenceSchema,
evidenceBaseSchema,
]);
export type Evidence = z.infer<typeof evidenceRecordSchema>;
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
/** Minimal immutable local artifact identity accepted by Evidence. */
export interface EvidenceSubjectTarget {
readonly path: string;
readonly sha256: string;
readonly format: z.infer<typeof subjectSchema>["format"];
readonly architecture?: "x86" | "x86_64" | "arm" | "arm64";
}
type EvidenceAuthority = z.infer<typeof evidenceAuthoritySchema>;
type ExecutionEnvironment = z.infer<typeof executionEnvironmentSchema>;
export interface EvidenceProvider {
readonly id: string;
readonly name: string;
readonly version: string | null;
}
export interface EvidenceObservation {
readonly predicateType?: string;
readonly operation: string;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly result: JsonValue;
readonly analysisProfile?: AnalysisProfileCommitment;
readonly rawResult?: JsonValue;
readonly confidence?: "observed" | "derived" | "inferred";
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[];
}
type WithoutEvidenceId<Record_> = Record_ extends unknown
? Omit<Record_, "evidence_id">
: never;
type EvidenceWithoutId = WithoutEvidenceId<Evidence>;
const semanticProjection = (evidence: EvidenceWithoutId): JsonValue => ({
subject:
evidence.subject === null
? null
: {
digest: evidence.subject.digest,
format: evidence.subject.format,
architecture: evidence.subject.architecture,
},
provider: evidence.provider,
...(!("analysis_profile" in evidence)
? {}
: { analysis_profile: evidence.analysis_profile }),
predicate_type: evidence.predicate_type,
operation: evidence.operation,
parameters: evidence.parameters,
raw_result: evidence.raw_result,
normalized_result: evidence.normalized_result,
confidence: evidence.confidence,
authority: evidence.authority,
environment: evidence.environment,
limitations: evidence.limitations,
locations: evidence.locations,
evidence_links: evidence.evidence_links,
});
/** Recompute the semantic identifier, excluding paths and raw payload bytes. */
const computeEvidenceId = (evidence: EvidenceWithoutId): string =>
`ev_${digestCanonicalValue(semanticProjection(evidence), "Evidence")}`;
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
export const parseEvidence = (input: unknown): Evidence => {
const evidence = evidenceRecordSchema.parse(input);
const { evidence_id: evidenceId, ...withoutId } = evidence;
if (computeEvidenceId(withoutId) !== evidenceId)
throw new TypeError(
"Evidence semantic identifier does not match its record",
);
return evidence;
};
/** Build deterministic Evidence from an immutable artifact subject. */
export const createEvidence = (
target: EvidenceSubjectTarget | BinaryTarget | undefined,
provider: EvidenceProvider,
observation: EvidenceObservation,
): Evidence => {
const subject =
target === undefined
? null
: {
name: target.path.split("/").at(-1) || "artifact",
digest: { sha256: target.sha256 },
format: target.format,
architecture: target.architecture ?? null,
local_path: target.path,
};
const semantic = {
subject:
subject === null
? null
: {
digest: subject.digest,
format: subject.format,
architecture: subject.architecture,
},
provider: {
id: provider.id,
name: provider.name,
version: provider.version,
},
...(observation.analysisProfile === undefined
? {}
: { analysis_profile: observation.analysisProfile }),
predicate_type: observation.predicateType ?? "rea.analysis",
operation: observation.operation,
parameters: observation.parameters,
raw_result: observation.rawResult ?? null,
normalized_result: observation.result,
confidence: observation.confidence ?? "observed",
authority: observation.authority ?? "shipped-artifact",
environment: observation.environment ?? null,
limitations: [
...(target === undefined
? [
observation.subjectUnavailableReason ??
"Artifact identity is unavailable for this observation.",
]
: []),
...(observation.limitations ?? []),
],
locations: [...(observation.locations ?? [])],
evidence_links: [...(observation.evidenceLinks ?? [])],
} satisfies JsonValue;
// Select the known envelope before parsing. A union otherwise traverses and
// clones a legacy result for the profiled branch before rejecting its absent
// profile and trying the legacy branch.
const schema =
observation.analysisProfile === undefined
? evidenceBaseSchema
: profiledEvidenceSchema;
const normalized = schema.parse({
...semantic,
evidence_id: `ev_${"0".repeat(64)}`,
subject,
});
// The envelope has already been parsed into an independent snapshot. Only
// its derived identifier changes here; parsing again clones the full payload
// and recomputes the same digest while the previous snapshot is still live.
return {
...normalized,
evidence_id: computeEvidenceId(normalized),
};
};