fix(javascript): hash graph and evidence JSON incrementally (#646)
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { fc, it } from "@fast-check/vitest";
|
||||
import canonicalize from "canonicalize";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
|
||||
const legacyDigest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined) throw new TypeError("Unserializable fixture");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
describe("incremental canonical digest", () => {
|
||||
it.prop([fc.jsonValue()])(
|
||||
"preserves canonicalize digests for JSON values",
|
||||
(value) => {
|
||||
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves Unicode ordering, escaping, numeric forms and non-JSON normalization", () => {
|
||||
const shared = { key: "value" };
|
||||
const sparse: unknown[] = [undefined, Symbol("omit"), () => undefined];
|
||||
sparse.length = 6;
|
||||
const fixtures: unknown[] = [
|
||||
{
|
||||
"€": "\ud800",
|
||||
"😀": "\udc00",
|
||||
"\r": '\n\t"\\',
|
||||
number: -0,
|
||||
exponent: 1e30,
|
||||
},
|
||||
{ omitted: undefined, symbol: Symbol("omit"), fn: () => undefined },
|
||||
sparse,
|
||||
[shared, shared],
|
||||
new Date("2026-10-06T00:00:00Z"),
|
||||
{ toJSON: () => ({ b: 2, a: [1, null] }) },
|
||||
{ nested: { toJSON: () => undefined } },
|
||||
];
|
||||
for (const value of fixtures)
|
||||
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
|
||||
});
|
||||
|
||||
it("rejects unsupported roots, non-finite numbers, BigInt and ancestor cycles", () => {
|
||||
for (const value of [undefined, Symbol("root"), () => undefined])
|
||||
expect(() => digestCanonicalValue(value, "Fixture")).toThrow(
|
||||
"Fixture could not canonicalize data",
|
||||
);
|
||||
const cyclic: Record<string, unknown> = {};
|
||||
cyclic.self = cyclic;
|
||||
const recursiveJson = { toJSON: (): unknown => recursiveJson };
|
||||
for (const value of [NaN, Infinity, -Infinity, 1n, cyclic, recursiveJson])
|
||||
expect(() => digestCanonicalValue(value)).toThrow();
|
||||
});
|
||||
|
||||
it("hashes repeated large leaves with the same byte sequence", () => {
|
||||
const value = {
|
||||
payload: Array.from({ length: 64 }, () => "x".repeat(16_384)),
|
||||
};
|
||||
expect(digestCanonicalValue(value)).toBe(legacyDigest(value));
|
||||
});
|
||||
|
||||
it("preserves canonicalize property access and toJSON cycle behavior", () => {
|
||||
const createAccessor = () => {
|
||||
let reads = 0;
|
||||
return {
|
||||
get value() {
|
||||
reads += 1;
|
||||
return reads;
|
||||
},
|
||||
};
|
||||
};
|
||||
expect(digestCanonicalValue(createAccessor())).toBe(
|
||||
legacyDigest(createAccessor()),
|
||||
);
|
||||
const shared = { toJSON: () => ({ answer: 42 }) };
|
||||
expect(digestCanonicalValue([shared, shared])).toBe(
|
||||
legacyDigest([shared, shared]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/** Hash canonicalize-compatible JSON without assembling an aggregate string. */
|
||||
export const digestCanonicalValue = (
|
||||
value: unknown,
|
||||
context = "Comparison",
|
||||
): string => {
|
||||
const hash = createHash("sha256");
|
||||
const encoded = emitCanonical(value, (part) => hash.update(part), new Set());
|
||||
if (!encoded) throw new TypeError(`${context} could not canonicalize data`);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
type Emit = (part: string) => void;
|
||||
|
||||
const emitCanonical = (
|
||||
value: unknown,
|
||||
emit: Emit,
|
||||
ancestors: Set<object>,
|
||||
): boolean => {
|
||||
if (typeof value === "number" && !Number.isFinite(value))
|
||||
throw new Error(
|
||||
Number.isNaN(value) ? "NaN is not allowed" : "Infinity is not allowed",
|
||||
);
|
||||
if (value === null || typeof value !== "object") {
|
||||
const encoded = JSON.stringify(value);
|
||||
if (encoded === undefined) return false;
|
||||
emit(encoded);
|
||||
return true;
|
||||
}
|
||||
if (ancestors.has(value)) throw new Error("Circular reference detected");
|
||||
ancestors.add(value);
|
||||
try {
|
||||
if ("toJSON" in value && typeof value.toJSON === "function") {
|
||||
const normalized: unknown = value.toJSON();
|
||||
return emitCanonical(normalized, emit, ancestors);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
emit("[");
|
||||
const length = value.length;
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
if (index > 0) emit(",");
|
||||
// Preserve canonicalize's sparse-array and unsupported-value behavior.
|
||||
if (!(index in value)) continue;
|
||||
const item: unknown = value[index];
|
||||
emitCanonical(
|
||||
item === undefined || typeof item === "symbol" ? null : item,
|
||||
emit,
|
||||
ancestors,
|
||||
);
|
||||
}
|
||||
emit("]");
|
||||
} else {
|
||||
emit("{");
|
||||
let first = true;
|
||||
for (const key of Object.keys(value).sort()) {
|
||||
if (
|
||||
Reflect.get(value, key) === undefined ||
|
||||
typeof Reflect.get(value, key) === "symbol"
|
||||
)
|
||||
continue;
|
||||
const item: unknown = Reflect.get(value, key);
|
||||
if (!first) emit(",");
|
||||
first = false;
|
||||
emit(JSON.stringify(key));
|
||||
emit(":");
|
||||
if (!emitCanonical(item, emit, ancestors)) emit("undefined");
|
||||
}
|
||||
emit("}");
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
ancestors.delete(value);
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
|
||||
/** Whether an inventory can support a claim that an item is absent. */
|
||||
export const absenceClaimable = (coverage: {
|
||||
readonly status: string;
|
||||
@@ -17,9 +17,7 @@ export const canonicalDigest = (
|
||||
value: unknown,
|
||||
context = "Comparison",
|
||||
): string => {
|
||||
return createHash("sha256")
|
||||
.update(canonicalJson(value, context))
|
||||
.digest("hex");
|
||||
return digestCanonicalValue(value, context);
|
||||
};
|
||||
|
||||
/** Canonical JSON used for deterministic tie breaking and stable digests. */
|
||||
|
||||
+3
-15
@@ -1,8 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
type AnalysisProfileCommitment,
|
||||
@@ -173,22 +172,11 @@ export interface EvidenceObservation {
|
||||
readonly evidenceLinks?: readonly string[];
|
||||
}
|
||||
|
||||
const sha256 = (value: string): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
type WithoutEvidenceId<Record_> = Record_ extends unknown
|
||||
? Omit<Record_, "evidence_id">
|
||||
: never;
|
||||
type EvidenceWithoutId = WithoutEvidenceId<Evidence>;
|
||||
|
||||
/** Serialize JSON according to RFC 8785 JSON Canonicalization Scheme. */
|
||||
const canonicalJson = (value: JsonValue): string => {
|
||||
const serialized = canonicalize(value);
|
||||
if (serialized === undefined)
|
||||
throw new TypeError("RFC 8785 canonicalization rejected a JSON value");
|
||||
return serialized;
|
||||
};
|
||||
|
||||
const semanticProjection = (evidence: EvidenceWithoutId): JsonValue => ({
|
||||
subject:
|
||||
evidence.subject === null
|
||||
@@ -217,7 +205,7 @@ const semanticProjection = (evidence: EvidenceWithoutId): JsonValue => ({
|
||||
|
||||
/** Recompute the semantic identifier, excluding paths and raw payload bytes. */
|
||||
const computeEvidenceId = (evidence: EvidenceWithoutId): string =>
|
||||
`ev_${sha256(canonicalJson(semanticProjection(evidence)))}`;
|
||||
`ev_${digestCanonicalValue(semanticProjection(evidence), "Evidence")}`;
|
||||
|
||||
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
|
||||
export const parseEvidence = (input: unknown): Evidence => {
|
||||
|
||||
Reference in New Issue
Block a user