@astram/core 0.1.0 → 1.1.0

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.
Files changed (142) hide show
  1. package/dist/admin/admin-service.d.ts +1 -1
  2. package/dist/admin/command/grants.js +3 -3
  3. package/dist/admin/command/grants.js.map +1 -1
  4. package/dist/admin/command/invitations.d.ts +2 -2
  5. package/dist/admin/command/invitations.js +8 -8
  6. package/dist/admin/command/invitations.js.map +1 -1
  7. package/dist/admin/command/service-accounts.d.ts +1 -1
  8. package/dist/admin/command/service-accounts.js +1 -1
  9. package/dist/admin/query/simulate.d.ts.map +1 -1
  10. package/dist/admin/query/simulate.js +4 -0
  11. package/dist/admin/query/simulate.js.map +1 -1
  12. package/dist/admin/safeguards-impl.d.ts +2 -2
  13. package/dist/admin/safeguards-impl.js +9 -9
  14. package/dist/admin/safeguards-impl.js.map +1 -1
  15. package/dist/admin/safeguards.d.ts +4 -4
  16. package/dist/admin/safeguards.js +4 -4
  17. package/dist/admin/types.d.ts +1 -1
  18. package/dist/admin/types.d.ts.map +1 -1
  19. package/dist/authentication/authenticator.d.ts +2 -2
  20. package/dist/authentication/authenticator.js +2 -2
  21. package/dist/authentication/authenticator.js.map +1 -1
  22. package/dist/authentication/credential-resolver.d.ts +1 -1
  23. package/dist/authorization/cross-tenant/grant-evaluator.d.ts +2 -2
  24. package/dist/authorization/cross-tenant/grant-evaluator.js +2 -2
  25. package/dist/authorization/decision-authority.d.ts +2 -2
  26. package/dist/authorization/decision-authority.d.ts.map +1 -1
  27. package/dist/authorization/decision-authority.js +11 -3
  28. package/dist/authorization/decision-authority.js.map +1 -1
  29. package/dist/authorization/errors.d.ts +37 -0
  30. package/dist/authorization/errors.d.ts.map +1 -1
  31. package/dist/authorization/errors.js +43 -0
  32. package/dist/authorization/errors.js.map +1 -1
  33. package/dist/authorization/gates/object-type.d.ts +2 -2
  34. package/dist/authorization/gates/object-type.d.ts.map +1 -1
  35. package/dist/authorization/gates/object-type.js +20 -7
  36. package/dist/authorization/gates/object-type.js.map +1 -1
  37. package/dist/authorization/gates/tenant.d.ts +3 -3
  38. package/dist/authorization/gates/tenant.js +7 -7
  39. package/dist/authorization/gates/tenant.js.map +1 -1
  40. package/dist/authorization/index.d.ts +33 -4
  41. package/dist/authorization/index.d.ts.map +1 -1
  42. package/dist/authorization/index.js +39 -4
  43. package/dist/authorization/index.js.map +1 -1
  44. package/dist/authorization/ports.d.ts +3 -3
  45. package/dist/authorization/reason-codes.d.ts +7 -1
  46. package/dist/authorization/reason-codes.d.ts.map +1 -1
  47. package/dist/authorization/reason-codes.js +9 -1
  48. package/dist/authorization/reason-codes.js.map +1 -1
  49. package/dist/authorization/record/owner-baseline.d.ts +43 -0
  50. package/dist/authorization/record/owner-baseline.d.ts.map +1 -0
  51. package/dist/authorization/record/owner-baseline.js +72 -0
  52. package/dist/authorization/record/owner-baseline.js.map +1 -0
  53. package/dist/authorization/record/permit-tier.d.ts.map +1 -1
  54. package/dist/authorization/record/permit-tier.js +16 -5
  55. package/dist/authorization/record/permit-tier.js.map +1 -1
  56. package/dist/identity/broker.d.ts +8 -8
  57. package/dist/identity/broker.d.ts.map +1 -1
  58. package/dist/identity/broker.js +8 -8
  59. package/dist/identity/broker.js.map +1 -1
  60. package/dist/identity/claim-mapper.d.ts +8 -8
  61. package/dist/identity/claim-mapper.d.ts.map +1 -1
  62. package/dist/identity/claim-mapper.js +4 -4
  63. package/dist/identity/index.d.ts +2 -2
  64. package/dist/identity/index.d.ts.map +1 -1
  65. package/dist/identity/internal-adapter.d.ts +12 -12
  66. package/dist/identity/internal-adapter.d.ts.map +1 -1
  67. package/dist/identity/internal-adapter.js +9 -9
  68. package/dist/identity/internal-adapter.js.map +1 -1
  69. package/dist/metadata/index.d.ts +43 -0
  70. package/dist/metadata/index.d.ts.map +1 -1
  71. package/dist/metadata/index.js +6 -0
  72. package/dist/metadata/index.js.map +1 -1
  73. package/dist/metadata/registry.d.ts.map +1 -1
  74. package/dist/metadata/registry.js +2 -1
  75. package/dist/metadata/registry.js.map +1 -1
  76. package/dist-cjs/admin/admin-service.js +159 -0
  77. package/dist-cjs/admin/command/grants.js +200 -0
  78. package/dist-cjs/admin/command/index.js +38 -0
  79. package/dist-cjs/admin/command/invitations.js +246 -0
  80. package/dist-cjs/admin/command/permissions.js +69 -0
  81. package/dist-cjs/admin/command/pipeline.js +110 -0
  82. package/dist-cjs/admin/command/policies.js +223 -0
  83. package/dist-cjs/admin/command/service-accounts.js +278 -0
  84. package/dist-cjs/admin/command/service.js +130 -0
  85. package/dist-cjs/admin/command/tiers.js +81 -0
  86. package/dist-cjs/admin/index.js +78 -0
  87. package/dist-cjs/admin/ports.js +41 -0
  88. package/dist-cjs/admin/query/audit-view.js +88 -0
  89. package/dist-cjs/admin/query/catalog.js +174 -0
  90. package/dist-cjs/admin/query/explain.js +149 -0
  91. package/dist-cjs/admin/query/index.js +74 -0
  92. package/dist-cjs/admin/query/simulate.js +98 -0
  93. package/dist-cjs/admin/safeguards-impl.js +322 -0
  94. package/dist-cjs/admin/safeguards.js +95 -0
  95. package/dist-cjs/admin/types.js +40 -0
  96. package/dist-cjs/audit/audit-recorder.js +269 -0
  97. package/dist-cjs/audit/canonicalize.js +176 -0
  98. package/dist-cjs/audit/errors.js +44 -0
  99. package/dist-cjs/audit/index.js +39 -0
  100. package/dist-cjs/audit/ports.js +27 -0
  101. package/dist-cjs/audit/sensitive.js +162 -0
  102. package/dist-cjs/audit/walk.js +123 -0
  103. package/dist-cjs/authentication/authenticator.js +210 -0
  104. package/dist-cjs/authentication/credential-resolver.js +21 -0
  105. package/dist-cjs/authentication/index.js +42 -0
  106. package/dist-cjs/authentication/password-hasher.js +21 -0
  107. package/dist-cjs/authentication/totp.js +155 -0
  108. package/dist-cjs/authorization/cross-tenant/grant-evaluator.js +167 -0
  109. package/dist-cjs/authorization/decision-authority.js +213 -0
  110. package/dist-cjs/authorization/default-gates.js +53 -0
  111. package/dist-cjs/authorization/delegation/operation-identity.js +226 -0
  112. package/dist-cjs/authorization/errors.js +110 -0
  113. package/dist-cjs/authorization/gates/object-type.js +192 -0
  114. package/dist-cjs/authorization/gates/tenant.js +89 -0
  115. package/dist-cjs/authorization/gates/wiring.js +59 -0
  116. package/dist-cjs/authorization/index.js +134 -0
  117. package/dist-cjs/authorization/ports.js +36 -0
  118. package/dist-cjs/authorization/reason-codes.js +117 -0
  119. package/dist-cjs/authorization/record/owner-baseline.js +74 -0
  120. package/dist-cjs/authorization/record/permit-tier.js +92 -0
  121. package/dist-cjs/authorization/record/rule-evaluator.js +128 -0
  122. package/dist-cjs/authorization/record/shares.js +110 -0
  123. package/dist-cjs/identity/broker.js +139 -0
  124. package/dist-cjs/identity/claim-mapper.js +51 -0
  125. package/dist-cjs/identity/index.js +39 -0
  126. package/dist-cjs/identity/internal-adapter.js +91 -0
  127. package/dist-cjs/index.js +63 -0
  128. package/dist-cjs/metadata/completeness.js +108 -0
  129. package/dist-cjs/metadata/dependencies.js +110 -0
  130. package/dist-cjs/metadata/index.js +76 -0
  131. package/dist-cjs/metadata/registry.js +207 -0
  132. package/dist-cjs/package.json +3 -0
  133. package/dist-cjs/risk/evaluator.js +63 -0
  134. package/dist-cjs/risk/index.js +35 -0
  135. package/dist-cjs/risk/risk-engine.js +290 -0
  136. package/dist-cjs/risk/signals.js +106 -0
  137. package/dist-cjs/risk/thresholds.js +63 -0
  138. package/dist-cjs/session/index.js +35 -0
  139. package/dist-cjs/session/lifetimes.js +70 -0
  140. package/dist-cjs/session/ports.js +23 -0
  141. package/dist-cjs/session/session-authority.js +398 -0
  142. package/package.json +13 -10
@@ -0,0 +1,269 @@
1
+ "use strict";
2
+ /**
3
+ * The Audit **engine** — the body behind the FROZEN {@link AuditSink} seam
4
+ * (`./index.ts`). Validates → strips secrets → stamps → hash-CHAINS → appends
5
+ * ONE immutable, attributable, tenant-scoped audit record per event, so any later
6
+ * deletion / reordering / mutation is DETECTABLE ({@link verifyChain}).
7
+ *
8
+ * Mirrors the Session engine (`../session/session-authority.ts`): a pure
9
+ * `createAuditRecorder(...)` factory over INJECTED ports (store / hash / clock),
10
+ * a stateless impl, and a returned object that IS the frozen seam (drop-in
11
+ * `AuditSink`).
12
+ *
13
+ * ── THE TAMPER-EVIDENCE CORE (§3): a PER-TENANT hash chain.
14
+ * Each stored record carries `contentHash = H(canonicalize(cleanEvent))`,
15
+ * `prevHash` = the prior record's `entryHash` FOR THE SAME TENANT ({@link GENESIS}
16
+ * for a tenant's first record), and `entryHash = H(contentHash ‖ prevHash ‖
17
+ * sequenceNumber)`. Order is bound in via `sequenceNumber`, so deleting or
18
+ * reordering a record breaks EVERY downstream `entryHash`. The chain is
19
+ * per-tenant — a tamper in tenant A cannot be masked by tenant B's events, and
20
+ * B stays verifiable when A is broken (AC-5).
21
+ *
22
+ * ── APPEND-ONLY IS STRUCTURAL: the returned object exposes ONLY `record()` (the
23
+ * seam) — no update/delete path anywhere in the engine surface (AC-1). The
24
+ * store port likewise has no mutate/delete method (`./ports.ts`).
25
+ *
26
+ * ── FAIL-LOUD, NOT FAIL-CLOSED: unlike Session (which genericizes every failure),
27
+ * the audit engine must NEVER silently drop an event. A validation failure
28
+ * THROWS a typed {@link AuditValidationError} (AC-2); a store-append failure is
29
+ * let PROPAGATE unchanged (AC-11) so the emitting adapter — not the engine —
30
+ * decides whether the audited operation proceeds. The engine catches NOTHING on
31
+ * the write path.
32
+ *
33
+ * ── CONCURRENCY ASSUMPTION: `record()` reads the tenant's chain tail, then
34
+ * appends the successor. Correctness of the per-tenant `sequenceNumber` +
35
+ * `prevHash` link assumes the store SERIALIZES appends per tenant (the adapter's
36
+ * append-only table has a per-tenant unique `(tenantId, sequenceNumber)` key, so
37
+ * a racing duplicate sequence fails the constraint and the append rejects —
38
+ * surfacing to the caller rather than silently forking the chain). The pure
39
+ * engine does not itself lock; it relies on that store guarantee (documented on
40
+ * {@link import('./ports.js').AuditEventStore}).
41
+ *
42
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
43
+ */
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.GENESIS = void 0;
46
+ exports.createAuditRecorder = createAuditRecorder;
47
+ exports.verifyChain = verifyChain;
48
+ const canonicalize_js_1 = require("./canonicalize.js");
49
+ const errors_js_1 = require("./errors.js");
50
+ const sensitive_js_1 = require("./sensitive.js");
51
+ /**
52
+ * The fixed genesis `prevHash` for the FIRST record of every tenant's chain
53
+ * (§3.2). A constant (not a random/per-tenant value) so verification is fully
54
+ * reproducible from the records + the hash function alone — no hidden seed. The
55
+ * `shield:` namespace + `genesis:v1` version keeps it distinct from any real
56
+ * `entryHash` and lets the scheme version later without ambiguity.
57
+ */
58
+ exports.GENESIS = 'shield:audit:genesis:v1';
59
+ /** The field separator used when composing the `entryHash` preimage. */
60
+ const CHAIN_SEP = '|';
61
+ /**
62
+ * Compose the `entryHash` preimage: `contentHash ‖ prevHash ‖ sequenceNumber`.
63
+ * A single source of truth so the write path and {@link verifyChain} bind order
64
+ * IDENTICALLY (any drift here would make every chain fail verification).
65
+ */
66
+ function entryPreimage(contentHash, prevHash, sequenceNumber) {
67
+ return `${contentHash}${CHAIN_SEP}${prevHash}${CHAIN_SEP}${sequenceNumber}`;
68
+ }
69
+ /**
70
+ * A non-blank string guard — an actor/tenant id must be a present, non-whitespace
71
+ * string. (`.trim()` catches `' '`, which a bare `length === 0` would miss.)
72
+ */
73
+ function isNonBlank(value) {
74
+ return typeof value === 'string' && value.trim().length > 0;
75
+ }
76
+ /**
77
+ * Wire the injected ports and return an object implementing the FROZEN
78
+ * {@link AuditSink} — the engine's public entry point (mirrors
79
+ * `createSessionAuthority`). The returned value is a drop-in `AuditSink`: its ONLY
80
+ * public mutating method is `record()` (AC-1, no update/delete surface).
81
+ *
82
+ * ── APPEND-ONLY / ISOLATION IS STRUCTURAL (AC-1). The injected ports
83
+ * (`store`/`hash`/`clock`/`denylist`) are captured in THIS closure and are NOT
84
+ * fields on the returned object. A TS `private` field is compile-time-only — at
85
+ * runtime it is an enumerable own-property, so a class instance would leak
86
+ * `sink.store.append(forged)` / `sink.store.readChain(anyTenant)` as an
87
+ * append-only + cross-tenant escape hatch. Returning a frozen bare object whose
88
+ * ONLY own-property is `record` closes that hatch:
89
+ * `Object.getOwnPropertyNames(sink)` === `['record']`, `sink.store` is `undefined`.
90
+ *
91
+ * The independent tamper-detection primitive {@link verifyChain} is a SEPARATE
92
+ * exported pure function (an auditor/adapter verifies a chain it read back; it is
93
+ * not a method on the sink).
94
+ */
95
+ function createAuditRecorder(deps) {
96
+ // Capture the ports in the closure — never expose them off the returned object.
97
+ const store = deps.store;
98
+ const hash = deps.hash;
99
+ const clock = deps.clock;
100
+ const denylist = deps.sensitiveDenylist ?? sensitive_js_1.DEFAULT_SENSITIVE_DENYLIST;
101
+ async function record(event) {
102
+ // ── (1) VALIDATE (AC-2). Reject a malformed event LOUD — never store under a
103
+ // blank actor/tenant or an invalid time. Thrown BEFORE any hashing/append.
104
+ if (event === null || typeof event !== 'object') {
105
+ throw new errors_js_1.AuditValidationError('missing_actor');
106
+ }
107
+ if (!isNonBlank(event.actorId)) {
108
+ throw new errors_js_1.AuditValidationError('missing_actor');
109
+ }
110
+ if (!isNonBlank(event.tenantId)) {
111
+ throw new errors_js_1.AuditValidationError('missing_tenant');
112
+ }
113
+ if (typeof event.occurredAtMs !== 'number' || !Number.isFinite(event.occurredAtMs)) {
114
+ throw new errors_js_1.AuditValidationError('invalid_occurred_at');
115
+ }
116
+ // ── (2) STRIP SECRETS (AC-7). No raw secret value reaches the content hash or
117
+ // the store; only stripped key NAMES/PATHS are retained (never values). The
118
+ // stripper RECURSES through nested objects and arrays at every depth.
119
+ const { cleaned, strippedKeys } = (0, sensitive_js_1.stripSensitive)(event.attributes, denylist);
120
+ // The event whose CONTENT is fingerprinted — the caller's fields with the
121
+ // attributes replaced by the secret-stripped bag. Engine metadata (sequence,
122
+ // hashes, recordedAtMs) is NOT part of the content hash (see canonicalize).
123
+ const cleanEvent = {
124
+ type: event.type,
125
+ occurredAtMs: event.occurredAtMs,
126
+ actorId: event.actorId,
127
+ tenantId: event.tenantId,
128
+ ...(event.action !== undefined ? { action: event.action } : {}),
129
+ ...(event.resource !== undefined ? { resource: event.resource } : {}),
130
+ ...(event.decision !== undefined ? { decision: event.decision } : {}),
131
+ ...(cleaned !== undefined ? { attributes: cleaned } : {}),
132
+ };
133
+ // ── (3) CHAIN (§3, AC-3/4/5). Read this tenant's tail; compute sequence +
134
+ // prevHash from it. Per-tenant: `readChain` only returns THIS tenant's records.
135
+ const chain = await store.readChain(event.tenantId);
136
+ const tail = chain.length > 0 ? chain[chain.length - 1] : undefined;
137
+ const sequenceNumber = tail !== undefined ? tail.sequenceNumber + 1 : 0;
138
+ const prevHash = tail !== undefined ? tail.entryHash : exports.GENESIS;
139
+ const contentHash = hash.hash((0, canonicalize_js_1.canonicalizeEvent)(cleanEvent));
140
+ const entryHash = hash.hash(entryPreimage(contentHash, prevHash, sequenceNumber));
141
+ // ── (4) STAMP (AC-9). The engine's own clock — distinct from occurredAtMs.
142
+ const recordedAtMs = clock.nowMs();
143
+ const stored = {
144
+ type: cleanEvent.type,
145
+ occurredAtMs: cleanEvent.occurredAtMs,
146
+ actorId: cleanEvent.actorId,
147
+ tenantId: cleanEvent.tenantId,
148
+ ...(cleanEvent.action !== undefined ? { action: cleanEvent.action } : {}),
149
+ ...(cleanEvent.resource !== undefined ? { resource: cleanEvent.resource } : {}),
150
+ ...(cleanEvent.decision !== undefined ? { decision: cleanEvent.decision } : {}),
151
+ ...(cleaned !== undefined ? { attributes: cleaned } : {}),
152
+ ...(strippedKeys.length > 0 ? { strippedKeys } : {}),
153
+ sequenceNumber,
154
+ recordedAtMs,
155
+ contentHash,
156
+ prevHash,
157
+ entryHash,
158
+ };
159
+ // ── (5) APPEND (AC-1/11). If the store rejects, let it PROPAGATE — the engine
160
+ // NEVER swallows a failed append (that would silently drop an event). The
161
+ // emitting adapter decides whether the audited operation proceeds.
162
+ await store.append(Object.freeze(stored));
163
+ }
164
+ // The returned sink is a BARE, FROZEN object whose only own enumerable is
165
+ // `record` — no injected port is reachable off it (AC-1 append-only + isolation):
166
+ // • `Object.getOwnPropertyNames(sink)` === ['record'] (no store/hash/clock).
167
+ // • `sink.store` / `sink.hash` / `sink.clock` are `undefined`.
168
+ // • No mutate/delete/edit method anywhere on the surface OR its prototype.
169
+ // The prototype is a minimal `{ record }` (NOT `Object.prototype`) so a
170
+ // prototype-method scan sees ONLY `record`, never `Object.prototype`'s
171
+ // `hasOwnProperty`/`toString`/… — the surface is `record`, and nothing else,
172
+ // whether inspected as own-properties or as prototype methods.
173
+ const sinkProto = { record };
174
+ const sink = Object.create(sinkProto);
175
+ Object.defineProperty(sink, 'record', {
176
+ value: record,
177
+ enumerable: true,
178
+ writable: false,
179
+ configurable: false,
180
+ });
181
+ return Object.freeze(sink);
182
+ }
183
+ /**
184
+ * The PURE, independent TAMPER-DETECTION primitive (§3.4, AC-3/4/5). Recompute
185
+ * each record's `contentHash` and `entryHash` from the SAME injected
186
+ * {@link HashFunction} and the chain rule, and check the links, reporting the
187
+ * FIRST break (0-based index + reason) or `{ intact: true }`.
188
+ *
189
+ * Needs NO secret (integrity, not confidentiality) — anyone with the ordered
190
+ * records + the hash function can re-verify. Pass the records for ONE tenant,
191
+ * ordered by `sequenceNumber` ascending (e.g. from
192
+ * {@link import('./ports.js').AuditEventStore.readChain}). An empty chain is
193
+ * vacuously intact.
194
+ *
195
+ * Break kinds, in the order they are checked per record:
196
+ * - `tenant_mismatch` — a record's `tenantId` ≠ `records[0].tenantId`: the chain
197
+ * is contractually SINGLE-tenant, so a foreign-tenant
198
+ * record spliced in (e.g. to mask a deletion) is rejected
199
+ * BEFORE any hash math, even if it self-verifies (AC-5);
200
+ * - `sequence_gap` — `sequenceNumber` is not `previousSequence + 1` (starting
201
+ * at `0`): a deletion or reorder shifted positions;
202
+ * - `prev_mismatch` — `prevHash` ≠ the prior record's recomputed `entryHash`
203
+ * (or ≠ {@link GENESIS} for index 0): a link was cut,
204
+ * a record was removed, or two records were swapped;
205
+ * - `content_mismatch` — the recomputed `contentHash`/`entryHash` ≠ the stored
206
+ * ones: a field of the record was mutated.
207
+ *
208
+ * @param records An ordered, single-tenant chain (sequence ascending).
209
+ * @param hash The SAME deterministic hash used to write the chain.
210
+ */
211
+ function verifyChain(records, hash) {
212
+ let expectedPrevHash = exports.GENESIS;
213
+ let expectedSequence = 0;
214
+ // The chain is contractually SINGLE-tenant. Pin the expected tenant to the first
215
+ // record's; any later record with a different `tenantId` is a cross-tenant splice
216
+ // (a foreign record chained on at the right sequence can self-verify) and MUST be
217
+ // rejected. An empty array has no tenant → vacuously intact (loop does not run).
218
+ const expectedTenantId = records.length > 0 ? records[0]?.tenantId : undefined;
219
+ for (let i = 0; i < records.length; i++) {
220
+ const record = records[i];
221
+ if (record === undefined) {
222
+ // A sparse/holey array is itself a corruption of the chain — treat the hole
223
+ // as a break at its index rather than dereferencing undefined.
224
+ return { intact: false, brokenIndex: i, reason: 'sequence_gap' };
225
+ }
226
+ // (0) TENANT UNIFORMITY (AC-5): every record must belong to the SAME tenant as
227
+ // the first. A foreign-tenant record — even one crafted to chain cleanly onto
228
+ // the prior entryHash at the right sequence — is a cross-tenant splice and is
229
+ // rejected here, before the hash checks that it would otherwise pass.
230
+ if (record.tenantId !== expectedTenantId) {
231
+ return { intact: false, brokenIndex: i, reason: 'tenant_mismatch' };
232
+ }
233
+ // (a) ORDER: sequence must be dense + monotonic from 0. A gap/reorder here
234
+ // means a record was removed or moved (AC-4).
235
+ if (record.sequenceNumber !== expectedSequence) {
236
+ return { intact: false, brokenIndex: i, reason: 'sequence_gap' };
237
+ }
238
+ // (b) LINK: prevHash must equal the prior record's entryHash (GENESIS at 0).
239
+ // A cut link means a record was deleted/swapped/inserted (AC-4/5) — this also
240
+ // catches an attempt to "borrow" another tenant's hash (AC-5): a foreign
241
+ // prevHash won't match this chain's recomputed prior entryHash.
242
+ if (record.prevHash !== expectedPrevHash) {
243
+ return { intact: false, brokenIndex: i, reason: 'prev_mismatch' };
244
+ }
245
+ // (c) CONTENT + BINDING: recompute from the record's OWN stored fields with
246
+ // the SAME hash. If a field was mutated, the recomputed contentHash (and thus
247
+ // entryHash) diverges from what is stored (AC-3).
248
+ const cleanEvent = {
249
+ type: record.type,
250
+ occurredAtMs: record.occurredAtMs,
251
+ actorId: record.actorId,
252
+ tenantId: record.tenantId,
253
+ ...(record.action !== undefined ? { action: record.action } : {}),
254
+ ...(record.resource !== undefined ? { resource: record.resource } : {}),
255
+ ...(record.decision !== undefined ? { decision: record.decision } : {}),
256
+ ...(record.attributes !== undefined ? { attributes: record.attributes } : {}),
257
+ };
258
+ const recomputedContentHash = hash.hash((0, canonicalize_js_1.canonicalizeEvent)(cleanEvent));
259
+ const recomputedEntryHash = hash.hash(entryPreimage(recomputedContentHash, record.prevHash, record.sequenceNumber));
260
+ if (recomputedContentHash !== record.contentHash ||
261
+ recomputedEntryHash !== record.entryHash) {
262
+ return { intact: false, brokenIndex: i, reason: 'content_mismatch' };
263
+ }
264
+ // Advance the expected link/sequence to THIS record's recomputed entryHash.
265
+ expectedPrevHash = recomputedEntryHash;
266
+ expectedSequence = record.sequenceNumber + 1;
267
+ }
268
+ return { intact: true };
269
+ }
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ /**
3
+ * **Canonical event serialization** — the load-bearing determinism at the heart
4
+ * of tamper-evidence (§3.1, AC-6).
5
+ *
6
+ * `contentHash = hash(canonicalizeEvent(event))`. For the hash to be a stable
7
+ * fingerprint, the SAME logical event MUST serialize to BYTE-IDENTICAL output
8
+ * regardless of the insertion order of its attribute keys — otherwise two
9
+ * equivalent events hash differently and the write path and the independent
10
+ * verification path disagree, DEFEATING tamper-detection.
11
+ *
12
+ * `JSON.stringify` alone is INSUFFICIENT: it preserves object key INSERTION
13
+ * order, so `{a,b}` and `{b,a}` stringify differently. This module therefore does
14
+ * a RECURSIVE, KEY-SORTED walk producing a deterministic string, stable across:
15
+ * - object key order (keys emitted sorted);
16
+ * - nested objects/arrays (recursed, arrays keep their order as order IS data);
17
+ * - the `Decision`/`Action`/`Resource` sub-objects (they are plain objects →
18
+ * handled by the same recursive rule, no special-casing needed).
19
+ *
20
+ * PURE + DETERMINISTIC — no I/O, no clock, no randomness, no state. ADR-0003:
21
+ * framework-agnostic — no framework / HTTP / DB / node imports.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.canonicalizeEvent = canonicalizeEvent;
25
+ const errors_js_1 = require("./errors.js");
26
+ const walk_js_1 = require("./walk.js");
27
+ /**
28
+ * The ordered top-level fields of an {@link AuditEvent} that participate in the
29
+ * content hash. Listed EXPLICITLY (not derived from `Object.keys`) so the content
30
+ * fingerprint is stable even if the event object is built with a different key
31
+ * order, and so engine-only metadata (sequence/hashes/stamp) never leaks into the
32
+ * content hash. `attributes` is canonicalized recursively (key-sorted).
33
+ *
34
+ * ⛔ Deliberately EXCLUDES `recordedAtMs` (engine provenance, AC-9) and all chain
35
+ * metadata — the content hash fingerprints the CALLER's event only.
36
+ */
37
+ const CONTENT_FIELDS = [
38
+ 'type',
39
+ 'occurredAtMs',
40
+ 'actorId',
41
+ 'tenantId',
42
+ 'action',
43
+ 'resource',
44
+ 'decision',
45
+ 'attributes',
46
+ ];
47
+ /**
48
+ * Deterministically serialize an arbitrary JSON-ish value with object keys SORTED
49
+ * recursively. Arrays keep their element order (order is semantically meaningful);
50
+ * objects emit `{ "k":<canon>,... }` with keys in ascending `<` order.
51
+ *
52
+ * Encoding notes (chosen for stability, not readability). Every JS value type is
53
+ * handled EXPLICITLY — NONE reaches a raw `TypeError` mid-hash. Legitimate JSON-ish
54
+ * values are NORMALIZED; genuinely non-serializable values are REJECTED with a
55
+ * TYPED {@link AuditValidationError} (never an untyped throw / `JSON.stringify`
56
+ * crash on a `bigint`):
57
+ * - `undefined` → the token `null` (JSON has no `undefined`; treating it as null
58
+ * keeps "key absent" and "key present but undefined" indistinguishable, which
59
+ * is correct — neither carries information);
60
+ * - a non-finite number (`NaN`/`±Infinity`) → the token `null` (matches
61
+ * `JSON.stringify`), so it can never introduce non-determinism;
62
+ * - `Date` → a COLLISION-FREE STRUCTURAL tag ({@link specialLeafTag} in
63
+ * `./walk.ts`): `{"__shieldType":"date","v":"<ms>"}` (`getTime()`; an invalid
64
+ * Date → `v:"null"`). This is an OBJECT shape a plain string value can NEVER
65
+ * serialize to — a plain string `"date:0"` serializes as the JSON string
66
+ * `"date:0"`, which cannot equal the object form — so the previous string-prefix
67
+ * tag collision (a Date and the literal `"date:0"` hashing identically) is now
68
+ * structurally impossible (round-2 Finding D);
69
+ * - `-0` → normalized to `0`; `NaN` / `±Infinity` → the bare `null` token (both
70
+ * inline, matching `JSON.stringify` semantics). These are BARE JSON tokens, not
71
+ * quoted strings, so a plain string value (`"0"`/`"null"`, which JSON-encode to
72
+ * the QUOTED forms) can never collide with them — no structural tag needed;
73
+ * - `bigint` / `symbol` / `function` → REJECTED with a typed
74
+ * {@link AuditValidationError} (`reason: 'unserializable_attribute'`). A `bigint`
75
+ * passes `AuditEvent`'s `Record<string, unknown>` validation but has no
76
+ * unambiguous, `JSON.stringify`-safe canonical form; surfacing it as a TYPED
77
+ * rejection at hash time (rather than a raw `TypeError`) is the secure bar — the
78
+ * emitting adapter fixes the call site instead of seeing a leaky internal crash;
79
+ * - a CYCLIC / pathologically-deep object graph → REJECTED with a typed
80
+ * {@link AuditValidationError} (`reason: 'cyclic_attribute'`) via the shared
81
+ * visited-`WeakSet` + depth guard ({@link guardDescent}), never an untyped
82
+ * `RangeError` from stack overflow mid-hash;
83
+ * - remaining primitives (string / finite number / boolean / null) via
84
+ * `JSON.stringify` (stable and sufficient).
85
+ *
86
+ * ⛔ DESCEND-SET PARITY: the object/array recursion here uses the SHARED
87
+ * {@link isDescendableObject} predicate — the SAME one the secret stripper
88
+ * (`./sensitive.ts`) uses — so the two walkers descend the EXACT same objects
89
+ * (regardless of prototype: a null-proto or class-instance object is descended by
90
+ * both). This is the invariant that prevents a value being hashed-but-not-stripped.
91
+ */
92
+ function canonicalizeValue(value, visited, depth) {
93
+ if (value === undefined || value === null) {
94
+ return 'null';
95
+ }
96
+ if (typeof value === 'bigint' || typeof value === 'symbol' || typeof value === 'function') {
97
+ // Non-serializable for a deterministic content hash → TYPED rejection (never a
98
+ // raw TypeError from JSON.stringify(bigint) mid-hash). Carries NO value (the
99
+ // reason names the invariant; a value could be a secret — see errors.ts).
100
+ throw new errors_js_1.AuditValidationError('unserializable_attribute');
101
+ }
102
+ // Collision-free STRUCTURAL tag for a Date leaf — an object shape a plain string
103
+ // can never serialize to (closes the Date-vs-"date:0" collision, Finding D).
104
+ // Recurse into the tag object by the same rule so it is key-sorted like any object.
105
+ const tag = (0, walk_js_1.specialLeafTag)(value);
106
+ if (tag !== undefined) {
107
+ return canonicalizeValue(tag, visited, depth);
108
+ }
109
+ if (Array.isArray(value)) {
110
+ // Order IS data — do NOT sort array elements; recurse each in place. Guard the
111
+ // array itself against a cycle/over-depth before descending its elements.
112
+ (0, walk_js_1.guardDescent)(value, visited, depth);
113
+ visited.add(value);
114
+ try {
115
+ return `[${value.map((v) => canonicalizeValue(v, visited, depth + 1)).join(',')}]`;
116
+ }
117
+ finally {
118
+ visited.delete(value);
119
+ }
120
+ }
121
+ if ((0, walk_js_1.isDescendableObject)(value)) {
122
+ // Descend by the SHARED predicate (regardless of prototype). Guard against a
123
+ // cycle/over-depth, then sort keys so insertion order can't change the bytes.
124
+ // Skip `undefined` values entirely (a key mapping to undefined carries no
125
+ // information and JSON would drop it anyway) — keeping them would only add noise.
126
+ (0, walk_js_1.guardDescent)(value, visited, depth);
127
+ visited.add(value);
128
+ try {
129
+ const obj = value;
130
+ const keys = Object.keys(obj)
131
+ .filter((k) => obj[k] !== undefined)
132
+ .sort();
133
+ const parts = keys.map((k) => `${JSON.stringify(k)}:${canonicalizeValue(obj[k], visited, depth + 1)}`);
134
+ return `{${parts.join(',')}}`;
135
+ }
136
+ finally {
137
+ visited.delete(value);
138
+ }
139
+ }
140
+ if (typeof value === 'number') {
141
+ if (!Number.isFinite(value)) {
142
+ // NaN / ±Infinity are not representable in JSON; normalize to the bare `null`
143
+ // token so they can never introduce non-determinism. A plain string `"null"`
144
+ // JSON-encodes to the QUOTED `"null"`, so it can never collide with this token.
145
+ return 'null';
146
+ }
147
+ // Normalize -0 to 0 explicitly (JSON.stringify already does this; keep it pinned
148
+ // so the two zeros can never diverge). A finite number needs no structural tag.
149
+ return JSON.stringify(value === 0 ? 0 : value);
150
+ }
151
+ // string | boolean → JSON.stringify is stable and sufficient.
152
+ return JSON.stringify(value);
153
+ }
154
+ /**
155
+ * Produce the PURE, DETERMINISTIC, key-ordered canonical string for an
156
+ * {@link AuditEvent}. The SAME event with `attributes` in a different key order
157
+ * yields BYTE-IDENTICAL output (AC-6) — the input to {@link HashFunction.hash}
158
+ * for the record's `contentHash`.
159
+ *
160
+ * Only {@link CONTENT_FIELDS} participate; engine metadata (recordedAtMs,
161
+ * sequence, hashes) is excluded so the content fingerprint reflects the caller's
162
+ * event alone. Absent optional fields are encoded identically to a present-but-
163
+ * `undefined` field, so their presence/absence never changes the bytes.
164
+ *
165
+ * @param event The (already secret-stripped) event to fingerprint.
166
+ * @returns A deterministic canonical serialization suitable for hashing.
167
+ */
168
+ function canonicalizeEvent(event) {
169
+ const bag = event;
170
+ // One visited-set per event walk (a fresh WeakSet, depth 0) backs the shared
171
+ // cycle/over-depth guard so a self-referential attribute graph rejects with a
172
+ // TYPED AuditValidationError('cyclic_attribute') instead of overflowing the stack.
173
+ const visited = new WeakSet();
174
+ const parts = CONTENT_FIELDS.map((field) => `${JSON.stringify(field)}:${canonicalizeValue(bag[field], visited, 0)}`);
175
+ return `{${parts.join(',')}}`;
176
+ }
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ /**
3
+ * Audit engine ERRORS — the typed validation signal for a REJECTED event
4
+ * (attribution / tenant-scope / UTC-time enforcement, §2 / AC-2).
5
+ *
6
+ * Unlike the Session/Authorization engines (which fail CLOSED with a single
7
+ * GENERIC anti-enumeration reason), an audit REJECTION is a caller CONTRACT
8
+ * violation, not a security oracle — there is no resource-existence to protect by
9
+ * genericizing it. So this error names WHICH invariant failed (missing actor /
10
+ * tenant / invalid time) to help the emitting adapter fix its call site, WITHOUT
11
+ * ever echoing an attribute VALUE (a secret could ride in there).
12
+ *
13
+ * ⛔ This is thrown BEFORE anything is persisted — a rejected event is never
14
+ * stored under a blank actor (AC-2). It is distinct from a STORE-APPEND failure,
15
+ * which the engine lets PROPAGATE unchanged (AC-11) so the caller sees the real
16
+ * cause.
17
+ *
18
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.AuditValidationError = void 0;
22
+ /**
23
+ * Thrown by `record()` when an {@link import('./index.js').AuditEvent} fails the
24
+ * attribution / tenant-scope / UTC-time gate (AC-2): a blank/absent `actorId`, a
25
+ * blank/absent `tenantId`, or a non-finite `occurredAtMs`; ALSO thrown when an
26
+ * attribute value is non-serializable for the content hash (`bigint`/`symbol`/
27
+ * `function` → `unserializable_attribute`) or CYCLIC/over-deep (`cyclic_attribute`),
28
+ * so a bad value surfaces as a TYPED rejection rather than a raw `TypeError` /
29
+ * `RangeError` mid-hash. Names the failing invariant
30
+ * ({@link reason}) for the emitting adapter; NEVER carries an attribute value (no
31
+ * secret leak).
32
+ */
33
+ class AuditValidationError extends Error {
34
+ /** The specific invariant that failed (for the emitting adapter to fix). */
35
+ reason;
36
+ constructor(reason) {
37
+ super(`audit_event_rejected:${reason}`);
38
+ this.name = 'AuditValidationError';
39
+ this.reason = reason;
40
+ // Preserve the prototype chain when compiled down-level so `instanceof` works.
41
+ Object.setPrototypeOf(this, AuditValidationError.prototype);
42
+ }
43
+ }
44
+ exports.AuditValidationError = AuditValidationError;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /**
3
+ * Engine seam: **Audit** — records every decision that matters.
4
+ *
5
+ * Immutably and attributably records decisions and lifecycle events
6
+ * (010_Architecture §6). This seam names the sink contract only; the immutable
7
+ * store and retention are a later layer.
8
+ *
9
+ * TYPES / INTERFACES ONLY. ADR-0003: framework-agnostic.
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
23
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ // --- Engine implementation behind the FROZEN seam above (Layer 9) -------------
27
+ // APPEND-ONLY re-exports (mirrors identity/session/authorization barrels).
28
+ // Nothing above this line changes; the engine is added as SIBLING files.
29
+ // - the injected PORTs (hash / append-only store / clock) + the persisted record shape:
30
+ __exportStar(require("./ports.js"), exports);
31
+ // - the pure, key-ordered canonical serialization (determinism = tamper-evidence):
32
+ __exportStar(require("./canonicalize.js"), exports);
33
+ // - the default sensitive-key denylist + the no-secret-leak stripper:
34
+ __exportStar(require("./sensitive.js"), exports);
35
+ // - the typed validation-rejection error (attribution/tenant/UTC-time gate):
36
+ __exportStar(require("./errors.js"), exports);
37
+ // - the tamper-evident recorder `createAuditRecorder` (IS an AuditSink) + the pure
38
+ // `verifyChain` primitive + the GENESIS chain constant:
39
+ __exportStar(require("./audit-recorder.js"), exports);
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ /**
3
+ * The Audit engine **PORTS** — the framework-agnostic contracts the
4
+ * `createAuditRecorder` engine (`./audit-recorder.ts`) uses to HASH content,
5
+ * PERSIST records append-only, and READ the clock, WITHOUT the engine ever
6
+ * knowing which crypto / DB backs them.
7
+ *
8
+ * ADR-0003 (zero-dep Core): every concrete adapter (`node:crypto` SHA-256, the
9
+ * append-only MariaDB `shield_audit` table) is a real runtime dependency and
10
+ * CANNOT live here. The Core defines only these interfaces; `@astram/guard`
11
+ * ships the concretes and INJECTS them into `createAuditRecorder(...)`. This keeps
12
+ * `@astram/core` at ZERO runtime dependencies (the load-bearing invariant) while
13
+ * the substrate stays swappable.
14
+ *
15
+ * ⛔ SECURITY — the audit engine records for INTEGRITY, not confidentiality. It
16
+ * NEVER persists a secret value (a denylist strips secret-bearing keys before a
17
+ * record is built — see `./sensitive.ts`), and no port here is permitted to LOG
18
+ * its input. The hash is a fingerprint for tamper-detection, never a place to
19
+ * stash a secret.
20
+ *
21
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ // The Clock PORT (UTC epoch ms) — injected so `recordedAtMs` stamping is
25
+ // deterministic in tests; re-exported from `../session/ports.ts` at the top of
26
+ // this file (a single shared `Clock` contract, no duplicate barrel export).
27
+ // Concrete: `SystemClock` (`Date.now`) in `@astram/guard`.