fix(apple): distinguish cache loadability and propagate search uncertainty
This commit is contained in:
@@ -162,8 +162,7 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
|
||||
: `Evidence ${error.evidenceId} does not match the requested reference (${error.reason}). Check the expected and actual identity in the diagnostic details.`;
|
||||
if (error instanceof EvidenceIntegrityError)
|
||||
return "Evidence is invalid or has changed. Recreate or re-import it, then try again.";
|
||||
if (error instanceof EvidenceFileError)
|
||||
return evidenceFileMessage(error.reason);
|
||||
if (error instanceof EvidenceFileError) return evidenceFileMessage(error);
|
||||
if (error instanceof UnknownRegistryError && error.reason === "not-found")
|
||||
return "The requested residual unknown does not exist in this session. Check the unknown_id and try again.";
|
||||
if (error instanceof UnknownRegistryError)
|
||||
@@ -258,7 +257,14 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
|
||||
return "Artifact could not be read or written. Check file access and try again.";
|
||||
};
|
||||
|
||||
const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
|
||||
const evidenceFileMessage = ({
|
||||
operation,
|
||||
reason,
|
||||
}: EvidenceFileError): string => {
|
||||
if (reason === "missing")
|
||||
return operation === "read"
|
||||
? "Evidence file does not exist at the selected path. Check the path and try again."
|
||||
: "Evidence output directory does not exist. Choose an existing directory and try again.";
|
||||
if (reason === "not-file")
|
||||
return "Evidence path does not point to a regular file. Choose a file and try again.";
|
||||
if (reason === "exists")
|
||||
|
||||
@@ -259,7 +259,11 @@ const artifactStateErrorDetails = (
|
||||
};
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof EvidenceFileError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
return {
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...(error.path === undefined ? {} : { path: error.path }),
|
||||
};
|
||||
return undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ describe("dyld path expansion", () => {
|
||||
}),
|
||||
[plugin]: parsed(
|
||||
slice({
|
||||
file_type: "bundle",
|
||||
file_type: "dylib",
|
||||
dependencies: [dependency("@rpath/libshared.dylib")],
|
||||
}),
|
||||
),
|
||||
@@ -302,10 +302,13 @@ describe("dyld resolution outcomes", () => {
|
||||
trace.findings.map(({ kind, edge_index: index }) => [kind, index]),
|
||||
).toEqual([
|
||||
["earlier-rpath-candidate-absent", 0],
|
||||
["weak-load-unresolved", 1],
|
||||
["required-load-unresolved", 2],
|
||||
["dyld-environment-present", null],
|
||||
]);
|
||||
expect(trace.edges.map(({ resolution }) => resolution.status)).toEqual([
|
||||
"conditional",
|
||||
"undetermined",
|
||||
"undetermined",
|
||||
]);
|
||||
expect(trace.findings[0]?.explanation).toContain(
|
||||
"Contents/MacOS/../Overrides/libfound.dylib",
|
||||
);
|
||||
@@ -540,7 +543,7 @@ const cache = (
|
||||
].includes(path)
|
||||
? "mapped"
|
||||
: "absent",
|
||||
image: () => Promise.resolve(parsed(slice())),
|
||||
image: () => Promise.resolve(parsed(slice({ architecture: "arm64e" }))),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
@@ -830,3 +833,96 @@ describe("conditional loads", () => {
|
||||
).toContain(`${VENDOR} loads only conditionally; if it loads,`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dependency loadability", () => {
|
||||
it.each(["execute", "bundle", "other"] as const)(
|
||||
"does not load cached or in-root %s images as dependencies",
|
||||
async (fileType) => {
|
||||
for (const useCache of [true, false]) {
|
||||
const path = useCache
|
||||
? "/usr/lib/libSystem.B.dylib"
|
||||
: "@executable_path/libinvalid.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({ dependencies: [dependency(path)] }),
|
||||
"Contents/MacOS/libinvalid.dylib": parsed(
|
||||
slice({ file_type: fileType }),
|
||||
),
|
||||
}),
|
||||
{
|
||||
roots: [MAIN],
|
||||
...(useCache
|
||||
? {
|
||||
sharedCache: cache({
|
||||
image: async () =>
|
||||
parsed(
|
||||
slice({ architecture: "arm64e", file_type: fileType }),
|
||||
),
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
expect(trace.edges[0]?.resolution).toEqual({
|
||||
status: "undetermined",
|
||||
image: null,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each([{ platforms: [] }, { platforms: [{ id: 2, name: "ios" }] }])(
|
||||
"keeps cached unknown or incompatible platforms uncertain (%j)",
|
||||
async ({ platforms }) => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
}),
|
||||
{
|
||||
roots: [MAIN],
|
||||
sharedCache: cache({
|
||||
image: async () =>
|
||||
parsed(slice({ architecture: "arm64e", platforms })),
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(trace.edges[0]?.resolution.status).toBe("undetermined");
|
||||
expect(trace.coverage.status).toBe("partial");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("propagates embedded search-path uncertainty through found, missing, lazy and descendant edges", async () => {
|
||||
const child = "Contents/MacOS/child.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dyld_environment: ["DYLD_LIBRARY_PATH=/tmp"],
|
||||
dependencies: [
|
||||
dependency("@executable_path/child.dylib"),
|
||||
dependency("@executable_path/missing.dylib"),
|
||||
dependency("@executable_path/lazy.dylib", {
|
||||
command: "LC_LAZY_LOAD_DYLIB",
|
||||
}),
|
||||
dependency("/usr/lib/libSystem.B.dylib"),
|
||||
],
|
||||
}),
|
||||
[child]: parsed(
|
||||
slice({ dependencies: [dependency("@loader_path/gone.dylib")] }),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN], sharedCache: cache() },
|
||||
);
|
||||
expect(trace.edges.map(({ resolution }) => resolution.status)).toEqual([
|
||||
"conditional",
|
||||
"undetermined",
|
||||
"undetermined",
|
||||
"conditional",
|
||||
"undetermined",
|
||||
]);
|
||||
expect(trace.edges.at(-1)?.loader_conditional).toBe(true);
|
||||
expect(trace.findings.map(({ kind }) => kind)).toEqual([
|
||||
"dyld-environment-present",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
compatibleSlice,
|
||||
cacheServes,
|
||||
directoryOf,
|
||||
expandPrefix,
|
||||
joinPath,
|
||||
@@ -55,13 +56,15 @@ interface ProcessContext {
|
||||
readonly view: DylibTreeView;
|
||||
readonly root: string;
|
||||
readonly architecture: string;
|
||||
readonly platforms: MachoSlice["platforms"];
|
||||
readonly searchPathsUnknown: boolean;
|
||||
readonly executable: string | null;
|
||||
readonly loaded: Map<string, LoadedImage>;
|
||||
readonly byInstallName: Map<string, string>;
|
||||
readonly images: Map<string, MachoImageFacts>;
|
||||
/** The supplied cache, when it serves this process's architecture and platform. */
|
||||
readonly sharedCache: DylibSharedCacheView | undefined;
|
||||
/** Cached install paths whose subcache bytes were unavailable, across processes. */
|
||||
/** Cached install paths whose bytes or loadability could not be verified. */
|
||||
readonly unverifiedCacheImages: Set<string>;
|
||||
}
|
||||
|
||||
@@ -135,7 +138,14 @@ const evaluateCandidate = async (
|
||||
const facts = await sharedCache.image(template.expansion.path);
|
||||
if (
|
||||
facts?.status === "parsed" &&
|
||||
compatibleSlice(facts.slices, context.architecture) !== undefined
|
||||
facts.slices.some(
|
||||
(slice) =>
|
||||
cacheServes(slice.architecture, context.architecture) &&
|
||||
slice.file_type === "dylib" &&
|
||||
slice.platforms.some(({ id }) =>
|
||||
context.platforms.some((platform) => platform.id === id),
|
||||
),
|
||||
)
|
||||
)
|
||||
return {
|
||||
...base,
|
||||
@@ -160,13 +170,24 @@ const evaluateCandidate = async (
|
||||
if (lookup.kind !== "file")
|
||||
return { ...base, outcome: "absent", resolved_path: null };
|
||||
const facts = await imageFacts(context, lookup.path);
|
||||
const outcome: Candidate["outcome"] =
|
||||
facts.status !== "parsed"
|
||||
? facts.status
|
||||
: compatibleSlice(facts.slices, context.architecture) === undefined
|
||||
? "architecture-missing"
|
||||
: "resolved";
|
||||
return { ...base, outcome, resolved_path: lookup.path };
|
||||
if (facts.status !== "parsed")
|
||||
return { ...base, outcome: facts.status, resolved_path: lookup.path };
|
||||
const slice = compatibleSlice(facts.slices, context.architecture);
|
||||
if (slice === undefined)
|
||||
return {
|
||||
...base,
|
||||
outcome: "architecture-missing",
|
||||
resolved_path: lookup.path,
|
||||
};
|
||||
if (slice.file_type !== "dylib")
|
||||
return { ...base, outcome: "unsupported", resolved_path: lookup.path };
|
||||
if (
|
||||
!slice.platforms.some(({ id }) =>
|
||||
context.platforms.some((platform) => platform.id === id),
|
||||
)
|
||||
)
|
||||
return { ...base, outcome: "undetermined", resolved_path: lookup.path };
|
||||
return { ...base, outcome: "resolved", resolved_path: lookup.path };
|
||||
};
|
||||
|
||||
const imageFacts = async (
|
||||
@@ -234,7 +255,13 @@ const resolveDependency = async (
|
||||
)
|
||||
break;
|
||||
}
|
||||
const searched = resolution(candidates);
|
||||
const modeled = resolution(candidates);
|
||||
const searched: Edge["resolution"] = context.searchPathsUnknown
|
||||
? {
|
||||
...modeled,
|
||||
status: modeled.image === null ? "undetermined" : "conditional",
|
||||
}
|
||||
: modeled;
|
||||
// Reusing an image that itself loads only conditionally is conditional too.
|
||||
const resolved: Edge["resolution"] =
|
||||
loaded !== undefined &&
|
||||
@@ -368,6 +395,8 @@ export const traceDylibLoading = async (
|
||||
view,
|
||||
root,
|
||||
architecture: slice.architecture,
|
||||
platforms: slice.platforms,
|
||||
searchPathsUnknown: slice.dyld_environment.length > 0,
|
||||
executable: slice.file_type === "execute" ? root : null,
|
||||
loaded: new Map(),
|
||||
byInstallName: new Map(),
|
||||
|
||||
@@ -82,7 +82,7 @@ export interface DylibSharedCacheView {
|
||||
/**
|
||||
* `mapped`: listed and inside an admitted mapping. That is address coverage,
|
||||
* not a load: a shared-cache hit also requires `image` to parse a slice this
|
||||
* process can load. `unverified`: listed, but the subcache holding it is
|
||||
* process can load as a dylib on its platform. `unverified`: listed, but the subcache holding it is
|
||||
* unavailable. `absent`: not listed.
|
||||
*/
|
||||
lookup(path: string): "mapped" | "unverified" | "absent";
|
||||
@@ -191,7 +191,7 @@ export const dylibResolutionResultSchema = z.strictObject({
|
||||
status: z.enum(["complete", "partial"]),
|
||||
unparsed_images: z.array(z.string()),
|
||||
roots_without_architecture: z.array(z.string()),
|
||||
/** Install paths the supplied cache lists in subcaches that were unavailable. */
|
||||
/** Listed cache paths whose bytes or process-compatible dylib representation could not be verified. */
|
||||
unverified_shared_cache_images: z.array(z.string()),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
|
||||
|
||||
/** Select one archive within the active bundle and optionally one named root. */
|
||||
@@ -85,7 +86,14 @@ export const projectKeyedArchive = (
|
||||
if (top === undefined || Object.keys(top).length === 0)
|
||||
throw new TypeError("Keyed archive has no $top roots");
|
||||
if (selection.root !== undefined && !Object.hasOwn(top, selection.root))
|
||||
throw new TypeError(`Archive root does not exist: ${selection.root}`);
|
||||
throw new AnalysisInputError("inspect_keyed_archive", undefined, [
|
||||
{
|
||||
path: ["root"],
|
||||
reason: "invalid_value",
|
||||
message: `Archive root does not exist: ${selection.root}. Select one of the archive's $top roots or omit root.`,
|
||||
expected: Object.keys(top),
|
||||
},
|
||||
]);
|
||||
const roots =
|
||||
selection.root === undefined
|
||||
? top
|
||||
|
||||
@@ -44,13 +44,27 @@ it("snapshots caller-owned payloads before deriving their identity", () => {
|
||||
});
|
||||
|
||||
describe("analysis evidence identity", () => {
|
||||
it("normalizes prototype-named parameter keys", () => {
|
||||
it("preserves prototype-named parameter keys and their semantic identity", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: Object.fromEntries([["__proto__", false]]),
|
||||
result: true,
|
||||
});
|
||||
expect(evidence.parameters).toEqual({ ["__proto__"]: false });
|
||||
expect(Object.hasOwn(evidence.parameters, "__proto__")).toBe(true);
|
||||
expect(parseEvidence(evidence)).toEqual(evidence);
|
||||
const stripped = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(stripped.evidence_id).not.toBe(evidence.evidence_id);
|
||||
expect(() =>
|
||||
parseEvidence({
|
||||
...evidence,
|
||||
parameters: { ["__proto__"]: true },
|
||||
}),
|
||||
).toThrow(/semantic identifier/u);
|
||||
});
|
||||
|
||||
it.prop([
|
||||
@@ -280,3 +294,27 @@ describe("evidence parameter depth bound", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves prototype-named raw and normalized results with aligned identity", () => {
|
||||
const result = { ["__proto__"]: { preserved: 7 }, constructor: "ordinary" };
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result,
|
||||
rawResult: result,
|
||||
});
|
||||
const parsed = parseEvidence(evidence);
|
||||
expect(parsed.normalized_result).toEqual(result);
|
||||
expect(parsed.raw_result).toEqual(result);
|
||||
expect(Object.getPrototypeOf(parsed.normalized_result)).toBe(
|
||||
Object.prototype,
|
||||
);
|
||||
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
|
||||
const stripped = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: { constructor: "ordinary" },
|
||||
rawResult: { constructor: "ordinary" },
|
||||
});
|
||||
expect(stripped.evidence_id).not.toBe(evidence.evidence_id);
|
||||
});
|
||||
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
type AnalysisProfileCommitment,
|
||||
} from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "./jsonValue.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
|
||||
@@ -89,7 +93,7 @@ const evidenceBaseSchema = z
|
||||
provider: providerSchema,
|
||||
predicate_type: z.string().min(1),
|
||||
operation: z.string().min(1),
|
||||
parameters: z.record(z.string(), jsonValueSchema),
|
||||
parameters: jsonObjectSchema,
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
normalized_result: jsonValueSchema,
|
||||
confidence: z.enum(["observed", "derived", "inferred"]),
|
||||
|
||||
@@ -182,6 +182,34 @@ const referencedEvidenceIds = (unknown: ResidualUnknown): readonly string[] => [
|
||||
...(unknown.resolution?.evidence_ids ?? []),
|
||||
];
|
||||
|
||||
/**
|
||||
* Name the bundle constraint that failed and how to recover. A single
|
||||
* Evidence record, such as one command result, is not a bundle.
|
||||
*/
|
||||
export const describeEvidenceBundleFailure = (
|
||||
input: unknown,
|
||||
cause: unknown,
|
||||
): string => {
|
||||
const record = evidenceRecordSchema.safeParse(input);
|
||||
if (record.success)
|
||||
return `Expected an Evidence bundle with records and manifest arrays, but this JSON is one Evidence record (${record.data.evidence_id}). Export a session bundle with the MCP export_evidence_bundle tool and supply that file.`;
|
||||
return cause instanceof z.ZodError
|
||||
? `Evidence bundle does not match the bundle schema ${describeValidationFailure(cause)}. Supply an unmodified bundle written by export_evidence_bundle or rea evidence-export.`
|
||||
: `Evidence bundle validation failed: ${describeValidationFailure(cause)}. Recreate or re-export the bundle, then try again.`;
|
||||
};
|
||||
|
||||
/** Locate the first schema issue, or keep a thrown constraint message. */
|
||||
export const describeValidationFailure = (cause: unknown): string => {
|
||||
if (!(cause instanceof z.ZodError))
|
||||
return cause instanceof Error ? cause.message : String(cause);
|
||||
const [first, ...rest] = cause.issues;
|
||||
const location =
|
||||
first === undefined || first.path.length === 0
|
||||
? "the document root"
|
||||
: first.path.map(String).join(".");
|
||||
return `at ${location}: ${first?.message ?? "invalid value"}${rest.length === 0 ? "" : ` (${String(rest.length)} more issues)`}`;
|
||||
};
|
||||
|
||||
/** Parse records, verify semantic IDs, and reject inconsistent manifests. */
|
||||
export const parseEvidenceBundle = (input: unknown): EvidenceBundle => {
|
||||
const parsed = evidenceBundleSchema.parse(input);
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { AnalysisError } from "./analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
type AnalysisErrorOptions,
|
||||
} from "./analysisErrorBase.js";
|
||||
|
||||
/** Evidence identity, schema, or bundle manifests failed integrity checks. */
|
||||
export class EvidenceIntegrityError extends AnalysisError {
|
||||
readonly _tag = "EvidenceIntegrityError";
|
||||
override readonly userMessage: string | undefined;
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
options?: AnalysisErrorOptions & { readonly userMessage?: string },
|
||||
) {
|
||||
super(message, options);
|
||||
this.userMessage = options?.userMessage;
|
||||
}
|
||||
}
|
||||
|
||||
/** A session Evidence reference is missing or has the wrong semantic identity. */
|
||||
@@ -25,11 +37,15 @@ export class EvidenceReferenceError extends EvidenceIntegrityError {
|
||||
export class EvidenceFileError extends AnalysisError {
|
||||
readonly _tag = "EvidenceFileError";
|
||||
|
||||
/** Caller-selected path that failed, resolved against the working directory. */
|
||||
readonly path: string | undefined;
|
||||
|
||||
constructor(
|
||||
readonly operation: "read" | "write",
|
||||
readonly reason: "not-file" | "exists" | "invalid-json" | "io",
|
||||
options?: ErrorOptions,
|
||||
readonly reason: "not-file" | "exists" | "invalid-json" | "missing" | "io",
|
||||
options?: ErrorOptions & { readonly path?: string },
|
||||
) {
|
||||
super(`Evidence bundle ${operation} failed: ${reason}`, options);
|
||||
this.path = options?.path;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,16 +12,21 @@ import { digestSchema } from "../digests.js";
|
||||
import { prefixedDigestSchema } from "../digests.js";
|
||||
|
||||
const semanticNodeIdSchema = prefixedDigestSchema("jsrg_node");
|
||||
const literalValueSchema = jsonValueSchema.refine(
|
||||
(value) =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean",
|
||||
"Literal seeds accept only JSON primitive values",
|
||||
);
|
||||
// Zod derivations drop the shared schema's JSON Schema projection override;
|
||||
// re-apply it so MCP catalog generation keeps projecting `{}`.
|
||||
literalValueSchema._zod.toJSONSchema = () => ({});
|
||||
|
||||
const literalSeedSchema = z.strictObject({
|
||||
kind: z.literal("literal"),
|
||||
value: jsonValueSchema.refine(
|
||||
(value) =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean",
|
||||
"Literal seeds accept only JSON primitive values",
|
||||
),
|
||||
value: literalValueSchema,
|
||||
});
|
||||
|
||||
/** Authenticated starting points accepted by semantic tracing. */
|
||||
|
||||
@@ -99,3 +99,34 @@ describe("jsonValueSchema depth bound", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves prototype-named members without prototype mutation", () => {
|
||||
const input: unknown = JSON.parse(
|
||||
'{"__proto__":{"preserved":7},"constructor":"ordinary","prototype":[1],"nested":{"\\u005f\\u005fproto\\u005f\\u005f":"escaped"},"list":[{"__proto__":null}]}',
|
||||
);
|
||||
const parsed = jsonObjectSchema.parse(input);
|
||||
expect(parsed).toEqual(input);
|
||||
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
|
||||
expect(Object.hasOwn(parsed, "__proto__")).toBe(true);
|
||||
expect(parsed["__proto__"]).toEqual({ preserved: 7 });
|
||||
expect(parsed["constructor"]).toBe("ordinary");
|
||||
expect(parsed["prototype"]).toEqual([1]);
|
||||
expect(parsed["nested"]).toEqual({ ["__proto__"]: "escaped" });
|
||||
expect(parsed["list"]).toEqual([{ ["__proto__"]: null }]);
|
||||
expect(Object.getPrototypeOf(parsed["nested"])).toBe(Object.prototype);
|
||||
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
|
||||
expect(JSON.parse(JSON.stringify(parsed))).toEqual(input);
|
||||
});
|
||||
|
||||
it.each([undefined, Number.NaN, Infinity, 1n, () => 0, new Date(0)])(
|
||||
"rejects non-JSON values in prototype-named members (%s)",
|
||||
(value) => {
|
||||
for (const input of [
|
||||
{ ["__proto__"]: value },
|
||||
{ nested: [{ ["__proto__"]: value }] },
|
||||
]) {
|
||||
expect(jsonValueSchema.safeParse(input).success).toBe(false);
|
||||
expect(jsonObjectSchema.safeParse(input).success).toBe(false);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
+63
-43
@@ -1,67 +1,87 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Maximum nesting depth accepted for JSON values.
|
||||
*
|
||||
* Sits well below the point where the recursive `z.json()` 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.
|
||||
*/
|
||||
/** Maximum JSON nesting accepted before recursive result cloning. */
|
||||
export const MAX_JSON_DEPTH = 1000;
|
||||
|
||||
/** JSON-safe value shared by domain, application, and adapter boundaries. */
|
||||
export type JsonValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| JsonValue[]
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const recordShape = z.record(z.string(), z.unknown());
|
||||
|
||||
const exceedsMaxDepth = (root: unknown): boolean => {
|
||||
// Depth counts edges from the root.
|
||||
const jsonValidationIssue = (root: unknown): string | undefined => {
|
||||
const pending: { value: unknown; depth: number }[] = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
while (pending.length > 0) {
|
||||
const item = pending.pop();
|
||||
if (item === undefined) break;
|
||||
if (item.depth > MAX_JSON_DEPTH) return true;
|
||||
if (item.depth > MAX_JSON_DEPTH)
|
||||
return `JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}`;
|
||||
const value = item.value;
|
||||
if (Array.isArray(value)) {
|
||||
if (
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "boolean"
|
||||
)
|
||||
continue;
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) return "JSON numbers must be finite";
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const child of value)
|
||||
pending.push({ value: child, depth: item.depth + 1 });
|
||||
} else if (isRecord(value)) {
|
||||
for (const key of Object.keys(value))
|
||||
pending.push({ value: value[key], depth: item.depth + 1 });
|
||||
}
|
||||
} else if (isRecord(value) && recordShape.safeParse(value).success) {
|
||||
// Inspect every own member, including keys Zod's record parser skips.
|
||||
for (const child of Object.values(value))
|
||||
pending.push({ value: child, depth: item.depth + 1 });
|
||||
} else return "Invalid JSON value";
|
||||
}
|
||||
return false;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* JSON-safe value shared by domain, application, and adapter boundaries.
|
||||
*
|
||||
* An iterative depth guard runs before the recursive `z.json()` core so
|
||||
* hostile nested payloads surface as validation issues instead of RangeErrors.
|
||||
* The guard only refuses over-deep values; ordinary JSON parsing semantics
|
||||
* (including which members `z.json()` keeps) are unchanged.
|
||||
*/
|
||||
const jsonCore = z.json();
|
||||
// Every JSON value satisfies `{}`. Advertise that instead of Zod's
|
||||
// self-referential `$defs` projection, which MCP clients and model APIs that
|
||||
// reject recursive JSON Schemas refuse. Runtime parsing still admits only JSON.
|
||||
// The override sits on the core as well as on the pipe because the standard
|
||||
// JSON Schema projection walks into pipe stages without consulting the outer
|
||||
// node, while the public toJSONSchema projection stops at the pipe.
|
||||
jsonCore._zod.toJSONSchema = () => ({});
|
||||
const preserveJsonValue = (value: JsonValue): JsonValue => {
|
||||
if (Array.isArray(value)) return value.map(preserveJsonValue);
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries<JsonValue>(
|
||||
Object.entries(value).map(([key, child]) => [
|
||||
key,
|
||||
preserveJsonValue(child),
|
||||
]),
|
||||
);
|
||||
return value;
|
||||
};
|
||||
|
||||
const validatedJsonValue = z.custom<JsonValue>(
|
||||
(value) => jsonValidationIssue(value) === undefined,
|
||||
{
|
||||
error: (issue) => jsonValidationIssue(issue.input) ?? "Invalid JSON value",
|
||||
},
|
||||
);
|
||||
// Keep both stages nonrecursive in public and Standard Schema projections.
|
||||
validatedJsonValue._zod.toJSONSchema = () => ({});
|
||||
|
||||
/** Parse bounded JSON and retain all own data members without prototype setters. */
|
||||
export const jsonValueSchema = z
|
||||
.unknown()
|
||||
.superRefine((value, context) => {
|
||||
if (exceedsMaxDepth(value))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}`,
|
||||
});
|
||||
})
|
||||
.pipe(jsonCore);
|
||||
.nonoptional()
|
||||
.pipe(validatedJsonValue)
|
||||
.transform(preserveJsonValue);
|
||||
jsonValueSchema._zod.toJSONSchema = () => ({});
|
||||
|
||||
/** JSON object boundary for caller-visible parameter maps. */
|
||||
export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
|
||||
const objectValidation = z.custom<Record<string, JsonValue>>(
|
||||
isRecord,
|
||||
"Expected JSON object",
|
||||
);
|
||||
const objectProjection = () => ({ type: "object", additionalProperties: {} });
|
||||
objectValidation._zod.toJSONSchema = objectProjection;
|
||||
|
||||
export type JsonValue = z.infer<typeof jsonValueSchema>;
|
||||
/** JSON object boundary for caller-visible parameter maps. */
|
||||
export const jsonObjectSchema = jsonValueSchema.pipe(objectValidation);
|
||||
jsonObjectSchema._zod.toJSONSchema = objectProjection;
|
||||
|
||||
@@ -223,6 +223,10 @@ export interface UnverifiedProcessCapture {
|
||||
readonly cleanup: {
|
||||
readonly owned_process_group: "verified";
|
||||
readonly temporary_root: "removed";
|
||||
/** Unrelated processes whose ownership token the host could not expose. */
|
||||
readonly unverified_processes?:
|
||||
| readonly UnverifiedCleanupProcess[]
|
||||
| undefined;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -232,10 +236,19 @@ const fileStateShape = {
|
||||
size: z.number().int().nonnegative(),
|
||||
};
|
||||
|
||||
/** An unrelated process left untouched because its ownership is unknown. */
|
||||
export interface UnverifiedCleanupProcess {
|
||||
readonly pid: number;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
/** A resource cleanup result retained when observations cannot be verified. */
|
||||
export interface ProcessCaptureResourceCleanup {
|
||||
readonly state: "cleaned" | "failed" | "unverified" | "not_required";
|
||||
readonly reason: string | null;
|
||||
readonly unverified_processes?:
|
||||
| readonly UnverifiedCleanupProcess[]
|
||||
| undefined;
|
||||
}
|
||||
|
||||
export interface ProcessCaptureCleanupReport {
|
||||
@@ -348,6 +361,10 @@ const processSettlementSchema = z.discriminatedUnion("state", [
|
||||
}),
|
||||
]);
|
||||
|
||||
const unverifiedCleanupProcessesSchema = z.array(
|
||||
z.strictObject({ pid: z.number().int().positive(), reason: z.string() }),
|
||||
);
|
||||
|
||||
const processCaptureShapeSchema = z.strictObject({
|
||||
manifest: z.strictObject({
|
||||
rea_version: z.string().min(1),
|
||||
@@ -478,12 +495,14 @@ const processCaptureShapeSchema = z.strictObject({
|
||||
cleanup: z.object({
|
||||
owned_process_group: z.literal("verified"),
|
||||
temporary_root: z.literal("removed"),
|
||||
unverified_processes: unverifiedCleanupProcessesSchema.optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
const processCleanupResourceSchema = z.strictObject({
|
||||
state: z.enum(["cleaned", "failed", "unverified", "not_required"]),
|
||||
reason: z.string().nullable(),
|
||||
unverified_processes: unverifiedCleanupProcessesSchema.optional(),
|
||||
});
|
||||
|
||||
const partialObservationFieldSchema = <Schema extends z.ZodType>(
|
||||
|
||||
Reference in New Issue
Block a user