@directive-run/core 1.22.0 → 1.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.d.cts +1 -1
- package/dist/adapter-utils.d.ts +1 -1
- package/dist/adapter-utils.js +1 -1
- package/dist/chunk-C3FW27S5.js +3 -0
- package/dist/chunk-C3FW27S5.js.map +1 -0
- package/dist/chunk-IZNOPHPL.js +3 -0
- package/dist/chunk-IZNOPHPL.js.map +1 -0
- package/dist/chunk-LN5H74CU.js +2 -0
- package/dist/{chunk-RBF653NR.js.map → chunk-LN5H74CU.js.map} +1 -1
- package/dist/chunk-PTT4MWNL.cjs +3 -0
- package/dist/chunk-PTT4MWNL.cjs.map +1 -0
- package/dist/chunk-QR2756CJ.js +2 -0
- package/dist/chunk-QR2756CJ.js.map +1 -0
- package/dist/{chunk-GKMJ7NMP.cjs → chunk-RD2HO5NZ.cjs} +2 -2
- package/dist/{chunk-GKMJ7NMP.cjs.map → chunk-RD2HO5NZ.cjs.map} +1 -1
- package/dist/{chunk-GACC2DMS.cjs → chunk-S6W6Y44G.cjs} +2 -2
- package/dist/{chunk-GACC2DMS.cjs.map → chunk-S6W6Y44G.cjs.map} +1 -1
- package/dist/{chunk-YJEDX2JX.js → chunk-SERVIHA3.js} +3 -3
- package/dist/chunk-SERVIHA3.js.map +1 -0
- package/dist/{chunk-OAPD3HIG.cjs → chunk-UDSP7U54.cjs} +3 -3
- package/dist/chunk-UDSP7U54.cjs.map +1 -0
- package/dist/chunk-UQZ2SMGS.cjs +2 -0
- package/dist/chunk-UQZ2SMGS.cjs.map +1 -0
- package/dist/{chunk-6PF2FRBG.js → chunk-WD47DB52.js} +2 -2
- package/dist/{chunk-6PF2FRBG.js.map → chunk-WD47DB52.js.map} +1 -1
- package/dist/chunk-WU4AXN3P.cjs +3 -0
- package/dist/chunk-WU4AXN3P.cjs.map +1 -0
- package/dist/{index-DRPkZ8HE.d.cts → index-Bz6DOdDN.d.ts} +32 -5
- package/dist/{index-BgKC_ZT_.d.ts → index-Cpgj4byM.d.cts} +32 -5
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -130
- package/dist/index.d.ts +8 -130
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.d.cts +10 -4
- package/dist/internals.d.ts +10 -4
- package/dist/internals.js +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +202 -3
- package/dist/plugins/index.d.ts +202 -3
- package/dist/plugins/index.js +2 -2
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-5Supk7it.d.cts → plugins-CaPMTICa.d.cts} +323 -2
- package/dist/{plugins-5Supk7it.d.ts → plugins-CaPMTICa.d.ts} +323 -2
- package/dist/{predicate-DYb-3Mvl.d.cts → predicate-CU0YC1i6.d.cts} +1 -1
- package/dist/{predicate-C9oMO_ny.d.ts → predicate-CgpwJqf4.d.ts} +1 -1
- package/dist/system-T6EZ6EYN.js +2 -0
- package/dist/{system-6YWCXQOQ.js.map → system-T6EZ6EYN.js.map} +1 -1
- package/dist/system-V7B4YUIR.cjs +2 -0
- package/dist/{system-5FKUBLLV.cjs.map → system-V7B4YUIR.cjs.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-6NCC6RBC.js +0 -3
- package/dist/chunk-6NCC6RBC.js.map +0 -1
- package/dist/chunk-GBCWXTXW.cjs +0 -3
- package/dist/chunk-GBCWXTXW.cjs.map +0 -1
- package/dist/chunk-KGTBTGOY.js +0 -2
- package/dist/chunk-KGTBTGOY.js.map +0 -1
- package/dist/chunk-MARZI3EY.cjs +0 -2
- package/dist/chunk-MARZI3EY.cjs.map +0 -1
- package/dist/chunk-OAPD3HIG.cjs.map +0 -1
- package/dist/chunk-QTY2FXZY.cjs +0 -3
- package/dist/chunk-QTY2FXZY.cjs.map +0 -1
- package/dist/chunk-RBF653NR.js +0 -2
- package/dist/chunk-SFUVPP4L.js +0 -3
- package/dist/chunk-SFUVPP4L.js.map +0 -1
- package/dist/chunk-YJEDX2JX.js.map +0 -1
- package/dist/system-5FKUBLLV.cjs +0 -2
- package/dist/system-6YWCXQOQ.js +0 -2
package/dist/chunk-GBCWXTXW.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
'use strict';var b=typeof process<"u"&&process.env?.NODE_ENV!=="production";function m(n,o=new WeakSet){if(n===null||typeof n!="object")return n;let r=n;if(o.has(r)||Object.isFrozen(r))return n;if(o.add(r),Array.isArray(r))for(let s of r)m(s,o);else for(let s of Object.keys(r))m(r[s],o);return Object.freeze(r),n}function x(n){return m(n)}function A(n,o,r){return (...s)=>{try{return r(...s)}catch(u){throw u instanceof Error&&u.message.startsWith("[Directive] ")?new Error(`[Directive] ${n} '${o}': ${u.message.slice(12)}`,{cause:u}):u}}}async function T(n,o,r){let s,u=new Promise((g,d)=>{s=setTimeout(()=>d(new Error(r)),o);});try{return await Promise.race([n,u])}finally{clearTimeout(s);}}function l(n,o=50){let r=new WeakSet;function s(t){if(t===null)return "null";if(t===void 0)return "undefined";let e=typeof t;if(e==="string")return JSON.stringify(t);if(e==="number"||e==="boolean")return String(t);if(e==="function")return '"[function]"';if(e==="symbol")return '"[symbol]"'}function u(t,e){if(r.has(t))return '"[circular]"';r.add(t);let i=e();return r.delete(t),i}function g(t,e){return u(t,()=>`[${t.map(i=>c(i,e+1)).join(",")}]`)}function d(t,e){return u(t,()=>`{${Object.keys(t).sort().map(f=>`${JSON.stringify(f)}:${c(t[f],e+1)}`).join(",")}}`)}function c(t,e){if(e>o)return '"[max depth exceeded]"';if(typeof t=="bigint")return `${t.toString()}n`;let i=s(t);if(i!==void 0)return i;if(t instanceof Date)return `D:${t.toISOString()}`;if(t instanceof RegExp)return `R:${t.source}:${t.flags}`;if(t instanceof Map){let a=[...t.entries()].sort();return `M:${c(a,e+1)}`}if(t instanceof Set){let a=[...t].sort();return `S:${c(a,e+1)}`}return Array.isArray(t)?g(t,e):typeof t=="object"?d(t,e):'"[unknown]"'}return c(n,0)}function D(n,o=50){let r=new Set(["__proto__","constructor","prototype"]),s=new WeakSet;function u(t,e){if(s.has(t))return true;s.add(t);let i=e();return s.delete(t),i}function g(t,e){for(let i of t)if(!c(i,e+1))return false;return true}function d(t,e){for(let i of Object.keys(t))if(r.has(i)||!c(t[i],e+1))return false;return true}function c(t,e){if(e>o)return false;if(t==null||typeof t!="object")return true;let i=t;return Array.isArray(i)?u(i,()=>g(i,e)):u(i,()=>d(i,e))}return c(n,0)}function E(n,o){if(n===o)return true;if(!n||!o)return false;let r=Object.keys(n),s=Object.keys(o);if(r.length!==s.length)return false;for(let u of r)if(n[u]!==o[u])return false;return true}function $(n){let o=l(n),r=5381;for(let s=0;s<o.length;s++)r=(r<<5)+r^o.charCodeAt(s);return (r>>>0).toString(16)}function k(n,o=Date.now()){return n.expiresAt!==void 0&&o>n.expiresAt}function R(n,o=Date.now()){if(!n||typeof n!="object")throw new Error("[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.");if(!("data"in n))throw new Error("[Directive] Invalid snapshot: missing required 'data' property.");if(!("createdAt"in n)||typeof n.createdAt!="number")throw new Error("[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).");if(k(n,o)){let r=new Date(n.expiresAt).toISOString();throw new Error(`[Directive] Snapshot expired at ${r}. Obtain a fresh snapshot from the source.`)}return n.data}function P(n,o){let r=[];function s(e,i,a,f){r.push({path:e,oldValue:i,newValue:a,type:f});}function u(e,i,a){return e==null?(i!=null&&s(a,e,i,"added"),true):i==null?(s(a,e,i,"removed"),true):false}function g(e,i,a){if(e.length!==i.length){s(a,e,i,"changed");return}for(let f=0;f<e.length;f++)c(e[f],i[f],`${a}[${f}]`);}function d(e,i,a){let f=new Set([...Object.keys(e),...Object.keys(i)]);for(let y of f){let p=a?`${a}.${y}`:y;y in e?y in i?c(e[y],i[y],p):s(p,e[y],void 0,"removed"):s(p,void 0,i[y],"added");}}function c(e,i,a){if(!u(e,i,a)){if(typeof e!="object"||typeof i!="object"){Object.is(e,i)||s(a,e,i,"changed");return}if(Array.isArray(e)&&Array.isArray(i)){g(e,i,a);return}d(e,i,a);}}c(n.data,o.data,"");let t=n.version!==o.version&&(n.version!==void 0||o.version!==void 0);return {identical:r.length===0,changes:r,versionChanged:t,oldVersion:n.version,newVersion:o.version}}function C(n){return "signature"in n&&typeof n.signature=="string"}async function v(n,o){let r=l({data:n.data,createdAt:n.createdAt,expiresAt:n.expiresAt,version:n.version,metadata:n.metadata}),s=await h(r,o);return {...n,signature:s,algorithm:"hmac-sha256"}}async function I(n,o,r){if(!n.signature||n.algorithm!=="hmac-sha256")return false;let s=l({data:n.data,createdAt:n.createdAt,expiresAt:n.expiresAt,version:n.version,metadata:n.metadata}),u=await h(s,o);return !(!w(n.signature,u)||!r?.ignoreExpiry&&k(n,r?.now))}async function h(n,o){let r=typeof o=="string"?new TextEncoder().encode(o):o,s={name:"HMAC",hash:{name:"SHA-256"}},u=await crypto.subtle.importKey("raw",r,s,false,["sign"]),g=new TextEncoder().encode(n),d=await crypto.subtle.sign("HMAC",u,g);return Array.from(new Uint8Array(d)).map(c=>c.toString(16).padStart(2,"0")).join("")}function w(n,o){if(n.length!==o.length)return false;let r=0;for(let s=0;s<n.length;s++)r|=n.charCodeAt(s)^o.charCodeAt(s);return r===0}function L(n,o=500){try{let r=JSON.stringify(n,(s,u)=>typeof u=="bigint"?`${u}n`:u,2);return r?r.length<=o?r:`${r.slice(0,o)}
|
|
2
|
-
... (truncated, ${r.length} chars total)`:"[undefined]"}catch{return "[unserializable]"}}exports.a=b;exports.b=x;exports.c=A;exports.d=T;exports.e=l;exports.f=D;exports.g=E;exports.h=$;exports.i=k;exports.j=R;exports.k=P;exports.l=C;exports.m=v;exports.n=I;exports.o=L;//# sourceMappingURL=chunk-GBCWXTXW.cjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-GBCWXTXW.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dev-true.ts","../src/utils/utils.ts"],"names":["dev_true_default","deepFreeze","value","seen","obj","item","key","freezeSpec","spec","attributeError","category","id","fn","args","e","withTimeout","promise","ms","errorMessage","timeoutId","timeoutPromise","_","reject","stableStringify","maxDepth","stringifyPrimitive","val","type","withCircularGuard","result","stringifyArray","depth","v","stringify","stringifyObject","k","primitive","entries","items","isPrototypeSafe","dangerousKeys","objVal","checkArray","arr","check","checkObject","shallowEqual","a","b","keysA","keysB","hashObject","str","hash","i","isSnapshotExpired","snapshot","now","validateSnapshot","expiredAt","diffSnapshots","oldSnapshot","newSnapshot","changes","pushChange","path","oldValue","newValue","compareNullish","oldObj","newObj","compareArrays","oldArr","newArr","compare","compareObjects","oldRecord","newRecord","allKeys","childPath","versionChanged","isSignedSnapshot","signSnapshot","secret","payload","signature","hmacSha256","verifySnapshotSignature","signedSnapshot","options","expectedSignature","timingSafeEqual","message","secretBytes","algorithm","messageBytes","safeStringify","data","maxLen","_key"],"mappings":"aAIA,IAAOA,CAAAA,CAAQ,OAAO,OAAA,CAAY,GAAA,EAChC,QAAQ,GAAA,EAAK,QAAA,GAAa,aCarB,SAASC,EACdC,CAAAA,CACAC,CAAAA,CAAwB,IAAI,OAAA,CACzB,CACH,GAAID,CAAAA,GAAU,IAAA,EAAQ,OAAOA,GAAU,QAAA,CACrC,OAAOA,CAAAA,CAET,IAAME,EAAMF,CAAAA,CACZ,GAAIC,CAAAA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,CACT9C,EAGF,CAAA,EAAGA,CAAAA,CAAI,KAAA,CAAM,CAAA,CAAG8C,CAAM,CAAC;AAAA,gBAAA,EAAqB9C,CAAAA,CAAI,MAAM,CAAA,aAAA,CAAA,CANpD,aAOX,MAAQ,CACN,OAAO,kBACT,CACF","file":"chunk-GBCWXTXW.cjs","sourcesContent":["// Runtime check that bundlers (webpack, esbuild, turbopack, rollup) inline\n// based on the consumer's NODE_ENV. Without this, the published bundle bakes\n// in `true` and dev-mode validation runs in every consumer's production\n// build — a real footgun the v1.5/v1.6 release hit.\nexport default typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\";\n","/**\n * Shared utilities for Directive\n */\n\n// ============================================================================\n// Deep freeze\n// ============================================================================\n\n/**\n * Recursively `Object.freeze` an object including nested objects, arrays, and\n * array elements. Uses a `WeakSet` to handle cycles. Skips primitives and\n * already-frozen values to avoid wasted work.\n *\n * Used at definition-registration sites (constraints, derivations, effects,\n * events, prefixed specs) so post-registration mutation of a nested operand\n * cannot silently change the compiled closure's behavior. Prefer\n * {@link freezeSpec} at registration sites — it documents the convention.\n */\nexport function deepFreeze<T>(\n value: T,\n seen: WeakSet<object> = new WeakSet(),\n): T {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const obj = value as unknown as object;\n if (seen.has(obj) || Object.isFrozen(obj)) {\n return value;\n }\n seen.add(obj);\n\n if (Array.isArray(obj)) {\n for (const item of obj) {\n deepFreeze(item, seen);\n }\n } else {\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key], seen);\n }\n }\n\n Object.freeze(obj);\n return value;\n}\n\n/**\n * Freeze a definition spec at registration. Centralizes the deepFreeze\n * convention so a new definition arm cannot forget it — every constraint,\n * derivation, effect, event, and prefixed-spec registration funnels through\n * this single helper.\n *\n * @param spec - The definition spec to freeze (mutated in place, returned)\n * @returns The same `spec` value, now deeply frozen\n *\n * @example\n * ```ts\n * // At registration time, freeze user-supplied specs so post-registration\n * // mutation cannot silently change the compiled closure's behavior.\n * const spec = freezeSpec(userPredicate);\n * memoizePredicate(spec);\n * ```\n */\nexport function freezeSpec<T>(spec: T): T {\n return deepFreeze(spec);\n}\n\n/**\n * Wrap a synthesized definition function so a `[Directive]`-prefixed error\n * thrown from inside it is re-thrown with the owning definition's category +\n * id injected, and the original error preserved as `cause`. Non-`[Directive]`\n * errors (user code, native) pass through untouched.\n *\n * Centralizes the owner-attribution wrap shared by the data-form `when`\n * (constraints), `on` (effects), and `compute` (derivations) closures — a\n * `[Directive]`-prefixed throw (e.g. `$matches: string`) is re-pointed at the\n * owning definition so the stack trace blames user config, not the runtime.\n *\n * @param category - The owning definition kind, used in the re-thrown message.\n * @param id - The owning definition's id.\n * @param fn - The synthesized function to wrap.\n * @returns A function with identical signature that re-attributes Directive errors.\n */\nexport function attributeError<A extends unknown[], R>(\n category: \"constraint\" | \"effect\" | \"derivation\",\n id: string,\n fn: (...args: A) => R,\n): (...args: A) => R {\n // Synchronous by design: the wrapped definition functions (memoized\n // predicate `when`/`on` closures, template closures) always return\n // synchronously. A `try/catch` only re-attributes a synchronous throw — an\n // async-returning fn's rejected promise would escape un-re-attributed.\n return (...args: A): R => {\n try {\n return fn(...args);\n } catch (e) {\n if (e instanceof Error && e.message.startsWith(\"[Directive] \")) {\n throw new Error(\n `[Directive] ${category} '${id}': ${e.message.slice(\"[Directive] \".length)}`,\n { cause: e },\n );\n }\n throw e;\n }\n };\n}\n\n/**\n * Execute a promise with a timeout, properly cleaning up the timer.\n * Used by both constraints and resolvers for timeout handling.\n *\n * @param promise - The promise to wrap with a timeout\n * @param ms - Timeout duration in milliseconds\n * @param errorMessage - Error message if timeout occurs\n * @returns The promise result\n * @throws Error if timeout is exceeded\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n errorMessage: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(errorMessage)), ms);\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n clearTimeout(timeoutId!);\n }\n}\n\n/**\n * Normalize an error to an Error instance.\n * Ensures consistent error handling throughout the library.\n *\n * @param error - The error to normalize (can be anything)\n * @returns An Error instance\n */\nexport function normalizeError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n/**\n * Create a stable JSON string with sorted keys.\n * Handles circular references and deeply nested objects safely.\n *\n * @param value - The value to stringify\n * @param maxDepth - Maximum nesting depth (default: 50)\n * @returns A stable JSON string\n */\nexport function stableStringify(value: unknown, maxDepth = 50): string {\n const seen = new WeakSet();\n\n /** Stringify a primitive value (null, undefined, string, number, boolean, function, symbol). */\n function stringifyPrimitive(val: unknown): string | undefined {\n if (val === null) return \"null\";\n if (val === undefined) return \"undefined\";\n\n const type = typeof val;\n if (type === \"string\") return JSON.stringify(val);\n if (type === \"number\" || type === \"boolean\") return String(val);\n if (type === \"function\") return '\"[function]\"';\n if (type === \"symbol\") return '\"[symbol]\"';\n\n return undefined;\n }\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(obj: object, fn: () => string): string {\n if (seen.has(obj)) {\n return '\"[circular]\"';\n }\n seen.add(obj);\n const result = fn();\n seen.delete(obj);\n\n return result;\n }\n\n /** Stringify an array with circular reference protection. */\n function stringifyArray(val: unknown[], depth: number): string {\n return withCircularGuard(\n val,\n () => `[${val.map((v) => stringify(v, depth + 1)).join(\",\")}]`,\n );\n }\n\n /** Stringify an object with sorted keys and circular reference protection. */\n function stringifyObject(\n obj: Record<string, unknown>,\n depth: number,\n ): string {\n return withCircularGuard(obj, () => {\n const keys = Object.keys(obj).sort();\n const pairs = keys.map(\n (k) => `${JSON.stringify(k)}:${stringify(obj[k], depth + 1)}`,\n );\n\n return `{${pairs.join(\",\")}}`;\n });\n }\n\n /** Recursively stringify a value with depth limit and circular detection. */\n function stringify(val: unknown, depth: number): string {\n if (depth > maxDepth) {\n return '\"[max depth exceeded]\"';\n }\n\n // BigInt is not JSON-serializable; encode with a trailing 'n' to remain\n // distinct from numeric strings.\n if (typeof val === \"bigint\") {\n return `${val.toString()}n`;\n }\n\n const primitive = stringifyPrimitive(val);\n if (primitive !== undefined) {\n return primitive;\n }\n\n // Typed-value branches: each prefix is bare (no outer quotes) so it can\n // never collide with a JSON-encoded string. `JSON.stringify(\"D:...\")`\n // emits `\"D:...\"` (the wrapping quotes ARE part of the output string),\n // whereas the Date branch emits `D:...` (no quotes). Distinct outputs.\n if (val instanceof Date) {\n return `D:${val.toISOString()}`;\n }\n if (val instanceof RegExp) {\n return `R:${val.source}:${val.flags}`;\n }\n if (val instanceof Map) {\n const entries = [...val.entries()].sort();\n return `M:${stringify(entries, depth + 1)}`;\n }\n if (val instanceof Set) {\n const items = [...val].sort();\n return `S:${stringify(items, depth + 1)}`;\n }\n\n if (Array.isArray(val)) {\n return stringifyArray(val, depth);\n }\n\n if (typeof val === \"object\") {\n return stringifyObject(val as Record<string, unknown>, depth);\n }\n\n return '\"[unknown]\"';\n }\n\n return stringify(value, 0);\n}\n\n/**\n * Check for prototype pollution in an object, including nested objects.\n * Returns true if the object is safe, false if dangerous keys are found.\n *\n * @param obj - The object to check\n * @param maxDepth - Maximum nesting depth to check (default: 50)\n * @returns True if safe, false if dangerous keys found\n */\nexport function isPrototypeSafe(obj: unknown, maxDepth = 50): boolean {\n const dangerousKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n const seen = new WeakSet();\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(objVal: object, fn: () => boolean): boolean {\n if (seen.has(objVal)) return true;\n seen.add(objVal);\n const result = fn();\n seen.delete(objVal);\n\n return result;\n }\n\n /** Check array elements for prototype pollution keys. */\n function checkArray(arr: unknown[], depth: number): boolean {\n for (const item of arr) {\n if (!check(item, depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Check object keys and values for prototype pollution. */\n function checkObject(\n objVal: Record<string, unknown>,\n depth: number,\n ): boolean {\n for (const key of Object.keys(objVal)) {\n if (dangerousKeys.has(key)) {\n return false;\n }\n if (!check(objVal[key], depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Recursively check a value tree for dangerous prototype keys. */\n function check(val: unknown, depth: number): boolean {\n if (depth > maxDepth) return false; // Fail safe at max depth - don't assume safety\n if (val === null || val === undefined) return true;\n if (typeof val !== \"object\") return true;\n\n const objVal = val as Record<string, unknown>;\n\n if (Array.isArray(objVal)) {\n return withCircularGuard(objVal, () => checkArray(objVal, depth));\n }\n\n return withCircularGuard(objVal, () => checkObject(objVal, depth));\n }\n\n return check(obj, 0);\n}\n\n/**\n * Shallow equality comparison for objects.\n * Used by React hooks to avoid unnecessary re-renders.\n *\n * @param a - First object\n * @param b - Second object\n * @returns True if objects are shallowly equal\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n a: T,\n b: T,\n): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (a[key] !== b[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Generate a simple hash string from an object.\n * Uses djb2 algorithm on the stable stringified value.\n *\n * **Limitations:**\n * - 32-bit hash output means collision probability increases with data set size\n * (birthday paradox: ~50% collision chance at ~77,000 distinct values)\n * - Suitable for: cache invalidation, change detection, deduplication of small sets\n * - NOT suitable for: cryptographic use, security-sensitive operations, large-scale deduplication\n *\n * For security-sensitive use cases requiring stronger collision resistance,\n * consider using a cryptographic hash like SHA-256.\n *\n * @param value - The value to hash\n * @returns A hex hash string (8 characters, 32 bits)\n */\nexport function hashObject(value: unknown): string {\n const str = stableStringify(value);\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n // Convert to unsigned 32-bit and then to hex\n return (hash >>> 0).toString(16);\n}\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\n/**\n * Distributable snapshot type for type-safe helper functions.\n */\nexport interface DistributableSnapshotLike<T = Record<string, unknown>> {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Check if a distributable snapshot has expired.\n * Returns false if the snapshot has no expiresAt field.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({ ttlSeconds: 3600 });\n * // ... later ...\n * if (isSnapshotExpired(snapshot)) {\n * // Refresh the snapshot\n * }\n * ```\n *\n * @param snapshot - The snapshot to check\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns True if the snapshot has expired, false otherwise\n */\nexport function isSnapshotExpired<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): boolean {\n return snapshot.expiresAt !== undefined && now > snapshot.expiresAt;\n}\n\n/**\n * Validate a distributable snapshot and return its data.\n * Throws if the snapshot is malformed or has expired.\n *\n * @example\n * ```typescript\n * const cached = JSON.parse(await redis.get(`entitlements:${userId}`));\n * try {\n * const data = validateSnapshot(cached);\n * // Use data.canUseFeature, etc.\n * } catch (e) {\n * // Snapshot invalid or expired, refresh it\n * }\n * ```\n *\n * @example Using custom timestamp for testing\n * ```typescript\n * const snapshot = { data: { test: true }, createdAt: 1000, expiresAt: 2000 };\n * validateSnapshot(snapshot, 1500); // Returns { test: true }\n * validateSnapshot(snapshot, 2500); // Throws: Snapshot expired\n * ```\n *\n * @param snapshot - The snapshot to validate\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns The snapshot data if valid\n * @throws Error if the snapshot is malformed or has expired\n */\nexport function validateSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): T {\n // Structural validation\n if (!snapshot || typeof snapshot !== \"object\") {\n throw new Error(\n \"[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.\",\n );\n }\n if (!(\"data\" in snapshot)) {\n throw new Error(\n \"[Directive] Invalid snapshot: missing required 'data' property.\",\n );\n }\n if (!(\"createdAt\" in snapshot) || typeof snapshot.createdAt !== \"number\") {\n throw new Error(\n \"[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).\",\n );\n }\n\n // Expiration validation\n if (isSnapshotExpired(snapshot, now)) {\n const expiredAt = new Date(snapshot.expiresAt!).toISOString();\n throw new Error(\n `[Directive] Snapshot expired at ${expiredAt}. Obtain a fresh snapshot from the source.`,\n );\n }\n return snapshot.data;\n}\n\n/**\n * Diff result for a single changed value.\n */\nexport interface SnapshotDiffEntry {\n /** The key path that changed (e.g., \"canUseApi\" or \"limits.apiCalls\") */\n path: string;\n /** The value in the old snapshot */\n oldValue: unknown;\n /** The value in the new snapshot */\n newValue: unknown;\n /** Type of change: \"added\", \"removed\", or \"changed\" */\n type: \"added\" | \"removed\" | \"changed\";\n}\n\n/**\n * Result of diffing two snapshots.\n */\nexport interface SnapshotDiff {\n /** Whether the snapshots are identical */\n identical: boolean;\n /** List of changes between snapshots */\n changes: SnapshotDiffEntry[];\n /** Whether the version changed (if both have versions) */\n versionChanged: boolean;\n /** Old version (if available) */\n oldVersion?: string;\n /** New version (if available) */\n newVersion?: string;\n}\n\n/**\n * Compare two distributable snapshots and return the differences.\n * Useful for debugging, audit logs, and webhook payloads.\n *\n * @example\n * ```typescript\n * const oldSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n * system.dispatch({ type: \"upgradePlan\", plan: \"pro\" });\n * const newSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n *\n * const diff = diffSnapshots(oldSnapshot, newSnapshot);\n * if (!diff.identical) {\n * console.log(\"Changes:\", diff.changes);\n * // [{ path: \"canUseApi\", oldValue: false, newValue: true, type: \"changed\" }]\n * }\n * ```\n *\n * @param oldSnapshot - The previous snapshot\n * @param newSnapshot - The new snapshot\n * @returns A diff result with all changes\n */\nexport function diffSnapshots<T = Record<string, unknown>>(\n oldSnapshot: DistributableSnapshotLike<T>,\n newSnapshot: DistributableSnapshotLike<T>,\n): SnapshotDiff {\n const changes: SnapshotDiffEntry[] = [];\n\n /** Push a change entry to the diff results. */\n function pushChange(\n path: string,\n oldValue: unknown,\n newValue: unknown,\n type: SnapshotDiffEntry[\"type\"],\n ): void {\n changes.push({ path, oldValue, newValue, type });\n }\n\n /** Handle null/undefined comparison cases. Returns true if fully handled. */\n function compareNullish(\n oldObj: unknown,\n newObj: unknown,\n path: string,\n ): boolean {\n if (oldObj === null || oldObj === undefined) {\n if (newObj !== null && newObj !== undefined) {\n pushChange(path, oldObj, newObj, \"added\");\n }\n\n return true;\n }\n if (newObj === null || newObj === undefined) {\n pushChange(path, oldObj, newObj, \"removed\");\n\n return true;\n }\n\n return false;\n }\n\n /** Compare two arrays element by element, recursing into each. */\n function compareArrays(\n oldArr: unknown[],\n newArr: unknown[],\n path: string,\n ): void {\n if (oldArr.length !== newArr.length) {\n pushChange(path, oldArr, newArr, \"changed\");\n\n return;\n }\n for (let i = 0; i < oldArr.length; i++) {\n compare(oldArr[i], newArr[i], `${path}[${i}]`);\n }\n }\n\n /** Compare two objects by key union, detecting added/removed/changed. */\n function compareObjects(\n oldRecord: Record<string, unknown>,\n newRecord: Record<string, unknown>,\n path: string,\n ): void {\n const allKeys = new Set([\n ...Object.keys(oldRecord),\n ...Object.keys(newRecord),\n ]);\n\n for (const key of allKeys) {\n const childPath = path ? `${path}.${key}` : key;\n if (!(key in oldRecord)) {\n pushChange(childPath, undefined, newRecord[key], \"added\");\n } else if (!(key in newRecord)) {\n pushChange(childPath, oldRecord[key], undefined, \"removed\");\n } else {\n compare(oldRecord[key], newRecord[key], childPath);\n }\n }\n }\n\n /** Recursively compare two values and record differences. */\n function compare(oldObj: unknown, newObj: unknown, path: string): void {\n if (compareNullish(oldObj, newObj, path)) {\n return;\n }\n\n // Handle primitives\n if (typeof oldObj !== \"object\" || typeof newObj !== \"object\") {\n if (!Object.is(oldObj, newObj)) {\n pushChange(path, oldObj, newObj, \"changed\");\n }\n\n return;\n }\n\n // Handle arrays\n if (Array.isArray(oldObj) && Array.isArray(newObj)) {\n compareArrays(oldObj, newObj, path);\n\n return;\n }\n\n // Handle objects\n compareObjects(\n oldObj as Record<string, unknown>,\n newObj as Record<string, unknown>,\n path,\n );\n }\n\n // Compare data\n compare(oldSnapshot.data, newSnapshot.data, \"\");\n\n // Check version change\n const versionChanged =\n oldSnapshot.version !== newSnapshot.version &&\n (oldSnapshot.version !== undefined || newSnapshot.version !== undefined);\n\n return {\n identical: changes.length === 0,\n changes,\n versionChanged,\n oldVersion: oldSnapshot.version,\n newVersion: newSnapshot.version,\n };\n}\n\n// ============================================================================\n// Snapshot Signing (HMAC)\n// ============================================================================\n\n/**\n * A signed distributable snapshot.\n * Contains the original snapshot plus a cryptographic signature.\n */\nexport interface SignedSnapshot<T = Record<string, unknown>>\n extends DistributableSnapshotLike<T> {\n /** HMAC-SHA256 signature in hex format */\n signature: string;\n /** Signing algorithm used */\n algorithm: \"hmac-sha256\";\n}\n\n/**\n * Check if a snapshot is signed.\n *\n * @param snapshot - The snapshot to check\n * @returns True if the snapshot has a signature\n */\nexport function isSignedSnapshot<T>(\n snapshot: DistributableSnapshotLike<T> | SignedSnapshot<T>,\n): snapshot is SignedSnapshot<T> {\n return \"signature\" in snapshot && typeof snapshot.signature === \"string\";\n}\n\n/**\n * Sign a distributable snapshot using HMAC-SHA256.\n * Creates a tamper-proof signature that can be verified later.\n *\n * **Security Notes:**\n * - Use a cryptographically random secret of at least 32 bytes\n * - Store the secret securely (environment variable, secrets manager)\n * - Never expose the secret to clients\n * - The signature covers all snapshot fields for integrity\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['canUseFeature', 'limits'],\n * ttlSeconds: 3600,\n * });\n *\n * // Sign the snapshot (server-side only)\n * const signed = await signSnapshot(snapshot, process.env.SNAPSHOT_SECRET);\n *\n * // Store in JWT, Redis, or send to client\n * const jwt = createJWT({ snapshot: signed });\n *\n * // Later, verify the signature\n * const isValid = await verifySnapshotSignature(signed, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Snapshot has been tampered with');\n * }\n * ```\n *\n * @param snapshot - The snapshot to sign\n * @param secret - The HMAC secret (string or Uint8Array)\n * @returns A signed snapshot with the signature attached\n */\nexport async function signSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n secret: string | Uint8Array,\n): Promise<SignedSnapshot<T>> {\n // Create a canonical representation for signing\n const payload = stableStringify({\n data: snapshot.data,\n createdAt: snapshot.createdAt,\n expiresAt: snapshot.expiresAt,\n version: snapshot.version,\n metadata: snapshot.metadata,\n });\n\n const signature = await hmacSha256(payload, secret);\n\n return {\n ...snapshot,\n signature,\n algorithm: \"hmac-sha256\",\n };\n}\n\n/**\n * Verify the signature of a signed snapshot.\n * Returns true if the signature is valid, false otherwise.\n *\n * **Important:** Always verify signatures before trusting snapshot data,\n * especially if the snapshot was received from an untrusted source (client, cache).\n *\n * The default verification enforces `expiresAt` — a captured-and-replayed\n * snapshot stops verifying once its `expiresAt` is in the past. Callers\n * that legitimately need signature-only validation (testing infrastructure,\n * archival validation) can pass `{ ignoreExpiry: true }`.\n *\n * @example\n * ```typescript\n * // Receive signed snapshot from client or cache\n * const snapshot = JSON.parse(cachedData);\n *\n * // Verify before using. `verifySnapshotSignature` returns false for an\n * // expired snapshot even when the HMAC is valid; treat it as the\n * // single attestation gate.\n * const isValid = await verifySnapshotSignature(snapshot, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Invalid or expired snapshot');\n * }\n *\n * // Now safe to use snapshot.data\n * processSnapshotData(snapshot.data);\n * ```\n *\n * @param signedSnapshot - The signed snapshot to verify\n * @param secret - The HMAC secret (must match the signing secret)\n * @param options - Optional flags:\n * - `ignoreExpiry`: skip the `expiresAt` check (signature-only mode)\n * - `now`: override the current time used for expiry comparison\n * (test helper)\n * @returns True if signature is valid AND (unless `ignoreExpiry`) not\n * expired; false otherwise\n */\nexport async function verifySnapshotSignature<T>(\n signedSnapshot: SignedSnapshot<T>,\n secret: string | Uint8Array,\n options?: { ignoreExpiry?: boolean; now?: number },\n): Promise<boolean> {\n if (!signedSnapshot.signature || signedSnapshot.algorithm !== \"hmac-sha256\") {\n return false;\n }\n\n // Recreate the canonical payload (same as signing)\n const payload = stableStringify({\n data: signedSnapshot.data,\n createdAt: signedSnapshot.createdAt,\n expiresAt: signedSnapshot.expiresAt,\n version: signedSnapshot.version,\n metadata: signedSnapshot.metadata,\n });\n\n const expectedSignature = await hmacSha256(payload, secret);\n\n // Use timing-safe comparison\n if (!timingSafeEqual(signedSnapshot.signature, expectedSignature)) {\n return false;\n }\n\n // Enforce expiresAt unless the caller explicitly opted out. Without\n // this check, a captured-and-replayed valid signature is accepted\n // forever — the canonical replay-attack chain. Treating the signature\n // as a full attestation gate requires checking the attestation window.\n if (\n !options?.ignoreExpiry &&\n isSnapshotExpired(signedSnapshot, options?.now)\n ) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create HMAC-SHA256 signature of a message.\n * Uses Web Crypto API for cross-platform support (Node.js, browsers, Deno, Bun).\n */\nasync function hmacSha256(\n message: string,\n secret: string | Uint8Array,\n): Promise<string> {\n // Convert secret to Uint8Array if string\n const secretBytes: Uint8Array =\n typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\n // Import key for HMAC\n const algorithm: HmacImportParams = {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n };\n const key = await crypto.subtle.importKey(\n \"raw\",\n secretBytes as unknown as ArrayBuffer,\n algorithm,\n false,\n [\"sign\"],\n );\n\n // Sign the message\n const messageBytes = new TextEncoder().encode(message);\n const signature = await crypto.subtle.sign(\"HMAC\", key, messageBytes);\n\n // Convert to hex string\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Timing-safe string comparison to prevent timing attacks.\n * Both strings should be the same length (hex signatures from same algorithm).\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return result === 0;\n}\n\n/**\n * Safely stringify any value for display. Handles circular references,\n * BigInt, throwing toJSON, and optional truncation.\n *\n * This is the canonical implementation – all packages should import this\n * instead of maintaining local copies.\n */\nexport function safeStringify(data: unknown, maxLen = 500): string {\n try {\n const str = JSON.stringify(\n data,\n (_key, value) => {\n if (typeof value === \"bigint\") {\n return `${value}n`;\n }\n\n return value;\n },\n 2,\n );\n if (!str) {\n return \"[undefined]\";\n }\n if (str.length <= maxLen) {\n return str;\n }\n\n return `${str.slice(0, maxLen)}\\n... (truncated, ${str.length} chars total)`;\n } catch {\n return \"[unserializable]\";\n }\n}\n"]}
|
package/dist/chunk-KGTBTGOY.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {i}from'./chunk-RBF653NR.js';import {h}from'./chunk-SFUVPP4L.js';function L(t){if(t instanceof Date)return t.getTime();if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("[Directive] audit-ledger: changedBetween bound must be a finite number, ISO string, or Date.");return t}if(typeof t=="string"){let n=Date.parse(t);if(!Number.isFinite(n))throw new Error(`[Directive] audit-ledger: changedBetween bound "${t}" is not a parseable ISO date string.`);return n}throw new Error("[Directive] audit-ledger: changedBetween bound must be a number, ISO string, or Date.")}function x(t,n){if(n.kind&&!(Array.isArray(n.kind)?n.kind:[n.kind]).includes(t.kind))return false;if(n.factPath!==void 0)if(t.kind==="fact.change"){if(t.key!==n.factPath)return false}else if(t.kind==="resolver.write.rejected"){if(t.fact!==n.factPath)return false}else return false;if(n.constraintId!==void 0&&(t.kind!=="constraint.evaluate"||t.constraintId!==n.constraintId))return false;if(n.changedBetween){let[r,a]=n.changedBetween,u=L(r),d=L(a);if(t.ts<u||t.ts>d)return false}return true}function R(t={}){let n=t.capacity??1e4,r=[],a=null;return {write(d){if(r.length>=n){let i=r[0];a?.(i.seq,1),r.shift();}for(r.push(d);r.length>n;)r.shift();},query(d){let i=d.limit??1e3,o=[];for(let c=r.length-1;c>=0;c--){let y=r[c];if(x(y,d)&&(o.push(y),o.length>=i))break}return o},recent(d){let i=Math.max(0,r.length-d);return r.slice(i)},forFact(d,i={}){return this.query({factPath:d,limit:i.limit})},forConstraint(d,i={}){return this.query({constraintId:d,limit:i.limit})},toJSON(){return {entries:r.slice(),capturedAt:Date.now()}},clear(){r=[];},destroy(){r=[],a=null;},erase(d,i){let o=0;for(let c=0;c<r.length;c++){let y=r[c];x(y,d)&&(r[c]=i(y),o++);}return o},onTruncate(d){a=d;}}}var _=Symbol("directive.audit-ledger.internal");function C(t){for(let n of Object.keys(t)){let r=t[n];if(r!==null&&typeof r=="object"){if(Array.isArray(r)&&n==="whenExplain")for(let a of r)a!==null&&typeof a=="object"&&Object.freeze(a);Object.freeze(r);}}return Object.freeze(t),t}function K(t){return h(t)}function I(t){if(t.hashAlgo==="djb2-1")return K(t);throw new Error(`[Directive] audit-ledger: unknown hashAlgo "${String(t.hashAlgo)}" on entry seq=${t.seq}. Cannot verify chain integrity. Known algorithms: "djb2-1".`)}function H(t,n,r){if(t===null||typeof t!="object")return;let a=[];for(let i of n.split(".")){if(!i)continue;let o=i.match(/^\[(\d+)\](.*)$/);if(o){a.push(Number(o[1])),o[2]&&a.push(o[2].replace(/^\./,""));continue}let c=i.match(/^([^[]+)\[(\d+)\](.*)$/);if(c){a.push(c[1]),a.push(Number(c[2])),c[3]&&a.push(c[3].replace(/^\./,""));continue}a.push(i);}let u=t;for(let i=0;i<a.length-1;i++){let o=a[i];if(u===null||typeof u!="object")return;u=u[o];}if(u===null||typeof u!="object")return;let d=a[a.length-1];d!==void 0&&(u[d]=r);}function F(t,n,r){if(n||r.size===0||t===null||typeof t!="object")return t;let a;try{a=JSON.parse(JSON.stringify(t));}catch{return t}return i(a,{operator(u,d,i,o){r.has(u)&&H(a,o,"[redacted]");},literal(u){r.has(u)&&H(a,u,"[redacted]");}}),a}var D="djb2-1";function N(t,n){if(n?.strong===true)throw new Error("[Directive] verify({ strong: true }) is reserved for v2 \u2014 v1 ships sync djb2 chain only. Use verify() (sync) for tamper detection.");let{entries:r}=t.toJSON();if(r.length===0)return {valid:true,entryCount:0};let a=new Set,u=null;for(let i=0;i<r.length;i++){let o=r[i];if(o.prevHash!==u){let c=i>0?r[i-1]:null,y=o.kind==="system.entry-erased",h=c?.kind==="system.entry-erased";if(y||h){let A=[];y&&A.push(o),h&&c!==null&&A.push(c);let b=A.find(v=>v.__internal!==_);if(b)return {valid:false,brokenAt:i,expectedHash:u??"<genesis>",actualHash:o.prevHash??"<genesis>",entry:b,reason:"tombstone forgery detected \u2014 missing internal sentinel. A 'system.entry-erased' entry was written via sink.write() rather than ledger.erase(); rejected as tamper."};let E=y?o:c;a.add(E.seq),u=I(o);continue}return {valid:false,brokenAt:i,expectedHash:u??"<genesis>",actualHash:o.prevHash??"<genesis>",entry:o}}u=I(o);}let d={valid:true,entryCount:r.length};return a.size>0&&(d.erasedSeqs=[...a].sort((i,o)=>i-o)),d}function ie(t={}){let n=t.sink??R(),r=t.capturePII??false,a=t.redact,u=0,d=null,i=null,o=null,c=new Map,y=new Map,h$1=new Set;function A(){if(c.clear(),y.clear(),!!i)try{let e=i.inspect;if(typeof e!="function")return;let l=e()?.constraints??[],f=i.$internal?.mergedConstraints;for(let m of l)if(m.whenSpec!==void 0)c.set(m.id,F(m.whenSpec,r,h$1));else {let g=f?.[m.id],S=g&&typeof g.when=="function"?g.when:void 0;S?y.set(m.id,h(String(S))):m.when!==void 0&&typeof m.when=="function"?y.set(m.id,h(String(m.when))):y.set(m.id,h("[function]"));}}catch{}}function b(){if(h$1.clear(),!(r||!i))try{let e=i.meta;if(!e||typeof e.byTag!="function")return;let s=e.byTag("pii")??[];for(let l of s)h$1.add(l.id);}catch{}}function E(e,s){return r?s:h$1.has(e)?"[redacted]":s}function v(e){if(!e||r||h$1.size===0)return e;let s=false,l=e.map(f=>{if(h$1.has(f.path))return s=true,{...f,actual:"[redacted]"};if(f.children){let m=v(f.children);if(m!==f.children)return s=true,{...f,children:m}}return f});return s?l:e}function p(e){let s={...e,seq:u++,ts:Date.now(),prevHash:d,hashAlgo:D,schemaVersion:1},l=a?a(s):s;return C(l),n.write(l),d=I(l),l}function P(e){switch(e.type){case "constraint.evaluate":{let s=c.get(e.id),l=y.get(e.id),f={kind:"constraint.evaluate",constraintId:e.id,active:e.active,whenExplain:v(e.whenExplain)};s!==void 0?f.whenSpec=s:l!==void 0&&(f.whenSource={kind:"function",sourceHash:l}),p(f);break}case "fact.change":p({kind:"fact.change",key:e.key,prior:E(e.key,e.prev),next:E(e.key,e.next)});break;case "resolver.write.rejected":e.kind==="summary"?p({kind:"resolver.write.rejected",rejection:"summary",resolverId:e.resolver,requirementId:e.requirementId,reason:e.reason,dropped:e.dropped}):p({kind:"resolver.write.rejected",rejection:"rejection",resolverId:e.resolver,requirementId:e.requirementId,reason:e.reason,fact:e.fact,expected:E(e.fact,e.expected),actual:E(e.fact,e.actual)});break;case "resolver.complete":p({kind:"resolver.complete",resolverId:e.resolver,requirementId:e.requirementId,duration:e.duration});break;case "resolver.error":p({kind:"resolver.error",resolverId:e.resolver,requirementId:e.requirementId,error:String(e.error)});break;case "system.init":case "system.start":case "system.stop":case "system.destroy":p({kind:e.type});break;case "source.attach":case "source.detach":p({kind:e.type,sourceId:e.id,moduleId:e.moduleId});break;case "source.error":p({kind:"source.error",sourceId:e.id,moduleId:e.moduleId,phase:e.phase,error:e.error instanceof Error?e.error.message:String(e.error)});break;}}let j=false;function T(e){i=e,b(),A(),o=e.observe(P),n.onTruncate?.((s,l)=>{if(!j){j=true;try{p({kind:"system.truncated",droppedSeq:s,droppedCount:l});}finally{j=false;}}});}function q(){o&&(o(),o=null),i=null,c.clear(),y.clear(),h$1.clear();}let M={name:"audit-ledger",onInit(e){T(e);},onStop(){o&&(o(),o=null);},onDestroy(){q();},onDefinitionRegister(e,s){e==="constraint"&&A(),(e==="constraint"||e==="resolver"||e==="effect")&&b();},onDefinitionAssign(e,s){e==="constraint"&&A();},onDefinitionUnregister(e,s){e==="constraint"&&A();},onSnapshot(e){p({kind:"system.snapshot",snapshotId:e.id,trigger:e.trigger});},onHistoryNavigate(e,s){p({kind:"system.history.navigate",from:e,to:s});}};function V(e){if(e.__internal===void 0)return e;let s={...e};return delete s.__internal,s}function w(e){let s=false;for(let l of e)if(l.__internal!==void 0){s=true;break}return s?e.map(V):e}return {plugin:M,query:(e={})=>w(n.query(e)),recent:e=>w(n.recent(e)),forFact:(e,s)=>w(n.forFact(e,s)),forConstraint:(e,s)=>w(n.forConstraint(e,s)),toJSON:()=>{let e=n.toJSON();return {entries:w(e.entries),capturedAt:e.capturedAt}},verify(e){return N(n,e)},erase(e){let s=Date.now(),l=0;if(typeof n.erase=="function"&&(l=n.erase(e,g=>{let S={seq:g.seq,ts:g.ts,kind:"system.entry-erased",prevHash:g.prevHash,hashAlgo:g.hashAlgo,schemaVersion:g.schemaVersion??1,originalKind:g.kind,erasedAt:s,__internal:_};return C(S),S})),l===0)return {erased:0,markerEntry:null};let f={factPath:e.factPath!==void 0,constraintId:e.constraintId!==void 0,kind:e.kind,changedBetween:e.changedBetween!==void 0?"[range]":void 0},m=p({kind:"system.subject-erased",filterHash:h(e),filterShape:f,erased:l});return {erased:l,markerEntry:m}},clear(){n.clear(),u=0,d=null;},destroy(){q(),n.destroy();}}}export{R as a,ie as b};//# sourceMappingURL=chunk-KGTBTGOY.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-KGTBTGOY.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugins/audit-ledger/sink.ts","../src/plugins/audit-ledger/hash.ts","../src/plugins/audit-ledger/predicate-redact.ts","../src/plugins/audit-ledger/types.ts","../src/plugins/audit-ledger/verify.ts","../src/plugins/audit-ledger/index.ts"],"names":["parseRangeBound","v","t","matchesFilter","entry","filter","a","b","start","end","memorySink","opts","capacity","entries","truncateHandler","dropped","limit","out","i","e","n","path","opts2","id","tombstoneFactory","count","handler","LEDGER_INTERNAL_TOKEN","freezeEntry","key","clause","syncHash","hashObject","hashForEntry","replaceAtPath","root","dottedPath","value","segs","part","m","m2","cur","seg","lastSeg","redactWhenSpec","spec","capturePII","piiTaggedFacts","cloned","walkPredicate","factPath","op","_operand","operandPath","HASH_ALGO","verify","sink","erasedSeqsSet","prevHash","prevEntry","entryIsTombstone","prevIsTombstone","candidates","forged","tombstoneEntry","result","createAuditLedger","userRedact","seq","lastHashCache","system","unobserve","whenSpecCache","whenSourceCache","refreshWhenSpecCache","inspect","constraints","mergedDefs","c","def","whenFn","refreshPIITags","meta","tagged","redactValue","redactClauses","clauses","mutated","inner","emit","partial","finalEntry","onEvent","event","whenSpec","whenSourceHash","emittingTruncate","attach","sys","droppedSeq","droppedCount","detach","plugin","type","snapshot","from","to","stripInternal","clone","stripInternalAll","needsClone","snap","erasedAt","tombstone","filterShape","markerEntry"],"mappings":"wEAiBA,SAASA,CAAAA,CAAgBC,CAAAA,CAAmC,CAC1D,GAAIA,CAAAA,YAAa,KAAM,OAAOA,CAAAA,CAAE,OAAA,EAAQ,CACxC,GAAI,OAAOA,GAAM,QAAA,CAAU,CACzB,GAAI,CAAC,MAAA,CAAO,QAAA,CAASA,CAAC,CAAA,CACpB,MAAM,IAAI,KAAA,CACR,8FACF,CAAA,CAGF,OAAOA,CACT,CACA,GAAI,OAAOA,CAAAA,EAAM,QAAA,CAAU,CACzB,IAAMC,CAAAA,CAAI,IAAA,CAAK,KAAA,CAAMD,CAAC,CAAA,CACtB,GAAI,CAAC,MAAA,CAAO,QAAA,CAASC,CAAC,CAAA,CACpB,MAAM,IAAI,KAAA,CACR,CAAA,gDAAA,EAAmDD,CAAC,CAAA,qCAAA,CACtD,CAAA,CAGF,OAAOC,CACT,CACA,MAAM,IAAI,KAAA,CACR,uFACF,CACF,CAEO,SAASC,EAAcC,CAAAA,CAAmBC,CAAAA,CAA8B,CAC7E,GAAIA,CAAAA,CAAO,I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AGM+G,CAAAA,CAAc1B,CAAAA,CAAK,CACvB,IAAA,CAAM,uBAAA,CACN,UAAA,CAAY1D,CAAAA,CAAW3B,CAAM,CAAA,CAC7B,WAAA,CAAA8G,CAAAA,CACA,MAAA,CAAQ1F,CACV,CAAC,CAAA,CAED,OAAO,CAAE,MAAA,CAAQA,CAAAA,CAAO,WAAA,CAAA2F,CAAY,CACtC,CAAA,CACA,KAAA,EAAQ,CACN3D,CAAAA,CAAK,KAAA,EAAM,CACXY,EAAM,CAAA,CACNC,CAAAA,CAAgB,KAClB,CAAA,CACA,OAAA,EAAU,CACRgC,CAAAA,EAAO,CACP7C,CAAAA,CAAK,OAAA,GACP,CACF,CACF","file":"chunk-KGTBTGOY.js","sourcesContent":["/**\n * `memorySink()` — bounded ring-buffer implementation of\n * `AuditLedgerSink`. Drops the oldest entry past `capacity`\n * (default 10,000), exposes a truncation hook so the ledger plugin\n * can emit a `system.truncated` marker before the shift, and\n * supports in-place tombstone erasure for GDPR Art. 17.\n *\n * Pure storage layer — no hash chain awareness, no PII redaction.\n * The plugin in `./index.ts` owns those concerns and routes them\n * through this sink via `write()` / `erase()`.\n */\n\nimport type { AuditEntry, AuditLedgerSink, QueryFilter } from \"./types.js\";\n\nconst DEFAULT_MEMORY_CAPACITY = 10_000;\nconst DEFAULT_QUERY_LIMIT = 1000;\n\nfunction parseRangeBound(v: string | number | Date): number {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"number\") {\n if (!Number.isFinite(v)) {\n throw new Error(\n \"[Directive] audit-ledger: changedBetween bound must be a finite number, ISO string, or Date.\",\n );\n }\n\n return v;\n }\n if (typeof v === \"string\") {\n const t = Date.parse(v);\n if (!Number.isFinite(t)) {\n throw new Error(\n `[Directive] audit-ledger: changedBetween bound \"${v}\" is not a parseable ISO date string.`,\n );\n }\n\n return t;\n }\n throw new Error(\n \"[Directive] audit-ledger: changedBetween bound must be a number, ISO string, or Date.\",\n );\n}\n\nexport function matchesFilter(entry: AuditEntry, filter: QueryFilter): boolean {\n if (filter.kind) {\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n if (!kinds.includes(entry.kind)) return false;\n }\n if (filter.factPath !== undefined) {\n // Exact match — no LIKE wildcards. (SEC M2)\n if (entry.kind === \"fact.change\") {\n if (entry.key !== filter.factPath) return false;\n } else if (entry.kind === \"resolver.write.rejected\") {\n if (entry.fact !== filter.factPath) return false;\n } else {\n return false;\n }\n }\n if (filter.constraintId !== undefined) {\n if (entry.kind !== \"constraint.evaluate\") return false;\n if (entry.constraintId !== filter.constraintId) return false;\n }\n if (filter.changedBetween) {\n const [a, b] = filter.changedBetween;\n const start = parseRangeBound(a);\n const end = parseRangeBound(b);\n if (entry.ts < start || entry.ts > end) return false;\n }\n\n return true;\n}\n\n/**\n * In-memory bounded ring-buffer sink. Drops oldest entries past\n * `capacity` (default 10,000). Use this as the default sink for dev,\n * tests, and StackBlitz demos.\n */\nexport function memorySink(opts: { capacity?: number } = {}): AuditLedgerSink {\n const capacity = opts.capacity ?? DEFAULT_MEMORY_CAPACITY;\n let entries: AuditEntry[] = [];\n let truncateHandler:\n | ((droppedSeq: number, droppedCount: number) => void)\n | null = null;\n\n const sink: AuditLedgerSink = {\n write(entry) {\n if (entries.length >= capacity) {\n // (M23) About to overflow — notify the owner BEFORE the shift\n // so the dropped seq is still known. The handler may push an\n // entry of its own (a truncation marker), which will itself\n // push us over capacity; we shift one for one until we're back\n // at capacity (handlers must be O(1) writers — typically one).\n const dropped = entries[0]!;\n truncateHandler?.(dropped.seq, 1);\n entries.shift();\n }\n entries.push(entry);\n // If the handler wrote a marker (entries.length now > capacity),\n // drop one more from the head to keep us at capacity exactly.\n while (entries.length > capacity) {\n entries.shift();\n }\n },\n query(filter) {\n const limit = filter.limit ?? DEFAULT_QUERY_LIMIT;\n const out: AuditEntry[] = [];\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i]!;\n if (matchesFilter(e, filter)) {\n out.push(e);\n if (out.length >= limit) break;\n }\n }\n\n return out;\n },\n recent(n) {\n const start = Math.max(0, entries.length - n);\n\n return entries.slice(start);\n },\n forFact(path, opts2 = {}) {\n return this.query({ factPath: path, limit: opts2.limit });\n },\n forConstraint(id, opts2 = {}) {\n return this.query({ constraintId: id, limit: opts2.limit });\n },\n toJSON() {\n return { entries: entries.slice(), capturedAt: Date.now() };\n },\n clear() {\n entries = [];\n },\n destroy() {\n entries = [];\n truncateHandler = null;\n },\n erase(filter, tombstoneFactory) {\n let count = 0;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!;\n if (matchesFilter(e, filter)) {\n entries[i] = tombstoneFactory(e);\n count++;\n }\n }\n\n return count;\n },\n onTruncate(handler) {\n truncateHandler = handler;\n },\n };\n\n return sink;\n}\n","/**\n * Hash chain primitives — canonicalization, djb2 dispatch, depth-2\n * freeze, and the in-module tombstone sentinel.\n *\n * `LEDGER_INTERNAL_TOKEN` is the heart of the tombstone-forgery defense\n * (N7). It MUST live in this single file and MUST NOT be re-exported\n * from the folder's public surface (`./index.ts`). The only external\n * surface that touches it is `verify()` and the tombstone factory in\n * `index.ts`, both of which import it directly from this module.\n *\n * Hash chain: each entry stores `prevHash` — the djb2 (`hashObject`)\n * hash of the previous entry's stable-stringified payload. Tampering\n * with any entry's payload breaks the next entry's `prevHash` link —\n * visible in `verify()`. v1 ships sync djb2 only; `verify({ strong: true })`\n * is reserved for v2 (SHA-256) and throws today.\n */\n\nimport { hashObject } from \"../../utils/utils.js\";\nimport type { AuditEntry } from \"./types.js\";\n\n/**\n * Private sentinel stamped onto tombstone entries by {@link createAuditLedger.erase}.\n * Never exported from the folder's barrel, never serialized — `verify()`\n * checks for it before accepting a `system.entry-erased` entry as a\n * legitimate chain break.\n *\n * (N7) Without this, a caller holding a raw `AuditLedgerSink` reference\n * could write `{ kind: \"system.entry-erased\", … }` directly into the\n * sink to mask real tampering as legitimate erasure. The sentinel\n * raises the bar so only the in-process ledger plugin (which lives in\n * this folder's closure) can mint a valid tombstone.\n *\n * @internal — DO NOT re-export from `./index.ts` or `./types.ts`.\n */\nexport const LEDGER_INTERNAL_TOKEN: unique symbol = Symbol(\n \"directive.audit-ledger.internal\",\n);\n\n/**\n * Depth-2 freeze: freeze the entry, freeze each top-level value, and\n * freeze each clause in `whenExplain`. Cycle-safe + cheap; prevents\n * in-process payload mutation that would forge the chain. (C3)\n */\nexport function freezeEntry(entry: AuditEntry): AuditEntry {\n for (const key of Object.keys(entry)) {\n const v = (entry as unknown as Record<string, unknown>)[key];\n if (v !== null && typeof v === \"object\") {\n if (Array.isArray(v) && key === \"whenExplain\") {\n for (const clause of v) {\n if (clause !== null && typeof clause === \"object\") {\n Object.freeze(clause);\n }\n }\n }\n Object.freeze(v);\n }\n }\n Object.freeze(entry);\n\n return entry;\n}\n\n// ============================================================================\n// Hash chain — canonicalization\n// ============================================================================\n//\n// `syncHash(entry)` calls `hashObject(entry)` which calls\n// `stableStringify(entry)` — every entry shape (seq, ts, kind, prevHash,\n// hashAlgo, ...payload) is canonicalized via key-sorted JSON, then\n// djb2-hashed to a 32-bit hex string.\n//\n// - Fast, sync, isomorphic Node/Bun/Deno/browser.\n// - Tamper-DETECTION against accidental + light adversarial probing.\n// - Collision-prone against a determined attacker, by design (32 bits).\n//\n// Any future change to the canonicalization or hash function breaks\n// existing exports, so each entry carries `hashAlgo: \"djb2-1\"`. Verifiers\n// must check that tag matches what they expect.\n//\n// `verify({ strong: true })` is reserved for v2 (SHA-256 chain via Web\n// Crypto). It throws today — there is no silent fallback. v1 ships sync\n// djb2 only.\n\nfunction syncHash(entry: AuditEntry): string {\n // stableStringify guarantees same hash across runtimes regardless of\n // key insertion order (architecture review #11, security review C1).\n return hashObject(entry);\n}\n\n/**\n * Dispatch to the right hash function based on the entry's `hashAlgo`\n * discriminator. v1 has a single arm (`djb2-1`); the switch is in\n * place so v2 can add `\"sha256-1\"` without touching call sites. (N5)\n *\n * v2 promise: when SHA-256 lands, this becomes `case \"sha256-1\": return\n * await asyncSha256(entry);` — verify() will become async accordingly.\n */\nexport function hashForEntry(entry: AuditEntry): string {\n switch (entry.hashAlgo) {\n case \"djb2-1\":\n return syncHash(entry);\n default:\n throw new Error(\n `[Directive] audit-ledger: unknown hashAlgo \"${String((entry as { hashAlgo: unknown }).hashAlgo)}\" on entry seq=${entry.seq}. Cannot verify chain integrity. Known algorithms: \"djb2-1\".`,\n );\n }\n}\n","/**\n * PII operand redaction for cached predicate specs.\n *\n * Cached `whenSpec` operand pointers (e.g. `{ email: { $eq:\n * \"alice@x.com\" } }`) flow into every `constraint.evaluate` entry —\n * without scrubbing, the email would land in the audit trail in\n * plaintext on every evaluation. (C2)\n *\n * `redactWhenSpec` deep-clones the spec, walks it via `walkPredicate`,\n * and replaces operand values at PII-tagged fact paths with\n * `\"[redacted]\"`. Best-effort: if the spec contains anything\n * non-JSON-serialisable, we return the original (the caller has\n * already snapshotted the reference).\n */\n\nimport { walkPredicate } from \"../../core/predicate.js\";\n\n/**\n * Navigate `root` to `dottedPath` (`foo.bar.$eq`, `foo[0].value`) and\n * replace the value at the leaf. Used by `redactWhenSpec` to scrub\n * PII operands in cached predicate specs. Best-effort: silently no-ops\n * if the path doesn't resolve (caller already cloned the spec).\n */\nfunction replaceAtPath(\n root: unknown,\n dottedPath: string,\n value: unknown,\n): void {\n if (root === null || typeof root !== \"object\") return;\n // Split on \".\" but treat \"[N]\" segments as array indices.\n // E.g. \"[0].value\" → [\"[0]\", \"value\"], \"foo.bar[1]\" → [\"foo\", \"bar[1]\"].\n const segs: Array<string | number> = [];\n for (const part of dottedPath.split(\".\")) {\n if (!part) continue;\n // Pull leading `[N]` if present.\n const m = part.match(/^\\[(\\d+)\\](.*)$/);\n if (m) {\n segs.push(Number(m[1]));\n if (m[2]) segs.push(m[2].replace(/^\\./, \"\"));\n continue;\n }\n // Trailing `[N]` on the segment.\n const m2 = part.match(/^([^[]+)\\[(\\d+)\\](.*)$/);\n if (m2) {\n segs.push(m2[1]!);\n segs.push(Number(m2[2]));\n if (m2[3]) segs.push(m2[3].replace(/^\\./, \"\"));\n continue;\n }\n segs.push(part);\n }\n\n let cur: unknown = root;\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n if (cur === null || typeof cur !== \"object\") return;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n if (cur === null || typeof cur !== \"object\") return;\n const lastSeg = segs[segs.length - 1];\n if (lastSeg === undefined) return;\n (cur as Record<string | number, unknown>)[lastSeg] = value;\n}\n\n/**\n * Walk a predicate spec and replace operands at PII-tagged fact paths\n * with `\"[redacted]\"`. Returns the input as-is when redaction is\n * disabled (`capturePII: true`) or no PII tags are registered;\n * otherwise returns a deep clone with the leaf values rewritten. (C2)\n */\nexport function redactWhenSpec(\n spec: unknown,\n capturePII: boolean,\n piiTaggedFacts: ReadonlySet<string>,\n): unknown {\n if (capturePII || piiTaggedFacts.size === 0) return spec;\n if (spec === null || typeof spec !== \"object\") return spec;\n\n // Deep-clone so we don't mutate the user's source predicate. JSON\n // round-trip handles plain objects + arrays cheaply; predicates are\n // already JSON-safe (validatePredicate enforces this).\n let cloned: unknown;\n try {\n cloned = JSON.parse(JSON.stringify(spec));\n } catch {\n // Spec contained something non-serializable; bail rather than crash.\n return spec;\n }\n\n walkPredicate(cloned, {\n operator(factPath, op, _operand, operandPath) {\n if (!piiTaggedFacts.has(factPath)) return;\n // Navigate cloned tree to operandPath and replace value.\n replaceAtPath(cloned, operandPath, \"[redacted]\");\n void op;\n },\n literal(factPath) {\n if (!piiTaggedFacts.has(factPath)) return;\n // Replace bare-value leaf at this factPath.\n replaceAtPath(cloned, factPath, \"[redacted]\");\n },\n });\n\n return cloned;\n}\n","/**\n * Audit-ledger type definitions — entry shapes, sink interface, query\n * filter, verify result, and plugin options. Pure types + the two\n * schema-version constants (`HASH_ALGO`, `SCHEMA_VERSION`) that are\n * referenced by the entry shape.\n *\n * Kept free of runtime imports so the hash/freeze/sink modules can pull\n * types from here without a cycle.\n */\n\nimport type { ModuleSchema, Plugin } from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.js\";\n\n// ============================================================================\n// Version stamps\n// ============================================================================\n\n/** Hash algorithm tag — bumped if canonicalization or hash function changes. */\nexport const HASH_ALGO = \"djb2-1\" as const;\n\n/**\n * Entry schema version. Bumped if `AuditEntry` field shape changes in\n * a way that breaks back-compat parsers. Persisted on every entry so\n * exports remain self-describing across library upgrades. (F-5)\n */\nexport const SCHEMA_VERSION = 1 as const;\n\n// ============================================================================\n// AuditEntry types\n// ============================================================================\n\nexport type AuditEntryKind =\n | \"constraint.evaluate\"\n | \"resolver.write.rejected\"\n | \"fact.change\"\n | \"resolver.complete\"\n | \"resolver.error\"\n | \"source.attach\"\n | \"source.detach\"\n | \"source.error\"\n | \"system.init\"\n | \"system.start\"\n | \"system.stop\"\n | \"system.destroy\"\n | \"system.snapshot\"\n | \"system.history.navigate\"\n | \"system.truncated\"\n | \"system.entry-erased\"\n | \"system.subject-erased\";\n\n/**\n * Internal sentinel symbol type. The actual symbol VALUE lives in\n * `hash.ts` and is never exported from this folder's public surface —\n * but the TYPE must be referenceable here so `AuditEntryBase` can\n * declare the optional `__internal` field.\n *\n * We use `symbol` rather than `typeof LEDGER_INTERNAL_TOKEN` because\n * importing the symbol value into types.ts would either re-export it\n * (defeating the defense) or create a circular import. The runtime\n * check in `verify()` compares against the actual symbol reference.\n */\ntype LedgerInternalSentinel = symbol;\n\ninterface AuditEntryBase {\n /** Monotonic sequence number, starting at 0. */\n readonly seq: number;\n /** Wall-clock timestamp (ms epoch). */\n readonly ts: number;\n /** Discriminator. */\n readonly kind: AuditEntryKind;\n /** Hash of the previous entry's full payload. null on the genesis entry. */\n readonly prevHash: string | null;\n /**\n * Hash algorithm tag identifying the canonicalization + hash\n * function in use. Bumped if the algorithm or canonical form\n * changes, so exports remain verifiable across versions.\n */\n readonly hashAlgo: typeof HASH_ALGO;\n /**\n * Entry schema version — bumped if any `AuditEntry` field shape\n * changes in a way that breaks back-compat. Pair with `hashAlgo`\n * when migrating older exports. (F-5)\n */\n readonly schemaVersion: typeof SCHEMA_VERSION;\n /**\n * Private sentinel — present (and equal to the in-module token) only\n * on legitimate tombstones minted by `ledger.erase()`. Filtered out\n * of all public read paths (`query`, `recent`, `toJSON`, etc.) so\n * consumers never see or copy it. (N7)\n *\n * NOT serialized. NOT exported. Forging this from outside the module\n * is impossible without the symbol reference; `verify()` rejects any\n * `system.entry-erased` entry that lacks it.\n *\n * @internal\n */\n readonly __internal?: LedgerInternalSentinel;\n}\n\nexport type AuditEntry =\n | (AuditEntryBase & {\n kind: \"constraint.evaluate\";\n constraintId: string;\n active: boolean;\n /** Cached at ledger start from `system.inspect().constraints[].whenSpec`. Refreshed on `register()`/`assign()`/`unregister()`. May be undefined for function-form constraints (see `whenSource`). PII operands redacted unless `capturePII: true`. */\n whenSpec?: FactPredicate<unknown>;\n whenExplain?: readonly ClauseResult[];\n /**\n * For function-form constraints (no `whenSpec`), a tamper-evident\n * identity for the function. We DO NOT capture the raw source —\n * closures routinely reference secrets, API keys, or PII (e.g.\n * `if (apiKey === \"sk-live-xxx\")`) and a preview would leak them\n * into the audit log. Instead, we capture a djb2 hash of the\n * stringified function (`hashObject(String(fn))`). Auditors can\n * detect \"the function changed between deploys\" by comparing\n * hashes across entries, without ever seeing the function body.\n *\n * Informational only — NOT replayable. (N5, M22)\n */\n whenSource?: { kind: \"function\"; sourceHash: string };\n })\n | (AuditEntryBase & {\n kind: \"resolver.write.rejected\";\n rejection: \"rejection\" | \"summary\";\n resolverId: string;\n requirementId: string;\n reason: string;\n fact?: string;\n expected?: unknown;\n actual?: unknown;\n dropped?: number;\n })\n | (AuditEntryBase & {\n kind: \"fact.change\";\n key: string;\n prior: unknown;\n next: unknown;\n })\n | (AuditEntryBase & {\n kind: \"resolver.complete\";\n resolverId: string;\n requirementId: string;\n duration: number;\n })\n | (AuditEntryBase & {\n kind: \"resolver.error\";\n resolverId: string;\n requirementId: string;\n error: string;\n })\n | (AuditEntryBase & {\n kind: \"source.attach\" | \"source.detach\";\n sourceId: string;\n moduleId: string;\n })\n | (AuditEntryBase & {\n kind: \"source.error\";\n sourceId: string;\n moduleId: string;\n /**\n * `phase: \"runtime\"` (RFC 0008) flags errors the source reported\n * mid-flight via the `reportError` callback `attach` receives as\n * its second argument — distinct from lifecycle `\"attach\"` /\n * `\"cleanup\"` failures.\n */\n phase: \"attach\" | \"cleanup\" | \"runtime\";\n /**\n * Truncated error message — capped at a fixed length by the source\n * manager before it reaches the ledger. Source authors who embed\n * payloads in error messages get a bounded leak surface rather than\n * an unbounded one. Pair with the matching `source.attach` /\n * `source.detach` entries for full lifecycle context.\n */\n error: string;\n })\n | (AuditEntryBase & {\n kind: \"system.init\" | \"system.start\" | \"system.stop\" | \"system.destroy\";\n })\n | (AuditEntryBase & {\n kind: \"system.snapshot\";\n snapshotId: number;\n trigger: string;\n })\n | (AuditEntryBase & {\n kind: \"system.history.navigate\";\n from: number;\n to: number;\n })\n | (AuditEntryBase & {\n kind: \"system.truncated\";\n droppedSeq: number;\n droppedCount: number;\n })\n | (AuditEntryBase & {\n kind: \"system.entry-erased\";\n originalKind: AuditEntryKind;\n erasedAt: number;\n })\n | (AuditEntryBase & {\n kind: \"system.subject-erased\";\n /**\n * djb2 hash of the filter (via `hashObject(filter)`). PII-safe —\n * the raw filter values never land in the ledger. Pair with\n * `filterShape` to see which filter fields were used. (N2)\n */\n filterHash: string;\n /**\n * Stripped-values shape of the filter — captures WHICH fields were\n * present without recording their values. (N2)\n */\n filterShape: {\n factPath: boolean;\n constraintId: boolean;\n kind: AuditEntryKind | readonly AuditEntryKind[] | undefined;\n changedBetween: \"[range]\" | undefined;\n };\n erased: number;\n });\n\n// ============================================================================\n// Sink interface\n// ============================================================================\n\nexport interface QueryFilter {\n /** Exact-match fact path. */\n factPath?: string;\n /** Filter by constraint id. */\n constraintId?: string;\n /** Filter by entry kind. */\n kind?: AuditEntryKind | readonly AuditEntryKind[];\n /** Time range as `[startMs, endMs]`, ISO strings, or epoch numbers. */\n changedBetween?: [string | number | Date, string | number | Date];\n /** Maximum entries returned. Default 1000. */\n limit?: number;\n}\n\n/**\n * Verify result — chain valid OR a break with full context for tamper visualization.\n *\n * Erased entries (via `ledger.erase()`) appear as legitimate chain breaks —\n * `verify()` reports them in `erasedSeqs` and continues the walk from the\n * tombstone's own hash. Real tamper still surfaces as `valid: false`.\n *\n * Forged tombstones (a caller writes `kind: \"system.entry-erased\"`\n * directly via `sink.write()` to mask tamper as erasure) are detected:\n * legitimate tombstones carry an in-module sentinel that forgeries\n * cannot mint, so `verify()` reports them as tamper. (N7)\n */\nexport type VerifyResult =\n | {\n valid: true;\n entryCount: number;\n /**\n * Seq numbers of entries legitimately broken by `erase()`\n * tombstones. NOT timestamps — each entry pairs this seq with\n * the per-entry `system.entry-erased.erasedAt` (ms epoch) for\n * the timestamp. Empty unless the chain contains erasures.\n * (N1 + M1; renamed from `erasedAt` in R3)\n */\n erasedSeqs?: number[];\n }\n | {\n valid: false;\n brokenAt: number;\n expectedHash: string;\n actualHash: string;\n entry: AuditEntry;\n /**\n * Human-readable reason for the break — populated for cases\n * where the cause is more specific than \"hash mismatch\" (e.g.\n * tombstone forgery detected via missing sentinel).\n */\n reason?: string;\n };\n\nexport interface AuditLedgerSink {\n write(entry: AuditEntry): void;\n query(filter: QueryFilter): readonly AuditEntry[];\n recent(n: number): readonly AuditEntry[];\n forFact(path: string, opts?: { limit?: number }): readonly AuditEntry[];\n forConstraint(id: string, opts?: { limit?: number }): readonly AuditEntry[];\n toJSON(): { entries: readonly AuditEntry[]; capturedAt: number };\n clear(): void;\n destroy(): void;\n /**\n * Replace matching entries with marker entries IN PLACE (preserving seq +\n * prevHash so the hash chain still verifies — the marker is a\n * tombstone in chain terms; the chain break is what makes erasure\n * visible to `verify()`). v1 implementation matches on the same\n * `QueryFilter` shape used by `query()`. Returns the count of entries\n * replaced.\n *\n * WARNING: erases only from this sink. Any external copies (toJSON\n * exports, downstream pipelines) must be erased separately.\n */\n erase?(\n filter: QueryFilter,\n markerEntryFactory: (e: AuditEntry) => AuditEntry,\n ): number;\n /**\n * Optional hook fired by the sink BEFORE shifting the oldest entry\n * out of a bounded ring buffer. The ledger plugin uses this to emit\n * a `system.truncated` marker so an auditor sees that the log was\n * truncated and where. (M23)\n */\n onTruncate?(\n handler: (droppedSeq: number, droppedCount: number) => void,\n ): void;\n}\n\n// ============================================================================\n// Plugin options + public API surface\n// ============================================================================\n\nexport interface AuditLedgerOptions {\n /** Sink to write entries to. Default: in-memory ring buffer (capacity 10k). */\n sink?: AuditLedgerSink;\n /**\n * Whether to capture raw fact values (`prior`/`next` on fact.change,\n * `actual` in whenExplain). Default `false` — PII-tagged facts are\n * redacted by default. Set `true` to opt out of redaction.\n */\n capturePII?: boolean;\n /**\n * Optional caller-supplied redactor. Runs AFTER the default\n * pii-tag-based redaction. Useful for additional sanitization.\n */\n redact?: (entry: AuditEntry) => AuditEntry;\n}\n\nexport interface AuditLedger {\n /** The plugin to pass to `createSystem({ plugins: [...] })`. */\n readonly plugin: Plugin<ModuleSchema>;\n /** Query entries matching the filter. */\n query(filter?: QueryFilter): readonly AuditEntry[];\n /** Most recent N entries (chronological). */\n recent(n: number): readonly AuditEntry[];\n /** All entries that touch this fact path (exact match). */\n forFact(path: string, opts?: { limit?: number }): readonly AuditEntry[];\n /** All entries for this constraint id. */\n forConstraint(id: string, opts?: { limit?: number }): readonly AuditEntry[];\n /** Full ledger snapshot for export / serialization. */\n toJSON(): { entries: readonly AuditEntry[]; capturedAt: number };\n /**\n * Walk the hash chain genesis → tip. Returns `{ valid: true }` iff\n * every entry's `prevHash` matches the (sync, djb2-based) hash of\n * the previous entry. On break, returns the index of the first\n * broken link plus the expected vs actual hashes — feed into a\n * \"TAMPERED\" visualization.\n *\n * Erased entries (via `ledger.erase()`) appear as legitimate chain\n * breaks — `verify()` reports them in `erasedSeqs` and continues\n * the walk from the tombstone's actual hash. Real tamper still\n * surfaces as `valid: false`. (N1 + M1)\n *\n * Forged tombstones — `kind: \"system.entry-erased\"` entries written\n * directly via `sink.write()` to mask tamper — are detected as\n * forgery. Legitimate tombstones carry an in-module sentinel that\n * forgeries cannot mint. (N7)\n *\n * v1 ships sync djb2 only. `verify({ strong: true })` is reserved\n * for v2 (SHA-256) and THROWS today — there is no silent fallback.\n * Call `verify()` (no args) for tamper detection.\n */\n verify(opts?: { strong?: boolean }): VerifyResult;\n /**\n * Per-subject erasure (GDPR Art. 17 stub). Replaces matching entries\n * in this sink with `system.entry-erased` tombstones (preserving\n * seq + prevHash so verify() can resync), then appends a chained\n * `system.subject-erased` marker entry that summarises the erasure.\n *\n * Returns `{ erased, markerEntry }` — `markerEntry` is the chained\n * `system.subject-erased` summary (the N per-entry tombstones live\n * in the sink, not on the return value). (M7)\n *\n * When `erased === 0` (filter matched nothing), `markerEntry` is\n * `null` and no marker is emitted into the chain — avoids polluting\n * the audit trail with empty \"erased: 0\" records. (MAJOR-3)\n *\n * WARNING: v1 erases only from THIS sink. External copies (toJSON\n * exports, downstream pipelines, persisted backups) must be erased\n * separately. (C8)\n */\n erase(filter: QueryFilter): {\n erased: number;\n markerEntry: AuditEntry | null;\n };\n /** Empty the sink. */\n clear(): void;\n /** Unsubscribe + drop the sink. */\n destroy(): void;\n}\n","/**\n * `verify()` — walk the hash chain genesis → tip, surfacing the first\n * broken link (or accepting it as a legitimate erasure tombstone).\n *\n * Erased entries appear as legitimate breaks — their payload changed\n * so the NEXT entry's `prevHash` no longer matches. `verify()`\n * recognises a `system.entry-erased` entry bearing the in-module\n * sentinel and resyncs the walk from the tombstone's own hash.\n *\n * Forged tombstones — `kind: \"system.entry-erased\"` written directly\n * via `sink.write()` to mask real tamper — lack the sentinel and are\n * reported as `valid: false` with a `reason` describing the forgery. (N7)\n */\n\nimport { LEDGER_INTERNAL_TOKEN, hashForEntry } from \"./hash.js\";\nimport type { AuditEntry, AuditLedgerSink, VerifyResult } from \"./types.js\";\n\nexport function verify(\n sink: AuditLedgerSink,\n opts?: { strong?: boolean },\n): VerifyResult {\n // (C1) v1 ships sync djb2 only. Strong (SHA-256) verify is\n // reserved for v2 and must NOT silently no-op — the previous\n // implementation returned `{ valid: true }` regardless of the\n // chain's actual state, which lied to callers.\n if (opts?.strong === true) {\n throw new Error(\n \"[Directive] verify({ strong: true }) is reserved for v2 — v1 ships sync djb2 chain only. Use verify() (sync) for tamper detection.\",\n );\n }\n\n const { entries } = sink.toJSON();\n if (entries.length === 0) {\n return { valid: true, entryCount: 0 };\n }\n\n // Sync walk — catches anything the djb2 chain would see.\n // (N1 + M1) Erased-entry tombstones (kind: \"system.entry-erased\")\n // legitimately break the chain — the tombstone's payload differs\n // from the original entry it replaced, so the NEXT entry's\n // prevHash no longer matches. When we detect a break whose\n // PREVIOUS entry is a tombstone (or the broken entry itself is\n // one), record the seq and resync the walk from the tombstone's\n // own hash.\n //\n // (N7) Only tombstones bearing the internal sentinel are\n // recognised. A forged tombstone — `kind: \"system.entry-erased\"`\n // written directly via `sink.write()` to mask real tamper —\n // lacks the in-module symbol and is reported as tamper.\n //\n // Use a Set to dedupe — adjacent tombstones can otherwise be\n // recorded twice (once when the tombstone itself is the broken\n // entry, once when the next iteration sees its predecessor was\n // also a tombstone).\n const erasedSeqsSet = new Set<number>();\n let prevHash: string | null = null;\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i]!;\n if (entry.prevHash !== prevHash) {\n // Legitimate break? Either:\n // (a) the entry itself is the tombstone, or\n // (b) the previous entry was the tombstone whose payload\n // was rewritten by erase().\n const prevEntry = i > 0 ? entries[i - 1]! : null;\n const entryIsTombstone = entry.kind === \"system.entry-erased\";\n const prevIsTombstone = prevEntry?.kind === \"system.entry-erased\";\n\n if (entryIsTombstone || prevIsTombstone) {\n // (N7) Verify the SENTINEL on whichever entry(ies) claim\n // tombstone status. Missing sentinel ⇒ forgery ⇒ tamper.\n const candidates: AuditEntry[] = [];\n if (entryIsTombstone) candidates.push(entry);\n if (prevIsTombstone && prevEntry !== null) {\n candidates.push(prevEntry);\n }\n const forged = candidates.find(\n (e) =>\n (e as AuditEntry & { __internal?: unknown }).__internal !==\n LEDGER_INTERNAL_TOKEN,\n );\n if (forged) {\n return {\n valid: false,\n brokenAt: i,\n expectedHash: prevHash ?? \"<genesis>\",\n actualHash: entry.prevHash ?? \"<genesis>\",\n entry: forged,\n reason:\n \"tombstone forgery detected — missing internal sentinel. A 'system.entry-erased' entry was written via sink.write() rather than ledger.erase(); rejected as tamper.\",\n };\n }\n // Legitimate erasure — record the tombstone's seq and\n // resync the walk by hashing this entry as our new pointer\n // for the next iteration.\n const tombstoneEntry = entryIsTombstone ? entry : prevEntry!;\n erasedSeqsSet.add(tombstoneEntry.seq);\n prevHash = hashForEntry(entry);\n\n continue;\n }\n\n return {\n valid: false,\n brokenAt: i,\n expectedHash: prevHash ?? \"<genesis>\",\n actualHash: entry.prevHash ?? \"<genesis>\",\n entry,\n };\n }\n prevHash = hashForEntry(entry);\n }\n\n const result: {\n valid: true;\n entryCount: number;\n erasedSeqs?: number[];\n } = {\n valid: true,\n entryCount: entries.length,\n };\n if (erasedSeqsSet.size > 0) {\n result.erasedSeqs = [...erasedSeqsSet].sort((a, b) => a - b);\n }\n\n return result;\n}\n","/**\n * createAuditLedger — append-only, queryable, hash-chained\n * (djb2; SHA-256 reserved for v2) audit of every state change. For\n * forensics and \"show me why this user got that decision.\"\n *\n * Captures (per observation event):\n *\n * - `constraint.evaluate` → { whenSpec, whenExplain, active, whenSource? }\n * - `resolver.write.rejected` (rejection + summary kinds)\n * - `fact.change` → { key, prior, next }\n * - `resolver.complete` → { resolverId, requirementId, duration }\n * - `system.init` / `system.start` / `system.stop` / `system.destroy`\n * - `system.snapshot` / `system.history.navigate` (lifecycle markers)\n * - `system.truncated` (ring-buffer overflow marker)\n * - `system.entry-erased` / `system.subject-erased` (GDPR Art.17 stub)\n *\n * PII redaction: by default, fact keys whose meta carries the `pii`\n * tag (via `system.meta.byTag(\"pii\")`) have their values replaced with\n * `\"[redacted]\"` in `whenExplain.actual`, `fact.change.prior`,\n * `fact.change.next`, and the cached `whenSpec` operands. Opt out with\n * `capturePII: true`.\n *\n * Folder layout:\n * types.ts — public type surface + version stamps\n * hash.ts — djb2 dispatch + freeze helper + INTERNAL TOKEN\n * sink.ts — memorySink() ring buffer\n * predicate-redact.ts — PII-aware redactWhenSpec\n * verify.ts — tombstone-aware chain walk\n * index.ts (this) — createAuditLedger factory + plugin wiring\n */\n\nimport type {\n ModuleSchema,\n ObservationEvent,\n Plugin,\n System,\n} from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.js\";\nimport { hashObject } from \"../../utils/utils.js\";\nimport { LEDGER_INTERNAL_TOKEN, freezeEntry, hashForEntry } from \"./hash.js\";\nimport { redactWhenSpec } from \"./predicate-redact.js\";\nimport { memorySink } from \"./sink.js\";\nimport type {\n AuditEntry,\n AuditLedger,\n AuditLedgerOptions,\n VerifyResult,\n} from \"./types.js\";\nimport { HASH_ALGO, SCHEMA_VERSION } from \"./types.js\";\nimport { verify as verifyChain } from \"./verify.js\";\n\n// Re-export the public surface. `LEDGER_INTERNAL_TOKEN` is intentionally\n// NOT included — the tombstone-forgery defense depends on its\n// unguessability from outside this folder. (N7)\nexport { memorySink } from \"./sink.js\";\nexport type {\n AuditEntry,\n AuditEntryKind,\n AuditLedger,\n AuditLedgerOptions,\n AuditLedgerSink,\n QueryFilter,\n VerifyResult,\n} from \"./types.js\";\n\n/**\n * Create an audit ledger that subscribes to the given system's\n * observation stream. Returns a `Plugin` to install + a query/verify\n * API for the ledger.\n *\n * @example\n * ```ts\n * import { createAuditLedger } from \"@directive-run/core/plugins\";\n *\n * const ledger = createAuditLedger();\n * const system = createSystem({ module, plugins: [ledger.plugin] });\n * system.start();\n *\n * // Six months later — auditor asks \"what changed cart-total in March?\"\n * ledger.query({\n * factPath: \"cartTotal\",\n * changedBetween: [\"2026-03-01\", \"2026-04-01\"],\n * });\n *\n * // Verify nobody tampered with the ledger\n * const verdict = await ledger.verify();\n * if (!verdict.valid) {\n * console.error(\"Tamper at entry\", verdict.brokenAt);\n * }\n * ```\n */\nexport function createAuditLedger(opts: AuditLedgerOptions = {}): AuditLedger {\n const sink = opts.sink ?? memorySink();\n const capturePII = opts.capturePII ?? false;\n const userRedact = opts.redact;\n\n let seq = 0;\n let lastHashCache: string | null = null; // Cache hash of last-written entry payload\n\n let system: System<ModuleSchema> | null = null;\n let unobserve: (() => void) | null = null;\n\n /**\n * Cache of constraint.id → whenSpec (snapshotted at start, refreshed\n * on register/assign/unregister). Spec is already PII-redacted at\n * cache time, so the operand pointer that flows into every\n * `constraint.evaluate` entry can never leak. (C2)\n */\n const whenSpecCache = new Map<string, FactPredicate<unknown>>();\n\n /**\n * Cache of constraint.id → sourceHash for function-form constraints.\n * (N5, M22)\n *\n * We hash the stringified function rather than store any preview of\n * its source. Closures frequently reference secrets in scope\n * (`apiKey`, `dbPassword`, customer PII pulled from outer state) and\n * a preview would land those in the audit trail in plaintext. The\n * hash is a tamper-evident identity — auditors can verify \"this\n * constraint's source has not changed across these entries\" without\n * ever seeing the source itself.\n */\n const whenSourceCache = new Map<string, string>();\n\n /** Cache of PII-tagged fact paths. */\n const piiTaggedFacts = new Set<string>();\n\n function refreshWhenSpecCache(): void {\n whenSpecCache.clear();\n whenSourceCache.clear();\n if (!system) return;\n try {\n const inspect = (\n system as {\n inspect?: () => {\n constraints?: Array<{\n id: string;\n whenSpec?: unknown;\n when?: unknown;\n }>;\n };\n }\n ).inspect;\n if (typeof inspect !== \"function\") return;\n const inspection = inspect();\n const constraints = inspection?.constraints ?? [];\n // Best-effort access to merged constraint defs for function-form\n // source capture. Not exposed via the public type; we feature-detect.\n const mergedDefs = (\n system as {\n $internal?: {\n mergedConstraints?: Record<string, { when?: unknown }>;\n };\n }\n ).$internal?.mergedConstraints;\n for (const c of constraints) {\n if (c.whenSpec !== undefined) {\n // Redact PII operands at cache time so the cached pointer\n // flowing into evaluate entries is already safe. (C2)\n whenSpecCache.set(\n c.id,\n redactWhenSpec(\n c.whenSpec,\n capturePII,\n piiTaggedFacts,\n ) as FactPredicate<unknown>,\n );\n } else {\n // No whenSpec means function-form `when:` (or no when at\n // all). Capture a HASH of the function source rather than\n // the source itself — closures may reference secrets in\n // scope, and any preview would leak them into the audit\n // trail. (N5, M22)\n const def = mergedDefs?.[c.id];\n const whenFn =\n def && typeof def.when === \"function\" ? def.when : undefined;\n if (whenFn) {\n whenSourceCache.set(c.id, hashObject(String(whenFn)));\n } else if (c.when !== undefined && typeof c.when === \"function\") {\n whenSourceCache.set(c.id, hashObject(String(c.when)));\n } else {\n // Function-form constraint we couldn't reach the source\n // of. Mark it so audit entries still surface the form.\n // We hash the marker string for consistency with the\n // sourceHash field shape.\n whenSourceCache.set(c.id, hashObject(\"[function]\"));\n }\n }\n }\n } catch {\n // System not yet ready — skip silently.\n }\n }\n\n function refreshPIITags(): void {\n piiTaggedFacts.clear();\n if (capturePII || !system) return;\n try {\n const meta = (\n system as { meta?: { byTag?: (tag: string) => Array<{ id: string }> } }\n ).meta;\n if (!meta || typeof meta.byTag !== \"function\") return;\n const tagged = meta.byTag(\"pii\") ?? [];\n for (const m of tagged) {\n piiTaggedFacts.add(m.id);\n }\n } catch {\n // No meta accessor — skip.\n }\n }\n\n function redactValue(factPath: string, value: unknown): unknown {\n if (capturePII) return value;\n if (piiTaggedFacts.has(factPath)) return \"[redacted]\";\n\n return value;\n }\n\n function redactClauses(\n clauses: ClauseResult[] | undefined,\n ): ClauseResult[] | undefined {\n if (!clauses) return clauses;\n if (capturePII || piiTaggedFacts.size === 0) return clauses;\n let mutated = false;\n const out: ClauseResult[] = clauses.map((c) => {\n if (piiTaggedFacts.has(c.path)) {\n mutated = true;\n return { ...c, actual: \"[redacted]\" };\n }\n // Recurse into combinator children.\n if (c.children) {\n const inner = redactClauses(c.children);\n if (inner !== c.children) {\n mutated = true;\n return { ...c, children: inner };\n }\n }\n\n return c;\n });\n\n return mutated ? out : clauses;\n }\n\n /**\n * `partial` is the entry-specific payload (no seq/ts/prevHash). It's\n * typed as `Record<string, unknown>` because TS's distributed Omit\n * over the AuditEntry discriminated union doesn't compose cleanly;\n * runtime construction is safe because each call site passes a\n * known-shape literal.\n *\n * Entries are deeply-frozen at write time (depth 2 — top-level\n * values + whenExplain clauses) so that downstream consumers cannot\n * mutate payloads in place and forge the chain. (C3)\n */\n function emit(partial: Record<string, unknown>): AuditEntry {\n const entry = {\n ...partial,\n seq: seq++,\n ts: Date.now(),\n prevHash: lastHashCache,\n hashAlgo: HASH_ALGO,\n schemaVersion: SCHEMA_VERSION,\n } as AuditEntry;\n\n const finalEntry = userRedact ? userRedact(entry) : entry;\n freezeEntry(finalEntry);\n sink.write(finalEntry);\n\n // Sync hash of this entry — stashed as the next entry's prevHash.\n // Whole entry is hashed (including its own prevHash field) so\n // verify() can rebuild the chain deterministically.\n lastHashCache = hashForEntry(finalEntry);\n\n return finalEntry;\n }\n\n function onEvent(event: ObservationEvent): void {\n switch (event.type) {\n case \"constraint.evaluate\": {\n const whenSpec = whenSpecCache.get(event.id);\n const whenSourceHash = whenSourceCache.get(event.id);\n const partial: Record<string, unknown> = {\n kind: \"constraint.evaluate\",\n constraintId: event.id,\n active: event.active,\n whenExplain: redactClauses(event.whenExplain),\n };\n if (whenSpec !== undefined) {\n partial.whenSpec = whenSpec;\n } else if (whenSourceHash !== undefined) {\n // Function-form constraint — sourceHash is informational and\n // NOT replayable. We deliberately do NOT include any source\n // preview because closures may reference secrets in scope. (N5, M22)\n partial.whenSource = {\n kind: \"function\",\n sourceHash: whenSourceHash,\n };\n }\n emit(partial);\n break;\n }\n case \"fact.change\":\n emit({\n kind: \"fact.change\",\n key: event.key,\n prior: redactValue(event.key, event.prev),\n next: redactValue(event.key, event.next),\n });\n break;\n case \"resolver.write.rejected\":\n if (event.kind === \"summary\") {\n emit({\n kind: \"resolver.write.rejected\",\n rejection: \"summary\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n reason: event.reason,\n dropped: event.dropped,\n });\n } else {\n emit({\n kind: \"resolver.write.rejected\",\n rejection: \"rejection\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n reason: event.reason,\n fact: event.fact,\n expected: redactValue(event.fact, event.expected),\n actual: redactValue(event.fact, event.actual),\n });\n }\n break;\n case \"resolver.complete\":\n emit({\n kind: \"resolver.complete\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n duration: event.duration,\n });\n break;\n case \"resolver.error\":\n emit({\n kind: \"resolver.error\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n error: String(event.error),\n });\n break;\n case \"system.init\":\n case \"system.start\":\n case \"system.stop\":\n case \"system.destroy\":\n emit({ kind: event.type });\n break;\n case \"source.attach\":\n case \"source.detach\":\n // Source attach/detach captures the privilege-change posture:\n // a runtime-registered source is a new ingestion endpoint, an\n // attach/detach pair bounds the period during which fact mutations\n // could have originated from this source. `source.publish` is\n // DELIBERATELY NOT captured — high-volume sources would blow up\n // the ledger; the resulting fact.change entries already encode the\n // outcome and remain queryable.\n emit({\n kind: event.type,\n sourceId: event.id,\n moduleId: event.moduleId,\n });\n break;\n case \"source.error\":\n emit({\n kind: \"source.error\",\n sourceId: event.id,\n moduleId: event.moduleId,\n phase: event.phase,\n error:\n event.error instanceof Error\n ? event.error.message\n : String(event.error),\n });\n break;\n default:\n // Other observation events ignored in v1 (derivation.compute,\n // requirement.created/met/canceled, effect.run/error,\n // reconcile.start/end, source.publish). They're available via\n // .observe() directly if a consumer wants them.\n break;\n }\n }\n\n /**\n * Re-entrance guard for the truncation handler. The marker entry is\n * itself a write that may trigger another shift; without this we'd\n * recurse and overflow. (M23)\n */\n let emittingTruncate = false;\n\n function attach(sys: System<ModuleSchema>): void {\n system = sys;\n refreshPIITags();\n refreshWhenSpecCache();\n unobserve = sys.observe(onEvent);\n // Wire up the truncation marker — fires BEFORE the sink drops the\n // oldest entry, so the dropped seq is still known. The guard\n // prevents the marker's own write from recursing back through the\n // capacity overflow path. (M23)\n sink.onTruncate?.((droppedSeq, droppedCount) => {\n if (emittingTruncate) return;\n emittingTruncate = true;\n try {\n emit({\n kind: \"system.truncated\",\n droppedSeq,\n droppedCount,\n });\n } finally {\n emittingTruncate = false;\n }\n });\n }\n\n function detach(): void {\n if (unobserve) {\n unobserve();\n unobserve = null;\n }\n system = null;\n whenSpecCache.clear();\n whenSourceCache.clear();\n piiTaggedFacts.clear();\n }\n\n const plugin: Plugin<ModuleSchema> = {\n name: \"audit-ledger\",\n onInit(sys) {\n attach(sys as System<ModuleSchema>);\n },\n onStop() {\n // Keep the sink populated so query() works after stop, but\n // drop the subscription to avoid leaks.\n if (unobserve) {\n unobserve();\n unobserve = null;\n }\n },\n onDestroy() {\n detach();\n },\n onDefinitionRegister(type, id) {\n if (type === \"constraint\") refreshWhenSpecCache();\n if (type === \"constraint\" || type === \"resolver\" || type === \"effect\") {\n // Re-pull PII tags too — a dynamically-registered fact (rare)\n // could have brought new meta.\n refreshPIITags();\n }\n void id;\n },\n onDefinitionAssign(type, id) {\n // (C4) Constraint assigned a new spec — refresh the cache so the\n // NEXT evaluate emits the new whenSpec, not the stale one.\n if (type === \"constraint\") refreshWhenSpecCache();\n void id;\n },\n onDefinitionUnregister(type, id) {\n if (type === \"constraint\") refreshWhenSpecCache();\n void id;\n },\n onSnapshot(snapshot) {\n // (M9) Capture history snapshot as a lifecycle marker. Snapshot\n // contents (facts) are NOT included to keep the entry small and\n // avoid duplicating PII through a different channel.\n emit({\n kind: \"system.snapshot\",\n snapshotId: snapshot.id,\n trigger: snapshot.trigger,\n });\n },\n onHistoryNavigate(from, to) {\n // (M9) Capture time-travel navigation as a lifecycle marker.\n emit({\n kind: \"system.history.navigate\",\n from,\n to,\n });\n },\n };\n\n /**\n * Strip the internal sentinel from an entry before it reaches a\n * public read path. Returns a shallow clone with `__internal`\n * removed — keeps the (frozen) live entry intact for verify() while\n * making sure consumers never see the symbol. (N7)\n */\n function stripInternal(entry: AuditEntry): AuditEntry {\n if (\n (entry as AuditEntry & { __internal?: unknown }).__internal === undefined\n ) {\n return entry;\n }\n const clone = { ...entry } as AuditEntry & { __internal?: unknown };\n delete clone.__internal;\n\n return clone as AuditEntry;\n }\n\n function stripInternalAll(\n entries: readonly AuditEntry[],\n ): readonly AuditEntry[] {\n // Avoid allocating a new array unless at least one entry carries\n // the sentinel — the common case (no tombstones) is a no-op.\n let needsClone = false;\n for (const e of entries) {\n if (\n (e as AuditEntry & { __internal?: unknown }).__internal !== undefined\n ) {\n needsClone = true;\n break;\n }\n }\n if (!needsClone) {\n return entries;\n }\n\n return entries.map(stripInternal);\n }\n\n return {\n plugin,\n query: (filter = {}) => stripInternalAll(sink.query(filter)),\n recent: (n) => stripInternalAll(sink.recent(n)),\n forFact: (path, opts2) => stripInternalAll(sink.forFact(path, opts2)),\n forConstraint: (id, opts2) =>\n stripInternalAll(sink.forConstraint(id, opts2)),\n toJSON: () => {\n const snap = sink.toJSON();\n\n return {\n entries: stripInternalAll(snap.entries),\n capturedAt: snap.capturedAt,\n };\n },\n verify(opts?: { strong?: boolean }): VerifyResult {\n return verifyChain(sink, opts);\n },\n erase(filter) {\n // (C8) Replace matching entries with tombstones IN PLACE, keeping\n // seq + prevHash + hashAlgo so verify() can resync the chain.\n const erasedAt = Date.now();\n let count = 0;\n if (typeof sink.erase === \"function\") {\n count = sink.erase(filter, (e) => {\n // Build a tombstone preserving the immutable chain fields.\n // Carry SCHEMA_VERSION from the original so a fresh tombstone\n // doesn't claim to be at a newer schema than the entry it\n // replaced. (F-5)\n //\n // (N7) Stamp the in-module sentinel so `verify()` can tell\n // this tombstone apart from a forgery written via\n // `sink.write({ kind: \"system.entry-erased\", … })`. The\n // sentinel is stripped from every public read path.\n const tombstone = {\n seq: e.seq,\n ts: e.ts,\n kind: \"system.entry-erased\" as const,\n prevHash: e.prevHash,\n hashAlgo: e.hashAlgo,\n schemaVersion:\n (e as AuditEntry & { schemaVersion?: typeof SCHEMA_VERSION })\n .schemaVersion ?? SCHEMA_VERSION,\n originalKind: e.kind,\n erasedAt,\n __internal: LEDGER_INTERNAL_TOKEN,\n } as AuditEntry;\n // CAUTION: replacing the payload changes the entry's hash —\n // which means the NEXT entry's prevHash will no longer match.\n // verify() recognises `system.entry-erased` as a legitimate\n // chain break and reports it in `erasedSeqs` rather than as\n // tamper. (N1 + M1)\n freezeEntry(tombstone);\n\n return tombstone;\n });\n }\n // (MAJOR-3) Skip the `system.subject-erased` marker when nothing\n // matched the filter — emitting an \"erased: 0\" marker pollutes\n // the chain with noise and confuses auditors looking for real\n // erasures.\n if (count === 0) {\n return { erased: 0, markerEntry: null };\n }\n // (N2) Don't store the raw filter — PII can land in the values\n // (e.g. `factPath: \"alice@x.com\"`). Capture a hash + a shape\n // descriptor so an auditor sees WHICH fields were used without\n // exposing the values.\n const filterShape = {\n factPath: filter.factPath !== undefined,\n constraintId: filter.constraintId !== undefined,\n kind: filter.kind,\n changedBetween:\n filter.changedBetween !== undefined\n ? (\"[range]\" as const)\n : undefined,\n };\n // Emit a single chained `system.subject-erased` marker — recorded\n // AFTER the erasure so auditors see what was removed and why.\n const markerEntry = emit({\n kind: \"system.subject-erased\",\n filterHash: hashObject(filter),\n filterShape,\n erased: count,\n });\n\n return { erased: count, markerEntry };\n },\n clear() {\n sink.clear();\n seq = 0;\n lastHashCache = null;\n },\n destroy() {\n detach();\n sink.destroy();\n },\n };\n}\n"]}
|
package/dist/chunk-MARZI3EY.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkGACC2DMS_cjs=require('./chunk-GACC2DMS.cjs'),chunkGBCWXTXW_cjs=require('./chunk-GBCWXTXW.cjs');function L(t){if(t instanceof Date)return t.getTime();if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("[Directive] audit-ledger: changedBetween bound must be a finite number, ISO string, or Date.");return t}if(typeof t=="string"){let n=Date.parse(t);if(!Number.isFinite(n))throw new Error(`[Directive] audit-ledger: changedBetween bound "${t}" is not a parseable ISO date string.`);return n}throw new Error("[Directive] audit-ledger: changedBetween bound must be a number, ISO string, or Date.")}function x(t,n){if(n.kind&&!(Array.isArray(n.kind)?n.kind:[n.kind]).includes(t.kind))return false;if(n.factPath!==void 0)if(t.kind==="fact.change"){if(t.key!==n.factPath)return false}else if(t.kind==="resolver.write.rejected"){if(t.fact!==n.factPath)return false}else return false;if(n.constraintId!==void 0&&(t.kind!=="constraint.evaluate"||t.constraintId!==n.constraintId))return false;if(n.changedBetween){let[r,a]=n.changedBetween,u=L(r),d=L(a);if(t.ts<u||t.ts>d)return false}return true}function R(t={}){let n=t.capacity??1e4,r=[],a=null;return {write(d){if(r.length>=n){let i=r[0];a?.(i.seq,1),r.shift();}for(r.push(d);r.length>n;)r.shift();},query(d){let i=d.limit??1e3,o=[];for(let c=r.length-1;c>=0;c--){let y=r[c];if(x(y,d)&&(o.push(y),o.length>=i))break}return o},recent(d){let i=Math.max(0,r.length-d);return r.slice(i)},forFact(d,i={}){return this.query({factPath:d,limit:i.limit})},forConstraint(d,i={}){return this.query({constraintId:d,limit:i.limit})},toJSON(){return {entries:r.slice(),capturedAt:Date.now()}},clear(){r=[];},destroy(){r=[],a=null;},erase(d,i){let o=0;for(let c=0;c<r.length;c++){let y=r[c];x(y,d)&&(r[c]=i(y),o++);}return o},onTruncate(d){a=d;}}}var _=Symbol("directive.audit-ledger.internal");function C(t){for(let n of Object.keys(t)){let r=t[n];if(r!==null&&typeof r=="object"){if(Array.isArray(r)&&n==="whenExplain")for(let a of r)a!==null&&typeof a=="object"&&Object.freeze(a);Object.freeze(r);}}return Object.freeze(t),t}function K(t){return chunkGBCWXTXW_cjs.h(t)}function I(t){if(t.hashAlgo==="djb2-1")return K(t);throw new Error(`[Directive] audit-ledger: unknown hashAlgo "${String(t.hashAlgo)}" on entry seq=${t.seq}. Cannot verify chain integrity. Known algorithms: "djb2-1".`)}function H(t,n,r){if(t===null||typeof t!="object")return;let a=[];for(let i of n.split(".")){if(!i)continue;let o=i.match(/^\[(\d+)\](.*)$/);if(o){a.push(Number(o[1])),o[2]&&a.push(o[2].replace(/^\./,""));continue}let c=i.match(/^([^[]+)\[(\d+)\](.*)$/);if(c){a.push(c[1]),a.push(Number(c[2])),c[3]&&a.push(c[3].replace(/^\./,""));continue}a.push(i);}let u=t;for(let i=0;i<a.length-1;i++){let o=a[i];if(u===null||typeof u!="object")return;u=u[o];}if(u===null||typeof u!="object")return;let d=a[a.length-1];d!==void 0&&(u[d]=r);}function F(t,n,r){if(n||r.size===0||t===null||typeof t!="object")return t;let a;try{a=JSON.parse(JSON.stringify(t));}catch{return t}return chunkGACC2DMS_cjs.i(a,{operator(u,d,i,o){r.has(u)&&H(a,o,"[redacted]");},literal(u){r.has(u)&&H(a,u,"[redacted]");}}),a}var D="djb2-1";function N(t,n){if(n?.strong===true)throw new Error("[Directive] verify({ strong: true }) is reserved for v2 \u2014 v1 ships sync djb2 chain only. Use verify() (sync) for tamper detection.");let{entries:r}=t.toJSON();if(r.length===0)return {valid:true,entryCount:0};let a=new Set,u=null;for(let i=0;i<r.length;i++){let o=r[i];if(o.prevHash!==u){let c=i>0?r[i-1]:null,y=o.kind==="system.entry-erased",h=c?.kind==="system.entry-erased";if(y||h){let A=[];y&&A.push(o),h&&c!==null&&A.push(c);let b=A.find(v=>v.__internal!==_);if(b)return {valid:false,brokenAt:i,expectedHash:u??"<genesis>",actualHash:o.prevHash??"<genesis>",entry:b,reason:"tombstone forgery detected \u2014 missing internal sentinel. A 'system.entry-erased' entry was written via sink.write() rather than ledger.erase(); rejected as tamper."};let E=y?o:c;a.add(E.seq),u=I(o);continue}return {valid:false,brokenAt:i,expectedHash:u??"<genesis>",actualHash:o.prevHash??"<genesis>",entry:o}}u=I(o);}let d={valid:true,entryCount:r.length};return a.size>0&&(d.erasedSeqs=[...a].sort((i,o)=>i-o)),d}function ie(t={}){let n=t.sink??R(),r=t.capturePII??false,a=t.redact,u=0,d=null,i=null,o=null,c=new Map,y=new Map,h=new Set;function A(){if(c.clear(),y.clear(),!!i)try{let e=i.inspect;if(typeof e!="function")return;let l=e()?.constraints??[],f=i.$internal?.mergedConstraints;for(let m of l)if(m.whenSpec!==void 0)c.set(m.id,F(m.whenSpec,r,h));else {let g=f?.[m.id],S=g&&typeof g.when=="function"?g.when:void 0;S?y.set(m.id,chunkGBCWXTXW_cjs.h(String(S))):m.when!==void 0&&typeof m.when=="function"?y.set(m.id,chunkGBCWXTXW_cjs.h(String(m.when))):y.set(m.id,chunkGBCWXTXW_cjs.h("[function]"));}}catch{}}function b(){if(h.clear(),!(r||!i))try{let e=i.meta;if(!e||typeof e.byTag!="function")return;let s=e.byTag("pii")??[];for(let l of s)h.add(l.id);}catch{}}function E(e,s){return r?s:h.has(e)?"[redacted]":s}function v(e){if(!e||r||h.size===0)return e;let s=false,l=e.map(f=>{if(h.has(f.path))return s=true,{...f,actual:"[redacted]"};if(f.children){let m=v(f.children);if(m!==f.children)return s=true,{...f,children:m}}return f});return s?l:e}function p(e){let s={...e,seq:u++,ts:Date.now(),prevHash:d,hashAlgo:D,schemaVersion:1},l=a?a(s):s;return C(l),n.write(l),d=I(l),l}function P(e){switch(e.type){case "constraint.evaluate":{let s=c.get(e.id),l=y.get(e.id),f={kind:"constraint.evaluate",constraintId:e.id,active:e.active,whenExplain:v(e.whenExplain)};s!==void 0?f.whenSpec=s:l!==void 0&&(f.whenSource={kind:"function",sourceHash:l}),p(f);break}case "fact.change":p({kind:"fact.change",key:e.key,prior:E(e.key,e.prev),next:E(e.key,e.next)});break;case "resolver.write.rejected":e.kind==="summary"?p({kind:"resolver.write.rejected",rejection:"summary",resolverId:e.resolver,requirementId:e.requirementId,reason:e.reason,dropped:e.dropped}):p({kind:"resolver.write.rejected",rejection:"rejection",resolverId:e.resolver,requirementId:e.requirementId,reason:e.reason,fact:e.fact,expected:E(e.fact,e.expected),actual:E(e.fact,e.actual)});break;case "resolver.complete":p({kind:"resolver.complete",resolverId:e.resolver,requirementId:e.requirementId,duration:e.duration});break;case "resolver.error":p({kind:"resolver.error",resolverId:e.resolver,requirementId:e.requirementId,error:String(e.error)});break;case "system.init":case "system.start":case "system.stop":case "system.destroy":p({kind:e.type});break;case "source.attach":case "source.detach":p({kind:e.type,sourceId:e.id,moduleId:e.moduleId});break;case "source.error":p({kind:"source.error",sourceId:e.id,moduleId:e.moduleId,phase:e.phase,error:e.error instanceof Error?e.error.message:String(e.error)});break;}}let j=false;function T(e){i=e,b(),A(),o=e.observe(P),n.onTruncate?.((s,l)=>{if(!j){j=true;try{p({kind:"system.truncated",droppedSeq:s,droppedCount:l});}finally{j=false;}}});}function q(){o&&(o(),o=null),i=null,c.clear(),y.clear(),h.clear();}let M={name:"audit-ledger",onInit(e){T(e);},onStop(){o&&(o(),o=null);},onDestroy(){q();},onDefinitionRegister(e,s){e==="constraint"&&A(),(e==="constraint"||e==="resolver"||e==="effect")&&b();},onDefinitionAssign(e,s){e==="constraint"&&A();},onDefinitionUnregister(e,s){e==="constraint"&&A();},onSnapshot(e){p({kind:"system.snapshot",snapshotId:e.id,trigger:e.trigger});},onHistoryNavigate(e,s){p({kind:"system.history.navigate",from:e,to:s});}};function V(e){if(e.__internal===void 0)return e;let s={...e};return delete s.__internal,s}function w(e){let s=false;for(let l of e)if(l.__internal!==void 0){s=true;break}return s?e.map(V):e}return {plugin:M,query:(e={})=>w(n.query(e)),recent:e=>w(n.recent(e)),forFact:(e,s)=>w(n.forFact(e,s)),forConstraint:(e,s)=>w(n.forConstraint(e,s)),toJSON:()=>{let e=n.toJSON();return {entries:w(e.entries),capturedAt:e.capturedAt}},verify(e){return N(n,e)},erase(e){let s=Date.now(),l=0;if(typeof n.erase=="function"&&(l=n.erase(e,g=>{let S={seq:g.seq,ts:g.ts,kind:"system.entry-erased",prevHash:g.prevHash,hashAlgo:g.hashAlgo,schemaVersion:g.schemaVersion??1,originalKind:g.kind,erasedAt:s,__internal:_};return C(S),S})),l===0)return {erased:0,markerEntry:null};let f={factPath:e.factPath!==void 0,constraintId:e.constraintId!==void 0,kind:e.kind,changedBetween:e.changedBetween!==void 0?"[range]":void 0},m=p({kind:"system.subject-erased",filterHash:chunkGBCWXTXW_cjs.h(e),filterShape:f,erased:l});return {erased:l,markerEntry:m}},clear(){n.clear(),u=0,d=null;},destroy(){q(),n.destroy();}}}exports.a=R;exports.b=ie;//# sourceMappingURL=chunk-MARZI3EY.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-MARZI3EY.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugins/audit-ledger/sink.ts","../src/plugins/audit-ledger/hash.ts","../src/plugins/audit-ledger/predicate-redact.ts","../src/plugins/audit-ledger/types.ts","../src/plugins/audit-ledger/verify.ts","../src/plugins/audit-ledger/index.ts"],"names":["parseRangeBound","v","t","matchesFilter","entry","filter","a","b","start","end","memorySink","opts","capacity","entries","truncateHandler","dropped","limit","out","i","e","n","path","opts2","id","tombstoneFactory","count","handler","LEDGER_INTERNAL_TOKEN","freezeEntry","key","clause","syncHash","hashObject","hashForEntry","replaceAtPath","root","dottedPath","value","segs","part","m","m2","cur","seg","lastSeg","redactWhenSpec","spec","capturePII","piiTaggedFacts","cloned","walkPredicate","factPath","op","_operand","operandPath","HASH_ALGO","verify","sink","erasedSeqsSet","prevHash","prevEntry","entryIsTombstone","prevIsTombstone","candidates","forged","tombstoneEntry","result","createAuditLedger","userRedact","seq","lastHashCache","system","unobserve","whenSpecCache","whenSourceCache","refreshWhenSpecCache","inspect","constraints","mergedDefs","c","def","whenFn","refreshPIITags","meta","tagged","redactValue","redactClauses","clauses","mutated","inner","emit","partial","finalEntry","onEvent","event","whenSpec","whenSourceHash","emittingTruncate","attach","sys","droppedSeq","droppedCount","detach","plugin","type","snapshot","from","to","stripInternal","clone","stripInternalAll","needsClone","snap","erasedAt","tombstone","filterShape","markerEntry"],"mappings":"qHAiBA,SAASA,CAAAA,CAAgBC,CAAAA,CAAmC,CAC1D,GAAIA,CAAAA,YAAa,KAAM,OAAOA,CAAAA,CAAE,OAAA,EAAQ,CACxC,GAAI,OAAOA,GAAM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AAA,CACE,aAAA,EAAiB,EACtB,YAAA,CAAcA,CAAAA,CAAE,IAAA,CAChB,QAAA,CAAA8F,CAAAA,CACA,UAAA,CAAYtF,CACd,CAAA,CAMA,OAAAC,CAAAA,CAAYsF,CAAS,CAAA,CAEdA,CACT,CAAC,GAMCzF,CAAAA,GAAU,CAAA,CACZ,OAAO,CAAE,MAAA,CAAQ,CAAA,CAAG,WAAA,CAAa,IAAK,CAAA,CAMxC,IAAM0F,CAAAA,CAAc,CAClB,QAAA,CAAU9G,CAAAA,CAAO,WAAa,MAAA,CAC9B,YAAA,CAAcA,CAAAA,CAAO,YAAA,GAAiB,MAAA,CACtC,IAAA,CAAMA,EAAO,IAAA,CACb,cAAA,CACEA,CAAAA,CAAO,cAAA,GAAmB,MAAA,CACrB,SAAA,CACD,MACR,CAAA,CAGM+G,CAAAA,CAAc1B,CAAAA,CAAK,CACvB,IAAA,CAAM,uBAAA,CACN,UAAA,CAAY1D,mBAAAA,CAAW3B,CAAM,CAAA,CAC7B,WAAA,CAAA8G,CAAAA,CACA,MAAA,CAAQ1F,CACV,CAAC,CAAA,CAED,OAAO,CAAE,MAAA,CAAQA,CAAAA,CAAO,WAAA,CAAA2F,CAAY,CACtC,CAAA,CACA,KAAA,EAAQ,CACN3D,CAAAA,CAAK,KAAA,EAAM,CACXY,EAAM,CAAA,CACNC,CAAAA,CAAgB,KAClB,CAAA,CACA,OAAA,EAAU,CACRgC,CAAAA,EAAO,CACP7C,CAAAA,CAAK,OAAA,GACP,CACF,CACF","file":"chunk-MARZI3EY.cjs","sourcesContent":["/**\n * `memorySink()` — bounded ring-buffer implementation of\n * `AuditLedgerSink`. Drops the oldest entry past `capacity`\n * (default 10,000), exposes a truncation hook so the ledger plugin\n * can emit a `system.truncated` marker before the shift, and\n * supports in-place tombstone erasure for GDPR Art. 17.\n *\n * Pure storage layer — no hash chain awareness, no PII redaction.\n * The plugin in `./index.ts` owns those concerns and routes them\n * through this sink via `write()` / `erase()`.\n */\n\nimport type { AuditEntry, AuditLedgerSink, QueryFilter } from \"./types.js\";\n\nconst DEFAULT_MEMORY_CAPACITY = 10_000;\nconst DEFAULT_QUERY_LIMIT = 1000;\n\nfunction parseRangeBound(v: string | number | Date): number {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"number\") {\n if (!Number.isFinite(v)) {\n throw new Error(\n \"[Directive] audit-ledger: changedBetween bound must be a finite number, ISO string, or Date.\",\n );\n }\n\n return v;\n }\n if (typeof v === \"string\") {\n const t = Date.parse(v);\n if (!Number.isFinite(t)) {\n throw new Error(\n `[Directive] audit-ledger: changedBetween bound \"${v}\" is not a parseable ISO date string.`,\n );\n }\n\n return t;\n }\n throw new Error(\n \"[Directive] audit-ledger: changedBetween bound must be a number, ISO string, or Date.\",\n );\n}\n\nexport function matchesFilter(entry: AuditEntry, filter: QueryFilter): boolean {\n if (filter.kind) {\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n if (!kinds.includes(entry.kind)) return false;\n }\n if (filter.factPath !== undefined) {\n // Exact match — no LIKE wildcards. (SEC M2)\n if (entry.kind === \"fact.change\") {\n if (entry.key !== filter.factPath) return false;\n } else if (entry.kind === \"resolver.write.rejected\") {\n if (entry.fact !== filter.factPath) return false;\n } else {\n return false;\n }\n }\n if (filter.constraintId !== undefined) {\n if (entry.kind !== \"constraint.evaluate\") return false;\n if (entry.constraintId !== filter.constraintId) return false;\n }\n if (filter.changedBetween) {\n const [a, b] = filter.changedBetween;\n const start = parseRangeBound(a);\n const end = parseRangeBound(b);\n if (entry.ts < start || entry.ts > end) return false;\n }\n\n return true;\n}\n\n/**\n * In-memory bounded ring-buffer sink. Drops oldest entries past\n * `capacity` (default 10,000). Use this as the default sink for dev,\n * tests, and StackBlitz demos.\n */\nexport function memorySink(opts: { capacity?: number } = {}): AuditLedgerSink {\n const capacity = opts.capacity ?? DEFAULT_MEMORY_CAPACITY;\n let entries: AuditEntry[] = [];\n let truncateHandler:\n | ((droppedSeq: number, droppedCount: number) => void)\n | null = null;\n\n const sink: AuditLedgerSink = {\n write(entry) {\n if (entries.length >= capacity) {\n // (M23) About to overflow — notify the owner BEFORE the shift\n // so the dropped seq is still known. The handler may push an\n // entry of its own (a truncation marker), which will itself\n // push us over capacity; we shift one for one until we're back\n // at capacity (handlers must be O(1) writers — typically one).\n const dropped = entries[0]!;\n truncateHandler?.(dropped.seq, 1);\n entries.shift();\n }\n entries.push(entry);\n // If the handler wrote a marker (entries.length now > capacity),\n // drop one more from the head to keep us at capacity exactly.\n while (entries.length > capacity) {\n entries.shift();\n }\n },\n query(filter) {\n const limit = filter.limit ?? DEFAULT_QUERY_LIMIT;\n const out: AuditEntry[] = [];\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i]!;\n if (matchesFilter(e, filter)) {\n out.push(e);\n if (out.length >= limit) break;\n }\n }\n\n return out;\n },\n recent(n) {\n const start = Math.max(0, entries.length - n);\n\n return entries.slice(start);\n },\n forFact(path, opts2 = {}) {\n return this.query({ factPath: path, limit: opts2.limit });\n },\n forConstraint(id, opts2 = {}) {\n return this.query({ constraintId: id, limit: opts2.limit });\n },\n toJSON() {\n return { entries: entries.slice(), capturedAt: Date.now() };\n },\n clear() {\n entries = [];\n },\n destroy() {\n entries = [];\n truncateHandler = null;\n },\n erase(filter, tombstoneFactory) {\n let count = 0;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!;\n if (matchesFilter(e, filter)) {\n entries[i] = tombstoneFactory(e);\n count++;\n }\n }\n\n return count;\n },\n onTruncate(handler) {\n truncateHandler = handler;\n },\n };\n\n return sink;\n}\n","/**\n * Hash chain primitives — canonicalization, djb2 dispatch, depth-2\n * freeze, and the in-module tombstone sentinel.\n *\n * `LEDGER_INTERNAL_TOKEN` is the heart of the tombstone-forgery defense\n * (N7). It MUST live in this single file and MUST NOT be re-exported\n * from the folder's public surface (`./index.ts`). The only external\n * surface that touches it is `verify()` and the tombstone factory in\n * `index.ts`, both of which import it directly from this module.\n *\n * Hash chain: each entry stores `prevHash` — the djb2 (`hashObject`)\n * hash of the previous entry's stable-stringified payload. Tampering\n * with any entry's payload breaks the next entry's `prevHash` link —\n * visible in `verify()`. v1 ships sync djb2 only; `verify({ strong: true })`\n * is reserved for v2 (SHA-256) and throws today.\n */\n\nimport { hashObject } from \"../../utils/utils.js\";\nimport type { AuditEntry } from \"./types.js\";\n\n/**\n * Private sentinel stamped onto tombstone entries by {@link createAuditLedger.erase}.\n * Never exported from the folder's barrel, never serialized — `verify()`\n * checks for it before accepting a `system.entry-erased` entry as a\n * legitimate chain break.\n *\n * (N7) Without this, a caller holding a raw `AuditLedgerSink` reference\n * could write `{ kind: \"system.entry-erased\", … }` directly into the\n * sink to mask real tampering as legitimate erasure. The sentinel\n * raises the bar so only the in-process ledger plugin (which lives in\n * this folder's closure) can mint a valid tombstone.\n *\n * @internal — DO NOT re-export from `./index.ts` or `./types.ts`.\n */\nexport const LEDGER_INTERNAL_TOKEN: unique symbol = Symbol(\n \"directive.audit-ledger.internal\",\n);\n\n/**\n * Depth-2 freeze: freeze the entry, freeze each top-level value, and\n * freeze each clause in `whenExplain`. Cycle-safe + cheap; prevents\n * in-process payload mutation that would forge the chain. (C3)\n */\nexport function freezeEntry(entry: AuditEntry): AuditEntry {\n for (const key of Object.keys(entry)) {\n const v = (entry as unknown as Record<string, unknown>)[key];\n if (v !== null && typeof v === \"object\") {\n if (Array.isArray(v) && key === \"whenExplain\") {\n for (const clause of v) {\n if (clause !== null && typeof clause === \"object\") {\n Object.freeze(clause);\n }\n }\n }\n Object.freeze(v);\n }\n }\n Object.freeze(entry);\n\n return entry;\n}\n\n// ============================================================================\n// Hash chain — canonicalization\n// ============================================================================\n//\n// `syncHash(entry)` calls `hashObject(entry)` which calls\n// `stableStringify(entry)` — every entry shape (seq, ts, kind, prevHash,\n// hashAlgo, ...payload) is canonicalized via key-sorted JSON, then\n// djb2-hashed to a 32-bit hex string.\n//\n// - Fast, sync, isomorphic Node/Bun/Deno/browser.\n// - Tamper-DETECTION against accidental + light adversarial probing.\n// - Collision-prone against a determined attacker, by design (32 bits).\n//\n// Any future change to the canonicalization or hash function breaks\n// existing exports, so each entry carries `hashAlgo: \"djb2-1\"`. Verifiers\n// must check that tag matches what they expect.\n//\n// `verify({ strong: true })` is reserved for v2 (SHA-256 chain via Web\n// Crypto). It throws today — there is no silent fallback. v1 ships sync\n// djb2 only.\n\nfunction syncHash(entry: AuditEntry): string {\n // stableStringify guarantees same hash across runtimes regardless of\n // key insertion order (architecture review #11, security review C1).\n return hashObject(entry);\n}\n\n/**\n * Dispatch to the right hash function based on the entry's `hashAlgo`\n * discriminator. v1 has a single arm (`djb2-1`); the switch is in\n * place so v2 can add `\"sha256-1\"` without touching call sites. (N5)\n *\n * v2 promise: when SHA-256 lands, this becomes `case \"sha256-1\": return\n * await asyncSha256(entry);` — verify() will become async accordingly.\n */\nexport function hashForEntry(entry: AuditEntry): string {\n switch (entry.hashAlgo) {\n case \"djb2-1\":\n return syncHash(entry);\n default:\n throw new Error(\n `[Directive] audit-ledger: unknown hashAlgo \"${String((entry as { hashAlgo: unknown }).hashAlgo)}\" on entry seq=${entry.seq}. Cannot verify chain integrity. Known algorithms: \"djb2-1\".`,\n );\n }\n}\n","/**\n * PII operand redaction for cached predicate specs.\n *\n * Cached `whenSpec` operand pointers (e.g. `{ email: { $eq:\n * \"alice@x.com\" } }`) flow into every `constraint.evaluate` entry —\n * without scrubbing, the email would land in the audit trail in\n * plaintext on every evaluation. (C2)\n *\n * `redactWhenSpec` deep-clones the spec, walks it via `walkPredicate`,\n * and replaces operand values at PII-tagged fact paths with\n * `\"[redacted]\"`. Best-effort: if the spec contains anything\n * non-JSON-serialisable, we return the original (the caller has\n * already snapshotted the reference).\n */\n\nimport { walkPredicate } from \"../../core/predicate.js\";\n\n/**\n * Navigate `root` to `dottedPath` (`foo.bar.$eq`, `foo[0].value`) and\n * replace the value at the leaf. Used by `redactWhenSpec` to scrub\n * PII operands in cached predicate specs. Best-effort: silently no-ops\n * if the path doesn't resolve (caller already cloned the spec).\n */\nfunction replaceAtPath(\n root: unknown,\n dottedPath: string,\n value: unknown,\n): void {\n if (root === null || typeof root !== \"object\") return;\n // Split on \".\" but treat \"[N]\" segments as array indices.\n // E.g. \"[0].value\" → [\"[0]\", \"value\"], \"foo.bar[1]\" → [\"foo\", \"bar[1]\"].\n const segs: Array<string | number> = [];\n for (const part of dottedPath.split(\".\")) {\n if (!part) continue;\n // Pull leading `[N]` if present.\n const m = part.match(/^\\[(\\d+)\\](.*)$/);\n if (m) {\n segs.push(Number(m[1]));\n if (m[2]) segs.push(m[2].replace(/^\\./, \"\"));\n continue;\n }\n // Trailing `[N]` on the segment.\n const m2 = part.match(/^([^[]+)\\[(\\d+)\\](.*)$/);\n if (m2) {\n segs.push(m2[1]!);\n segs.push(Number(m2[2]));\n if (m2[3]) segs.push(m2[3].replace(/^\\./, \"\"));\n continue;\n }\n segs.push(part);\n }\n\n let cur: unknown = root;\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n if (cur === null || typeof cur !== \"object\") return;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n if (cur === null || typeof cur !== \"object\") return;\n const lastSeg = segs[segs.length - 1];\n if (lastSeg === undefined) return;\n (cur as Record<string | number, unknown>)[lastSeg] = value;\n}\n\n/**\n * Walk a predicate spec and replace operands at PII-tagged fact paths\n * with `\"[redacted]\"`. Returns the input as-is when redaction is\n * disabled (`capturePII: true`) or no PII tags are registered;\n * otherwise returns a deep clone with the leaf values rewritten. (C2)\n */\nexport function redactWhenSpec(\n spec: unknown,\n capturePII: boolean,\n piiTaggedFacts: ReadonlySet<string>,\n): unknown {\n if (capturePII || piiTaggedFacts.size === 0) return spec;\n if (spec === null || typeof spec !== \"object\") return spec;\n\n // Deep-clone so we don't mutate the user's source predicate. JSON\n // round-trip handles plain objects + arrays cheaply; predicates are\n // already JSON-safe (validatePredicate enforces this).\n let cloned: unknown;\n try {\n cloned = JSON.parse(JSON.stringify(spec));\n } catch {\n // Spec contained something non-serializable; bail rather than crash.\n return spec;\n }\n\n walkPredicate(cloned, {\n operator(factPath, op, _operand, operandPath) {\n if (!piiTaggedFacts.has(factPath)) return;\n // Navigate cloned tree to operandPath and replace value.\n replaceAtPath(cloned, operandPath, \"[redacted]\");\n void op;\n },\n literal(factPath) {\n if (!piiTaggedFacts.has(factPath)) return;\n // Replace bare-value leaf at this factPath.\n replaceAtPath(cloned, factPath, \"[redacted]\");\n },\n });\n\n return cloned;\n}\n","/**\n * Audit-ledger type definitions — entry shapes, sink interface, query\n * filter, verify result, and plugin options. Pure types + the two\n * schema-version constants (`HASH_ALGO`, `SCHEMA_VERSION`) that are\n * referenced by the entry shape.\n *\n * Kept free of runtime imports so the hash/freeze/sink modules can pull\n * types from here without a cycle.\n */\n\nimport type { ModuleSchema, Plugin } from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.js\";\n\n// ============================================================================\n// Version stamps\n// ============================================================================\n\n/** Hash algorithm tag — bumped if canonicalization or hash function changes. */\nexport const HASH_ALGO = \"djb2-1\" as const;\n\n/**\n * Entry schema version. Bumped if `AuditEntry` field shape changes in\n * a way that breaks back-compat parsers. Persisted on every entry so\n * exports remain self-describing across library upgrades. (F-5)\n */\nexport const SCHEMA_VERSION = 1 as const;\n\n// ============================================================================\n// AuditEntry types\n// ============================================================================\n\nexport type AuditEntryKind =\n | \"constraint.evaluate\"\n | \"resolver.write.rejected\"\n | \"fact.change\"\n | \"resolver.complete\"\n | \"resolver.error\"\n | \"source.attach\"\n | \"source.detach\"\n | \"source.error\"\n | \"system.init\"\n | \"system.start\"\n | \"system.stop\"\n | \"system.destroy\"\n | \"system.snapshot\"\n | \"system.history.navigate\"\n | \"system.truncated\"\n | \"system.entry-erased\"\n | \"system.subject-erased\";\n\n/**\n * Internal sentinel symbol type. The actual symbol VALUE lives in\n * `hash.ts` and is never exported from this folder's public surface —\n * but the TYPE must be referenceable here so `AuditEntryBase` can\n * declare the optional `__internal` field.\n *\n * We use `symbol` rather than `typeof LEDGER_INTERNAL_TOKEN` because\n * importing the symbol value into types.ts would either re-export it\n * (defeating the defense) or create a circular import. The runtime\n * check in `verify()` compares against the actual symbol reference.\n */\ntype LedgerInternalSentinel = symbol;\n\ninterface AuditEntryBase {\n /** Monotonic sequence number, starting at 0. */\n readonly seq: number;\n /** Wall-clock timestamp (ms epoch). */\n readonly ts: number;\n /** Discriminator. */\n readonly kind: AuditEntryKind;\n /** Hash of the previous entry's full payload. null on the genesis entry. */\n readonly prevHash: string | null;\n /**\n * Hash algorithm tag identifying the canonicalization + hash\n * function in use. Bumped if the algorithm or canonical form\n * changes, so exports remain verifiable across versions.\n */\n readonly hashAlgo: typeof HASH_ALGO;\n /**\n * Entry schema version — bumped if any `AuditEntry` field shape\n * changes in a way that breaks back-compat. Pair with `hashAlgo`\n * when migrating older exports. (F-5)\n */\n readonly schemaVersion: typeof SCHEMA_VERSION;\n /**\n * Private sentinel — present (and equal to the in-module token) only\n * on legitimate tombstones minted by `ledger.erase()`. Filtered out\n * of all public read paths (`query`, `recent`, `toJSON`, etc.) so\n * consumers never see or copy it. (N7)\n *\n * NOT serialized. NOT exported. Forging this from outside the module\n * is impossible without the symbol reference; `verify()` rejects any\n * `system.entry-erased` entry that lacks it.\n *\n * @internal\n */\n readonly __internal?: LedgerInternalSentinel;\n}\n\nexport type AuditEntry =\n | (AuditEntryBase & {\n kind: \"constraint.evaluate\";\n constraintId: string;\n active: boolean;\n /** Cached at ledger start from `system.inspect().constraints[].whenSpec`. Refreshed on `register()`/`assign()`/`unregister()`. May be undefined for function-form constraints (see `whenSource`). PII operands redacted unless `capturePII: true`. */\n whenSpec?: FactPredicate<unknown>;\n whenExplain?: readonly ClauseResult[];\n /**\n * For function-form constraints (no `whenSpec`), a tamper-evident\n * identity for the function. We DO NOT capture the raw source —\n * closures routinely reference secrets, API keys, or PII (e.g.\n * `if (apiKey === \"sk-live-xxx\")`) and a preview would leak them\n * into the audit log. Instead, we capture a djb2 hash of the\n * stringified function (`hashObject(String(fn))`). Auditors can\n * detect \"the function changed between deploys\" by comparing\n * hashes across entries, without ever seeing the function body.\n *\n * Informational only — NOT replayable. (N5, M22)\n */\n whenSource?: { kind: \"function\"; sourceHash: string };\n })\n | (AuditEntryBase & {\n kind: \"resolver.write.rejected\";\n rejection: \"rejection\" | \"summary\";\n resolverId: string;\n requirementId: string;\n reason: string;\n fact?: string;\n expected?: unknown;\n actual?: unknown;\n dropped?: number;\n })\n | (AuditEntryBase & {\n kind: \"fact.change\";\n key: string;\n prior: unknown;\n next: unknown;\n })\n | (AuditEntryBase & {\n kind: \"resolver.complete\";\n resolverId: string;\n requirementId: string;\n duration: number;\n })\n | (AuditEntryBase & {\n kind: \"resolver.error\";\n resolverId: string;\n requirementId: string;\n error: string;\n })\n | (AuditEntryBase & {\n kind: \"source.attach\" | \"source.detach\";\n sourceId: string;\n moduleId: string;\n })\n | (AuditEntryBase & {\n kind: \"source.error\";\n sourceId: string;\n moduleId: string;\n /**\n * `phase: \"runtime\"` (RFC 0008) flags errors the source reported\n * mid-flight via the `reportError` callback `attach` receives as\n * its second argument — distinct from lifecycle `\"attach\"` /\n * `\"cleanup\"` failures.\n */\n phase: \"attach\" | \"cleanup\" | \"runtime\";\n /**\n * Truncated error message — capped at a fixed length by the source\n * manager before it reaches the ledger. Source authors who embed\n * payloads in error messages get a bounded leak surface rather than\n * an unbounded one. Pair with the matching `source.attach` /\n * `source.detach` entries for full lifecycle context.\n */\n error: string;\n })\n | (AuditEntryBase & {\n kind: \"system.init\" | \"system.start\" | \"system.stop\" | \"system.destroy\";\n })\n | (AuditEntryBase & {\n kind: \"system.snapshot\";\n snapshotId: number;\n trigger: string;\n })\n | (AuditEntryBase & {\n kind: \"system.history.navigate\";\n from: number;\n to: number;\n })\n | (AuditEntryBase & {\n kind: \"system.truncated\";\n droppedSeq: number;\n droppedCount: number;\n })\n | (AuditEntryBase & {\n kind: \"system.entry-erased\";\n originalKind: AuditEntryKind;\n erasedAt: number;\n })\n | (AuditEntryBase & {\n kind: \"system.subject-erased\";\n /**\n * djb2 hash of the filter (via `hashObject(filter)`). PII-safe —\n * the raw filter values never land in the ledger. Pair with\n * `filterShape` to see which filter fields were used. (N2)\n */\n filterHash: string;\n /**\n * Stripped-values shape of the filter — captures WHICH fields were\n * present without recording their values. (N2)\n */\n filterShape: {\n factPath: boolean;\n constraintId: boolean;\n kind: AuditEntryKind | readonly AuditEntryKind[] | undefined;\n changedBetween: \"[range]\" | undefined;\n };\n erased: number;\n });\n\n// ============================================================================\n// Sink interface\n// ============================================================================\n\nexport interface QueryFilter {\n /** Exact-match fact path. */\n factPath?: string;\n /** Filter by constraint id. */\n constraintId?: string;\n /** Filter by entry kind. */\n kind?: AuditEntryKind | readonly AuditEntryKind[];\n /** Time range as `[startMs, endMs]`, ISO strings, or epoch numbers. */\n changedBetween?: [string | number | Date, string | number | Date];\n /** Maximum entries returned. Default 1000. */\n limit?: number;\n}\n\n/**\n * Verify result — chain valid OR a break with full context for tamper visualization.\n *\n * Erased entries (via `ledger.erase()`) appear as legitimate chain breaks —\n * `verify()` reports them in `erasedSeqs` and continues the walk from the\n * tombstone's own hash. Real tamper still surfaces as `valid: false`.\n *\n * Forged tombstones (a caller writes `kind: \"system.entry-erased\"`\n * directly via `sink.write()` to mask tamper as erasure) are detected:\n * legitimate tombstones carry an in-module sentinel that forgeries\n * cannot mint, so `verify()` reports them as tamper. (N7)\n */\nexport type VerifyResult =\n | {\n valid: true;\n entryCount: number;\n /**\n * Seq numbers of entries legitimately broken by `erase()`\n * tombstones. NOT timestamps — each entry pairs this seq with\n * the per-entry `system.entry-erased.erasedAt` (ms epoch) for\n * the timestamp. Empty unless the chain contains erasures.\n * (N1 + M1; renamed from `erasedAt` in R3)\n */\n erasedSeqs?: number[];\n }\n | {\n valid: false;\n brokenAt: number;\n expectedHash: string;\n actualHash: string;\n entry: AuditEntry;\n /**\n * Human-readable reason for the break — populated for cases\n * where the cause is more specific than \"hash mismatch\" (e.g.\n * tombstone forgery detected via missing sentinel).\n */\n reason?: string;\n };\n\nexport interface AuditLedgerSink {\n write(entry: AuditEntry): void;\n query(filter: QueryFilter): readonly AuditEntry[];\n recent(n: number): readonly AuditEntry[];\n forFact(path: string, opts?: { limit?: number }): readonly AuditEntry[];\n forConstraint(id: string, opts?: { limit?: number }): readonly AuditEntry[];\n toJSON(): { entries: readonly AuditEntry[]; capturedAt: number };\n clear(): void;\n destroy(): void;\n /**\n * Replace matching entries with marker entries IN PLACE (preserving seq +\n * prevHash so the hash chain still verifies — the marker is a\n * tombstone in chain terms; the chain break is what makes erasure\n * visible to `verify()`). v1 implementation matches on the same\n * `QueryFilter` shape used by `query()`. Returns the count of entries\n * replaced.\n *\n * WARNING: erases only from this sink. Any external copies (toJSON\n * exports, downstream pipelines) must be erased separately.\n */\n erase?(\n filter: QueryFilter,\n markerEntryFactory: (e: AuditEntry) => AuditEntry,\n ): number;\n /**\n * Optional hook fired by the sink BEFORE shifting the oldest entry\n * out of a bounded ring buffer. The ledger plugin uses this to emit\n * a `system.truncated` marker so an auditor sees that the log was\n * truncated and where. (M23)\n */\n onTruncate?(\n handler: (droppedSeq: number, droppedCount: number) => void,\n ): void;\n}\n\n// ============================================================================\n// Plugin options + public API surface\n// ============================================================================\n\nexport interface AuditLedgerOptions {\n /** Sink to write entries to. Default: in-memory ring buffer (capacity 10k). */\n sink?: AuditLedgerSink;\n /**\n * Whether to capture raw fact values (`prior`/`next` on fact.change,\n * `actual` in whenExplain). Default `false` — PII-tagged facts are\n * redacted by default. Set `true` to opt out of redaction.\n */\n capturePII?: boolean;\n /**\n * Optional caller-supplied redactor. Runs AFTER the default\n * pii-tag-based redaction. Useful for additional sanitization.\n */\n redact?: (entry: AuditEntry) => AuditEntry;\n}\n\nexport interface AuditLedger {\n /** The plugin to pass to `createSystem({ plugins: [...] })`. */\n readonly plugin: Plugin<ModuleSchema>;\n /** Query entries matching the filter. */\n query(filter?: QueryFilter): readonly AuditEntry[];\n /** Most recent N entries (chronological). */\n recent(n: number): readonly AuditEntry[];\n /** All entries that touch this fact path (exact match). */\n forFact(path: string, opts?: { limit?: number }): readonly AuditEntry[];\n /** All entries for this constraint id. */\n forConstraint(id: string, opts?: { limit?: number }): readonly AuditEntry[];\n /** Full ledger snapshot for export / serialization. */\n toJSON(): { entries: readonly AuditEntry[]; capturedAt: number };\n /**\n * Walk the hash chain genesis → tip. Returns `{ valid: true }` iff\n * every entry's `prevHash` matches the (sync, djb2-based) hash of\n * the previous entry. On break, returns the index of the first\n * broken link plus the expected vs actual hashes — feed into a\n * \"TAMPERED\" visualization.\n *\n * Erased entries (via `ledger.erase()`) appear as legitimate chain\n * breaks — `verify()` reports them in `erasedSeqs` and continues\n * the walk from the tombstone's actual hash. Real tamper still\n * surfaces as `valid: false`. (N1 + M1)\n *\n * Forged tombstones — `kind: \"system.entry-erased\"` entries written\n * directly via `sink.write()` to mask tamper — are detected as\n * forgery. Legitimate tombstones carry an in-module sentinel that\n * forgeries cannot mint. (N7)\n *\n * v1 ships sync djb2 only. `verify({ strong: true })` is reserved\n * for v2 (SHA-256) and THROWS today — there is no silent fallback.\n * Call `verify()` (no args) for tamper detection.\n */\n verify(opts?: { strong?: boolean }): VerifyResult;\n /**\n * Per-subject erasure (GDPR Art. 17 stub). Replaces matching entries\n * in this sink with `system.entry-erased` tombstones (preserving\n * seq + prevHash so verify() can resync), then appends a chained\n * `system.subject-erased` marker entry that summarises the erasure.\n *\n * Returns `{ erased, markerEntry }` — `markerEntry` is the chained\n * `system.subject-erased` summary (the N per-entry tombstones live\n * in the sink, not on the return value). (M7)\n *\n * When `erased === 0` (filter matched nothing), `markerEntry` is\n * `null` and no marker is emitted into the chain — avoids polluting\n * the audit trail with empty \"erased: 0\" records. (MAJOR-3)\n *\n * WARNING: v1 erases only from THIS sink. External copies (toJSON\n * exports, downstream pipelines, persisted backups) must be erased\n * separately. (C8)\n */\n erase(filter: QueryFilter): {\n erased: number;\n markerEntry: AuditEntry | null;\n };\n /** Empty the sink. */\n clear(): void;\n /** Unsubscribe + drop the sink. */\n destroy(): void;\n}\n","/**\n * `verify()` — walk the hash chain genesis → tip, surfacing the first\n * broken link (or accepting it as a legitimate erasure tombstone).\n *\n * Erased entries appear as legitimate breaks — their payload changed\n * so the NEXT entry's `prevHash` no longer matches. `verify()`\n * recognises a `system.entry-erased` entry bearing the in-module\n * sentinel and resyncs the walk from the tombstone's own hash.\n *\n * Forged tombstones — `kind: \"system.entry-erased\"` written directly\n * via `sink.write()` to mask real tamper — lack the sentinel and are\n * reported as `valid: false` with a `reason` describing the forgery. (N7)\n */\n\nimport { LEDGER_INTERNAL_TOKEN, hashForEntry } from \"./hash.js\";\nimport type { AuditEntry, AuditLedgerSink, VerifyResult } from \"./types.js\";\n\nexport function verify(\n sink: AuditLedgerSink,\n opts?: { strong?: boolean },\n): VerifyResult {\n // (C1) v1 ships sync djb2 only. Strong (SHA-256) verify is\n // reserved for v2 and must NOT silently no-op — the previous\n // implementation returned `{ valid: true }` regardless of the\n // chain's actual state, which lied to callers.\n if (opts?.strong === true) {\n throw new Error(\n \"[Directive] verify({ strong: true }) is reserved for v2 — v1 ships sync djb2 chain only. Use verify() (sync) for tamper detection.\",\n );\n }\n\n const { entries } = sink.toJSON();\n if (entries.length === 0) {\n return { valid: true, entryCount: 0 };\n }\n\n // Sync walk — catches anything the djb2 chain would see.\n // (N1 + M1) Erased-entry tombstones (kind: \"system.entry-erased\")\n // legitimately break the chain — the tombstone's payload differs\n // from the original entry it replaced, so the NEXT entry's\n // prevHash no longer matches. When we detect a break whose\n // PREVIOUS entry is a tombstone (or the broken entry itself is\n // one), record the seq and resync the walk from the tombstone's\n // own hash.\n //\n // (N7) Only tombstones bearing the internal sentinel are\n // recognised. A forged tombstone — `kind: \"system.entry-erased\"`\n // written directly via `sink.write()` to mask real tamper —\n // lacks the in-module symbol and is reported as tamper.\n //\n // Use a Set to dedupe — adjacent tombstones can otherwise be\n // recorded twice (once when the tombstone itself is the broken\n // entry, once when the next iteration sees its predecessor was\n // also a tombstone).\n const erasedSeqsSet = new Set<number>();\n let prevHash: string | null = null;\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i]!;\n if (entry.prevHash !== prevHash) {\n // Legitimate break? Either:\n // (a) the entry itself is the tombstone, or\n // (b) the previous entry was the tombstone whose payload\n // was rewritten by erase().\n const prevEntry = i > 0 ? entries[i - 1]! : null;\n const entryIsTombstone = entry.kind === \"system.entry-erased\";\n const prevIsTombstone = prevEntry?.kind === \"system.entry-erased\";\n\n if (entryIsTombstone || prevIsTombstone) {\n // (N7) Verify the SENTINEL on whichever entry(ies) claim\n // tombstone status. Missing sentinel ⇒ forgery ⇒ tamper.\n const candidates: AuditEntry[] = [];\n if (entryIsTombstone) candidates.push(entry);\n if (prevIsTombstone && prevEntry !== null) {\n candidates.push(prevEntry);\n }\n const forged = candidates.find(\n (e) =>\n (e as AuditEntry & { __internal?: unknown }).__internal !==\n LEDGER_INTERNAL_TOKEN,\n );\n if (forged) {\n return {\n valid: false,\n brokenAt: i,\n expectedHash: prevHash ?? \"<genesis>\",\n actualHash: entry.prevHash ?? \"<genesis>\",\n entry: forged,\n reason:\n \"tombstone forgery detected — missing internal sentinel. A 'system.entry-erased' entry was written via sink.write() rather than ledger.erase(); rejected as tamper.\",\n };\n }\n // Legitimate erasure — record the tombstone's seq and\n // resync the walk by hashing this entry as our new pointer\n // for the next iteration.\n const tombstoneEntry = entryIsTombstone ? entry : prevEntry!;\n erasedSeqsSet.add(tombstoneEntry.seq);\n prevHash = hashForEntry(entry);\n\n continue;\n }\n\n return {\n valid: false,\n brokenAt: i,\n expectedHash: prevHash ?? \"<genesis>\",\n actualHash: entry.prevHash ?? \"<genesis>\",\n entry,\n };\n }\n prevHash = hashForEntry(entry);\n }\n\n const result: {\n valid: true;\n entryCount: number;\n erasedSeqs?: number[];\n } = {\n valid: true,\n entryCount: entries.length,\n };\n if (erasedSeqsSet.size > 0) {\n result.erasedSeqs = [...erasedSeqsSet].sort((a, b) => a - b);\n }\n\n return result;\n}\n","/**\n * createAuditLedger — append-only, queryable, hash-chained\n * (djb2; SHA-256 reserved for v2) audit of every state change. For\n * forensics and \"show me why this user got that decision.\"\n *\n * Captures (per observation event):\n *\n * - `constraint.evaluate` → { whenSpec, whenExplain, active, whenSource? }\n * - `resolver.write.rejected` (rejection + summary kinds)\n * - `fact.change` → { key, prior, next }\n * - `resolver.complete` → { resolverId, requirementId, duration }\n * - `system.init` / `system.start` / `system.stop` / `system.destroy`\n * - `system.snapshot` / `system.history.navigate` (lifecycle markers)\n * - `system.truncated` (ring-buffer overflow marker)\n * - `system.entry-erased` / `system.subject-erased` (GDPR Art.17 stub)\n *\n * PII redaction: by default, fact keys whose meta carries the `pii`\n * tag (via `system.meta.byTag(\"pii\")`) have their values replaced with\n * `\"[redacted]\"` in `whenExplain.actual`, `fact.change.prior`,\n * `fact.change.next`, and the cached `whenSpec` operands. Opt out with\n * `capturePII: true`.\n *\n * Folder layout:\n * types.ts — public type surface + version stamps\n * hash.ts — djb2 dispatch + freeze helper + INTERNAL TOKEN\n * sink.ts — memorySink() ring buffer\n * predicate-redact.ts — PII-aware redactWhenSpec\n * verify.ts — tombstone-aware chain walk\n * index.ts (this) — createAuditLedger factory + plugin wiring\n */\n\nimport type {\n ModuleSchema,\n ObservationEvent,\n Plugin,\n System,\n} from \"../../core/types.js\";\nimport type {\n ClauseResult,\n FactPredicate,\n} from \"../../core/types/predicate.js\";\nimport { hashObject } from \"../../utils/utils.js\";\nimport { LEDGER_INTERNAL_TOKEN, freezeEntry, hashForEntry } from \"./hash.js\";\nimport { redactWhenSpec } from \"./predicate-redact.js\";\nimport { memorySink } from \"./sink.js\";\nimport type {\n AuditEntry,\n AuditLedger,\n AuditLedgerOptions,\n VerifyResult,\n} from \"./types.js\";\nimport { HASH_ALGO, SCHEMA_VERSION } from \"./types.js\";\nimport { verify as verifyChain } from \"./verify.js\";\n\n// Re-export the public surface. `LEDGER_INTERNAL_TOKEN` is intentionally\n// NOT included — the tombstone-forgery defense depends on its\n// unguessability from outside this folder. (N7)\nexport { memorySink } from \"./sink.js\";\nexport type {\n AuditEntry,\n AuditEntryKind,\n AuditLedger,\n AuditLedgerOptions,\n AuditLedgerSink,\n QueryFilter,\n VerifyResult,\n} from \"./types.js\";\n\n/**\n * Create an audit ledger that subscribes to the given system's\n * observation stream. Returns a `Plugin` to install + a query/verify\n * API for the ledger.\n *\n * @example\n * ```ts\n * import { createAuditLedger } from \"@directive-run/core/plugins\";\n *\n * const ledger = createAuditLedger();\n * const system = createSystem({ module, plugins: [ledger.plugin] });\n * system.start();\n *\n * // Six months later — auditor asks \"what changed cart-total in March?\"\n * ledger.query({\n * factPath: \"cartTotal\",\n * changedBetween: [\"2026-03-01\", \"2026-04-01\"],\n * });\n *\n * // Verify nobody tampered with the ledger\n * const verdict = await ledger.verify();\n * if (!verdict.valid) {\n * console.error(\"Tamper at entry\", verdict.brokenAt);\n * }\n * ```\n */\nexport function createAuditLedger(opts: AuditLedgerOptions = {}): AuditLedger {\n const sink = opts.sink ?? memorySink();\n const capturePII = opts.capturePII ?? false;\n const userRedact = opts.redact;\n\n let seq = 0;\n let lastHashCache: string | null = null; // Cache hash of last-written entry payload\n\n let system: System<ModuleSchema> | null = null;\n let unobserve: (() => void) | null = null;\n\n /**\n * Cache of constraint.id → whenSpec (snapshotted at start, refreshed\n * on register/assign/unregister). Spec is already PII-redacted at\n * cache time, so the operand pointer that flows into every\n * `constraint.evaluate` entry can never leak. (C2)\n */\n const whenSpecCache = new Map<string, FactPredicate<unknown>>();\n\n /**\n * Cache of constraint.id → sourceHash for function-form constraints.\n * (N5, M22)\n *\n * We hash the stringified function rather than store any preview of\n * its source. Closures frequently reference secrets in scope\n * (`apiKey`, `dbPassword`, customer PII pulled from outer state) and\n * a preview would land those in the audit trail in plaintext. The\n * hash is a tamper-evident identity — auditors can verify \"this\n * constraint's source has not changed across these entries\" without\n * ever seeing the source itself.\n */\n const whenSourceCache = new Map<string, string>();\n\n /** Cache of PII-tagged fact paths. */\n const piiTaggedFacts = new Set<string>();\n\n function refreshWhenSpecCache(): void {\n whenSpecCache.clear();\n whenSourceCache.clear();\n if (!system) return;\n try {\n const inspect = (\n system as {\n inspect?: () => {\n constraints?: Array<{\n id: string;\n whenSpec?: unknown;\n when?: unknown;\n }>;\n };\n }\n ).inspect;\n if (typeof inspect !== \"function\") return;\n const inspection = inspect();\n const constraints = inspection?.constraints ?? [];\n // Best-effort access to merged constraint defs for function-form\n // source capture. Not exposed via the public type; we feature-detect.\n const mergedDefs = (\n system as {\n $internal?: {\n mergedConstraints?: Record<string, { when?: unknown }>;\n };\n }\n ).$internal?.mergedConstraints;\n for (const c of constraints) {\n if (c.whenSpec !== undefined) {\n // Redact PII operands at cache time so the cached pointer\n // flowing into evaluate entries is already safe. (C2)\n whenSpecCache.set(\n c.id,\n redactWhenSpec(\n c.whenSpec,\n capturePII,\n piiTaggedFacts,\n ) as FactPredicate<unknown>,\n );\n } else {\n // No whenSpec means function-form `when:` (or no when at\n // all). Capture a HASH of the function source rather than\n // the source itself — closures may reference secrets in\n // scope, and any preview would leak them into the audit\n // trail. (N5, M22)\n const def = mergedDefs?.[c.id];\n const whenFn =\n def && typeof def.when === \"function\" ? def.when : undefined;\n if (whenFn) {\n whenSourceCache.set(c.id, hashObject(String(whenFn)));\n } else if (c.when !== undefined && typeof c.when === \"function\") {\n whenSourceCache.set(c.id, hashObject(String(c.when)));\n } else {\n // Function-form constraint we couldn't reach the source\n // of. Mark it so audit entries still surface the form.\n // We hash the marker string for consistency with the\n // sourceHash field shape.\n whenSourceCache.set(c.id, hashObject(\"[function]\"));\n }\n }\n }\n } catch {\n // System not yet ready — skip silently.\n }\n }\n\n function refreshPIITags(): void {\n piiTaggedFacts.clear();\n if (capturePII || !system) return;\n try {\n const meta = (\n system as { meta?: { byTag?: (tag: string) => Array<{ id: string }> } }\n ).meta;\n if (!meta || typeof meta.byTag !== \"function\") return;\n const tagged = meta.byTag(\"pii\") ?? [];\n for (const m of tagged) {\n piiTaggedFacts.add(m.id);\n }\n } catch {\n // No meta accessor — skip.\n }\n }\n\n function redactValue(factPath: string, value: unknown): unknown {\n if (capturePII) return value;\n if (piiTaggedFacts.has(factPath)) return \"[redacted]\";\n\n return value;\n }\n\n function redactClauses(\n clauses: ClauseResult[] | undefined,\n ): ClauseResult[] | undefined {\n if (!clauses) return clauses;\n if (capturePII || piiTaggedFacts.size === 0) return clauses;\n let mutated = false;\n const out: ClauseResult[] = clauses.map((c) => {\n if (piiTaggedFacts.has(c.path)) {\n mutated = true;\n return { ...c, actual: \"[redacted]\" };\n }\n // Recurse into combinator children.\n if (c.children) {\n const inner = redactClauses(c.children);\n if (inner !== c.children) {\n mutated = true;\n return { ...c, children: inner };\n }\n }\n\n return c;\n });\n\n return mutated ? out : clauses;\n }\n\n /**\n * `partial` is the entry-specific payload (no seq/ts/prevHash). It's\n * typed as `Record<string, unknown>` because TS's distributed Omit\n * over the AuditEntry discriminated union doesn't compose cleanly;\n * runtime construction is safe because each call site passes a\n * known-shape literal.\n *\n * Entries are deeply-frozen at write time (depth 2 — top-level\n * values + whenExplain clauses) so that downstream consumers cannot\n * mutate payloads in place and forge the chain. (C3)\n */\n function emit(partial: Record<string, unknown>): AuditEntry {\n const entry = {\n ...partial,\n seq: seq++,\n ts: Date.now(),\n prevHash: lastHashCache,\n hashAlgo: HASH_ALGO,\n schemaVersion: SCHEMA_VERSION,\n } as AuditEntry;\n\n const finalEntry = userRedact ? userRedact(entry) : entry;\n freezeEntry(finalEntry);\n sink.write(finalEntry);\n\n // Sync hash of this entry — stashed as the next entry's prevHash.\n // Whole entry is hashed (including its own prevHash field) so\n // verify() can rebuild the chain deterministically.\n lastHashCache = hashForEntry(finalEntry);\n\n return finalEntry;\n }\n\n function onEvent(event: ObservationEvent): void {\n switch (event.type) {\n case \"constraint.evaluate\": {\n const whenSpec = whenSpecCache.get(event.id);\n const whenSourceHash = whenSourceCache.get(event.id);\n const partial: Record<string, unknown> = {\n kind: \"constraint.evaluate\",\n constraintId: event.id,\n active: event.active,\n whenExplain: redactClauses(event.whenExplain),\n };\n if (whenSpec !== undefined) {\n partial.whenSpec = whenSpec;\n } else if (whenSourceHash !== undefined) {\n // Function-form constraint — sourceHash is informational and\n // NOT replayable. We deliberately do NOT include any source\n // preview because closures may reference secrets in scope. (N5, M22)\n partial.whenSource = {\n kind: \"function\",\n sourceHash: whenSourceHash,\n };\n }\n emit(partial);\n break;\n }\n case \"fact.change\":\n emit({\n kind: \"fact.change\",\n key: event.key,\n prior: redactValue(event.key, event.prev),\n next: redactValue(event.key, event.next),\n });\n break;\n case \"resolver.write.rejected\":\n if (event.kind === \"summary\") {\n emit({\n kind: \"resolver.write.rejected\",\n rejection: \"summary\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n reason: event.reason,\n dropped: event.dropped,\n });\n } else {\n emit({\n kind: \"resolver.write.rejected\",\n rejection: \"rejection\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n reason: event.reason,\n fact: event.fact,\n expected: redactValue(event.fact, event.expected),\n actual: redactValue(event.fact, event.actual),\n });\n }\n break;\n case \"resolver.complete\":\n emit({\n kind: \"resolver.complete\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n duration: event.duration,\n });\n break;\n case \"resolver.error\":\n emit({\n kind: \"resolver.error\",\n resolverId: event.resolver,\n requirementId: event.requirementId,\n error: String(event.error),\n });\n break;\n case \"system.init\":\n case \"system.start\":\n case \"system.stop\":\n case \"system.destroy\":\n emit({ kind: event.type });\n break;\n case \"source.attach\":\n case \"source.detach\":\n // Source attach/detach captures the privilege-change posture:\n // a runtime-registered source is a new ingestion endpoint, an\n // attach/detach pair bounds the period during which fact mutations\n // could have originated from this source. `source.publish` is\n // DELIBERATELY NOT captured — high-volume sources would blow up\n // the ledger; the resulting fact.change entries already encode the\n // outcome and remain queryable.\n emit({\n kind: event.type,\n sourceId: event.id,\n moduleId: event.moduleId,\n });\n break;\n case \"source.error\":\n emit({\n kind: \"source.error\",\n sourceId: event.id,\n moduleId: event.moduleId,\n phase: event.phase,\n error:\n event.error instanceof Error\n ? event.error.message\n : String(event.error),\n });\n break;\n default:\n // Other observation events ignored in v1 (derivation.compute,\n // requirement.created/met/canceled, effect.run/error,\n // reconcile.start/end, source.publish). They're available via\n // .observe() directly if a consumer wants them.\n break;\n }\n }\n\n /**\n * Re-entrance guard for the truncation handler. The marker entry is\n * itself a write that may trigger another shift; without this we'd\n * recurse and overflow. (M23)\n */\n let emittingTruncate = false;\n\n function attach(sys: System<ModuleSchema>): void {\n system = sys;\n refreshPIITags();\n refreshWhenSpecCache();\n unobserve = sys.observe(onEvent);\n // Wire up the truncation marker — fires BEFORE the sink drops the\n // oldest entry, so the dropped seq is still known. The guard\n // prevents the marker's own write from recursing back through the\n // capacity overflow path. (M23)\n sink.onTruncate?.((droppedSeq, droppedCount) => {\n if (emittingTruncate) return;\n emittingTruncate = true;\n try {\n emit({\n kind: \"system.truncated\",\n droppedSeq,\n droppedCount,\n });\n } finally {\n emittingTruncate = false;\n }\n });\n }\n\n function detach(): void {\n if (unobserve) {\n unobserve();\n unobserve = null;\n }\n system = null;\n whenSpecCache.clear();\n whenSourceCache.clear();\n piiTaggedFacts.clear();\n }\n\n const plugin: Plugin<ModuleSchema> = {\n name: \"audit-ledger\",\n onInit(sys) {\n attach(sys as System<ModuleSchema>);\n },\n onStop() {\n // Keep the sink populated so query() works after stop, but\n // drop the subscription to avoid leaks.\n if (unobserve) {\n unobserve();\n unobserve = null;\n }\n },\n onDestroy() {\n detach();\n },\n onDefinitionRegister(type, id) {\n if (type === \"constraint\") refreshWhenSpecCache();\n if (type === \"constraint\" || type === \"resolver\" || type === \"effect\") {\n // Re-pull PII tags too — a dynamically-registered fact (rare)\n // could have brought new meta.\n refreshPIITags();\n }\n void id;\n },\n onDefinitionAssign(type, id) {\n // (C4) Constraint assigned a new spec — refresh the cache so the\n // NEXT evaluate emits the new whenSpec, not the stale one.\n if (type === \"constraint\") refreshWhenSpecCache();\n void id;\n },\n onDefinitionUnregister(type, id) {\n if (type === \"constraint\") refreshWhenSpecCache();\n void id;\n },\n onSnapshot(snapshot) {\n // (M9) Capture history snapshot as a lifecycle marker. Snapshot\n // contents (facts) are NOT included to keep the entry small and\n // avoid duplicating PII through a different channel.\n emit({\n kind: \"system.snapshot\",\n snapshotId: snapshot.id,\n trigger: snapshot.trigger,\n });\n },\n onHistoryNavigate(from, to) {\n // (M9) Capture time-travel navigation as a lifecycle marker.\n emit({\n kind: \"system.history.navigate\",\n from,\n to,\n });\n },\n };\n\n /**\n * Strip the internal sentinel from an entry before it reaches a\n * public read path. Returns a shallow clone with `__internal`\n * removed — keeps the (frozen) live entry intact for verify() while\n * making sure consumers never see the symbol. (N7)\n */\n function stripInternal(entry: AuditEntry): AuditEntry {\n if (\n (entry as AuditEntry & { __internal?: unknown }).__internal === undefined\n ) {\n return entry;\n }\n const clone = { ...entry } as AuditEntry & { __internal?: unknown };\n delete clone.__internal;\n\n return clone as AuditEntry;\n }\n\n function stripInternalAll(\n entries: readonly AuditEntry[],\n ): readonly AuditEntry[] {\n // Avoid allocating a new array unless at least one entry carries\n // the sentinel — the common case (no tombstones) is a no-op.\n let needsClone = false;\n for (const e of entries) {\n if (\n (e as AuditEntry & { __internal?: unknown }).__internal !== undefined\n ) {\n needsClone = true;\n break;\n }\n }\n if (!needsClone) {\n return entries;\n }\n\n return entries.map(stripInternal);\n }\n\n return {\n plugin,\n query: (filter = {}) => stripInternalAll(sink.query(filter)),\n recent: (n) => stripInternalAll(sink.recent(n)),\n forFact: (path, opts2) => stripInternalAll(sink.forFact(path, opts2)),\n forConstraint: (id, opts2) =>\n stripInternalAll(sink.forConstraint(id, opts2)),\n toJSON: () => {\n const snap = sink.toJSON();\n\n return {\n entries: stripInternalAll(snap.entries),\n capturedAt: snap.capturedAt,\n };\n },\n verify(opts?: { strong?: boolean }): VerifyResult {\n return verifyChain(sink, opts);\n },\n erase(filter) {\n // (C8) Replace matching entries with tombstones IN PLACE, keeping\n // seq + prevHash + hashAlgo so verify() can resync the chain.\n const erasedAt = Date.now();\n let count = 0;\n if (typeof sink.erase === \"function\") {\n count = sink.erase(filter, (e) => {\n // Build a tombstone preserving the immutable chain fields.\n // Carry SCHEMA_VERSION from the original so a fresh tombstone\n // doesn't claim to be at a newer schema than the entry it\n // replaced. (F-5)\n //\n // (N7) Stamp the in-module sentinel so `verify()` can tell\n // this tombstone apart from a forgery written via\n // `sink.write({ kind: \"system.entry-erased\", … })`. The\n // sentinel is stripped from every public read path.\n const tombstone = {\n seq: e.seq,\n ts: e.ts,\n kind: \"system.entry-erased\" as const,\n prevHash: e.prevHash,\n hashAlgo: e.hashAlgo,\n schemaVersion:\n (e as AuditEntry & { schemaVersion?: typeof SCHEMA_VERSION })\n .schemaVersion ?? SCHEMA_VERSION,\n originalKind: e.kind,\n erasedAt,\n __internal: LEDGER_INTERNAL_TOKEN,\n } as AuditEntry;\n // CAUTION: replacing the payload changes the entry's hash —\n // which means the NEXT entry's prevHash will no longer match.\n // verify() recognises `system.entry-erased` as a legitimate\n // chain break and reports it in `erasedSeqs` rather than as\n // tamper. (N1 + M1)\n freezeEntry(tombstone);\n\n return tombstone;\n });\n }\n // (MAJOR-3) Skip the `system.subject-erased` marker when nothing\n // matched the filter — emitting an \"erased: 0\" marker pollutes\n // the chain with noise and confuses auditors looking for real\n // erasures.\n if (count === 0) {\n return { erased: 0, markerEntry: null };\n }\n // (N2) Don't store the raw filter — PII can land in the values\n // (e.g. `factPath: \"alice@x.com\"`). Capture a hash + a shape\n // descriptor so an auditor sees WHICH fields were used without\n // exposing the values.\n const filterShape = {\n factPath: filter.factPath !== undefined,\n constraintId: filter.constraintId !== undefined,\n kind: filter.kind,\n changedBetween:\n filter.changedBetween !== undefined\n ? (\"[range]\" as const)\n : undefined,\n };\n // Emit a single chained `system.subject-erased` marker — recorded\n // AFTER the erasure so auditors see what was removed and why.\n const markerEntry = emit({\n kind: \"system.subject-erased\",\n filterHash: hashObject(filter),\n filterShape,\n erased: count,\n });\n\n return { erased: count, markerEntry };\n },\n clear() {\n sink.clear();\n seq = 0;\n lastHashCache = null;\n },\n destroy() {\n detach();\n sink.destroy();\n },\n };\n}\n"]}
|