@astram/core 0.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.
- package/LICENSE +21 -0
- package/README.md +47 -0
- package/dist/admin/admin-service.d.ts +221 -0
- package/dist/admin/admin-service.d.ts.map +1 -0
- package/dist/admin/admin-service.js +155 -0
- package/dist/admin/admin-service.js.map +1 -0
- package/dist/admin/command/grants.d.ts +40 -0
- package/dist/admin/command/grants.d.ts.map +1 -0
- package/dist/admin/command/grants.js +196 -0
- package/dist/admin/command/grants.js.map +1 -0
- package/dist/admin/command/index.d.ts +23 -0
- package/dist/admin/command/index.d.ts.map +1 -0
- package/dist/admin/command/index.js +23 -0
- package/dist/admin/command/index.js.map +1 -0
- package/dist/admin/command/invitations.d.ts +72 -0
- package/dist/admin/command/invitations.d.ts.map +1 -0
- package/dist/admin/command/invitations.js +241 -0
- package/dist/admin/command/invitations.js.map +1 -0
- package/dist/admin/command/permissions.d.ts +33 -0
- package/dist/admin/command/permissions.d.ts.map +1 -0
- package/dist/admin/command/permissions.js +67 -0
- package/dist/admin/command/permissions.js.map +1 -0
- package/dist/admin/command/pipeline.d.ts +79 -0
- package/dist/admin/command/pipeline.d.ts.map +1 -0
- package/dist/admin/command/pipeline.js +106 -0
- package/dist/admin/command/pipeline.js.map +1 -0
- package/dist/admin/command/policies.d.ts +50 -0
- package/dist/admin/command/policies.d.ts.map +1 -0
- package/dist/admin/command/policies.js +219 -0
- package/dist/admin/command/policies.js.map +1 -0
- package/dist/admin/command/service-accounts.d.ts +58 -0
- package/dist/admin/command/service-accounts.d.ts.map +1 -0
- package/dist/admin/command/service-accounts.js +272 -0
- package/dist/admin/command/service-accounts.js.map +1 -0
- package/dist/admin/command/service.d.ts +65 -0
- package/dist/admin/command/service.d.ts.map +1 -0
- package/dist/admin/command/service.js +128 -0
- package/dist/admin/command/service.js.map +1 -0
- package/dist/admin/command/tiers.d.ts +40 -0
- package/dist/admin/command/tiers.d.ts.map +1 -0
- package/dist/admin/command/tiers.js +79 -0
- package/dist/admin/command/tiers.js.map +1 -0
- package/dist/admin/index.d.ts +36 -0
- package/dist/admin/index.d.ts.map +1 -0
- package/dist/admin/index.js +63 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/admin/ports.d.ts +288 -0
- package/dist/admin/ports.d.ts.map +1 -0
- package/dist/admin/ports.js +39 -0
- package/dist/admin/ports.js.map +1 -0
- package/dist/admin/query/audit-view.d.ts +52 -0
- package/dist/admin/query/audit-view.d.ts.map +1 -0
- package/dist/admin/query/audit-view.js +84 -0
- package/dist/admin/query/audit-view.js.map +1 -0
- package/dist/admin/query/catalog.d.ts +70 -0
- package/dist/admin/query/catalog.d.ts.map +1 -0
- package/dist/admin/query/catalog.js +169 -0
- package/dist/admin/query/catalog.js.map +1 -0
- package/dist/admin/query/explain.d.ts +52 -0
- package/dist/admin/query/explain.d.ts.map +1 -0
- package/dist/admin/query/explain.js +145 -0
- package/dist/admin/query/explain.js.map +1 -0
- package/dist/admin/query/index.d.ts +45 -0
- package/dist/admin/query/index.d.ts.map +1 -0
- package/dist/admin/query/index.js +58 -0
- package/dist/admin/query/index.js.map +1 -0
- package/dist/admin/query/simulate.d.ts +42 -0
- package/dist/admin/query/simulate.d.ts.map +1 -0
- package/dist/admin/query/simulate.js +91 -0
- package/dist/admin/query/simulate.js.map +1 -0
- package/dist/admin/safeguards-impl.d.ts +67 -0
- package/dist/admin/safeguards-impl.d.ts.map +1 -0
- package/dist/admin/safeguards-impl.js +318 -0
- package/dist/admin/safeguards-impl.js.map +1 -0
- package/dist/admin/safeguards.d.ts +89 -0
- package/dist/admin/safeguards.d.ts.map +1 -0
- package/dist/admin/safeguards.js +91 -0
- package/dist/admin/safeguards.js.map +1 -0
- package/dist/admin/types.d.ts +485 -0
- package/dist/admin/types.d.ts.map +1 -0
- package/dist/admin/types.js +38 -0
- package/dist/admin/types.js.map +1 -0
- package/dist/audit/audit-recorder.d.ts +129 -0
- package/dist/audit/audit-recorder.d.ts.map +1 -0
- package/dist/audit/audit-recorder.js +265 -0
- package/dist/audit/audit-recorder.js.map +1 -0
- package/dist/audit/canonicalize.d.ts +38 -0
- package/dist/audit/canonicalize.d.ts.map +1 -0
- package/dist/audit/canonicalize.js +174 -0
- package/dist/audit/canonicalize.js.map +1 -0
- package/dist/audit/errors.d.ts +56 -0
- package/dist/audit/errors.d.ts.map +1 -0
- package/dist/audit/errors.js +41 -0
- package/dist/audit/errors.js.map +1 -0
- package/dist/audit/index.d.ts +45 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/index.js +24 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/ports.d.ts +131 -0
- package/dist/audit/ports.d.ts.map +1 -0
- package/dist/audit/ports.js +27 -0
- package/dist/audit/ports.js.map +1 -0
- package/dist/audit/sensitive.d.ts +68 -0
- package/dist/audit/sensitive.d.ts.map +1 -0
- package/dist/audit/sensitive.js +159 -0
- package/dist/audit/sensitive.js.map +1 -0
- package/dist/audit/walk.d.ts +109 -0
- package/dist/audit/walk.d.ts.map +1 -0
- package/dist/audit/walk.js +117 -0
- package/dist/audit/walk.js.map +1 -0
- package/dist/authentication/authenticator.d.ts +74 -0
- package/dist/authentication/authenticator.d.ts.map +1 -0
- package/dist/authentication/authenticator.js +208 -0
- package/dist/authentication/authenticator.js.map +1 -0
- package/dist/authentication/credential-resolver.d.ts +76 -0
- package/dist/authentication/credential-resolver.d.ts.map +1 -0
- package/dist/authentication/credential-resolver.js +21 -0
- package/dist/authentication/credential-resolver.js.map +1 -0
- package/dist/authentication/index.d.ts +52 -0
- package/dist/authentication/index.d.ts.map +1 -0
- package/dist/authentication/index.js +27 -0
- package/dist/authentication/index.js.map +1 -0
- package/dist/authentication/password-hasher.d.ts +41 -0
- package/dist/authentication/password-hasher.d.ts.map +1 -0
- package/dist/authentication/password-hasher.js +21 -0
- package/dist/authentication/password-hasher.js.map +1 -0
- package/dist/authentication/totp.d.ts +101 -0
- package/dist/authentication/totp.d.ts.map +1 -0
- package/dist/authentication/totp.js +151 -0
- package/dist/authentication/totp.js.map +1 -0
- package/dist/authorization/cross-tenant/grant-evaluator.d.ts +90 -0
- package/dist/authorization/cross-tenant/grant-evaluator.d.ts.map +1 -0
- package/dist/authorization/cross-tenant/grant-evaluator.js +165 -0
- package/dist/authorization/cross-tenant/grant-evaluator.js.map +1 -0
- package/dist/authorization/decision-authority.d.ts +212 -0
- package/dist/authorization/decision-authority.d.ts.map +1 -0
- package/dist/authorization/decision-authority.js +200 -0
- package/dist/authorization/decision-authority.js.map +1 -0
- package/dist/authorization/default-gates.d.ts +41 -0
- package/dist/authorization/default-gates.d.ts.map +1 -0
- package/dist/authorization/default-gates.js +47 -0
- package/dist/authorization/default-gates.js.map +1 -0
- package/dist/authorization/delegation/operation-identity.d.ts +132 -0
- package/dist/authorization/delegation/operation-identity.d.ts.map +1 -0
- package/dist/authorization/delegation/operation-identity.js +220 -0
- package/dist/authorization/delegation/operation-identity.js.map +1 -0
- package/dist/authorization/errors.d.ts +54 -0
- package/dist/authorization/errors.d.ts.map +1 -0
- package/dist/authorization/errors.js +63 -0
- package/dist/authorization/errors.js.map +1 -0
- package/dist/authorization/gates/object-type.d.ts +63 -0
- package/dist/authorization/gates/object-type.d.ts.map +1 -0
- package/dist/authorization/gates/object-type.js +177 -0
- package/dist/authorization/gates/object-type.js.map +1 -0
- package/dist/authorization/gates/tenant.d.ts +50 -0
- package/dist/authorization/gates/tenant.d.ts.map +1 -0
- package/dist/authorization/gates/tenant.js +87 -0
- package/dist/authorization/gates/tenant.js.map +1 -0
- package/dist/authorization/gates/wiring.d.ts +57 -0
- package/dist/authorization/gates/wiring.d.ts.map +1 -0
- package/dist/authorization/gates/wiring.js +56 -0
- package/dist/authorization/gates/wiring.js.map +1 -0
- package/dist/authorization/index.d.ts +136 -0
- package/dist/authorization/index.d.ts.map +1 -0
- package/dist/authorization/index.js +82 -0
- package/dist/authorization/index.js.map +1 -0
- package/dist/authorization/ports.d.ts +271 -0
- package/dist/authorization/ports.d.ts.map +1 -0
- package/dist/authorization/ports.js +36 -0
- package/dist/authorization/ports.js.map +1 -0
- package/dist/authorization/reason-codes.d.ts +75 -0
- package/dist/authorization/reason-codes.d.ts.map +1 -0
- package/dist/authorization/reason-codes.js +98 -0
- package/dist/authorization/reason-codes.js.map +1 -0
- package/dist/authorization/record/permit-tier.d.ts +57 -0
- package/dist/authorization/record/permit-tier.d.ts.map +1 -0
- package/dist/authorization/record/permit-tier.js +79 -0
- package/dist/authorization/record/permit-tier.js.map +1 -0
- package/dist/authorization/record/rule-evaluator.d.ts +116 -0
- package/dist/authorization/record/rule-evaluator.d.ts.map +1 -0
- package/dist/authorization/record/rule-evaluator.js +125 -0
- package/dist/authorization/record/rule-evaluator.js.map +1 -0
- package/dist/authorization/record/shares.d.ts +70 -0
- package/dist/authorization/record/shares.d.ts.map +1 -0
- package/dist/authorization/record/shares.js +107 -0
- package/dist/authorization/record/shares.js.map +1 -0
- package/dist/identity/broker.d.ts +59 -0
- package/dist/identity/broker.d.ts.map +1 -0
- package/dist/identity/broker.js +135 -0
- package/dist/identity/broker.js.map +1 -0
- package/dist/identity/claim-mapper.d.ts +84 -0
- package/dist/identity/claim-mapper.d.ts.map +1 -0
- package/dist/identity/claim-mapper.js +48 -0
- package/dist/identity/claim-mapper.js.map +1 -0
- package/dist/identity/index.d.ts +60 -0
- package/dist/identity/index.d.ts.map +1 -0
- package/dist/identity/index.js +24 -0
- package/dist/identity/index.js.map +1 -0
- package/dist/identity/internal-adapter.d.ts +54 -0
- package/dist/identity/internal-adapter.d.ts.map +1 -0
- package/dist/identity/internal-adapter.js +88 -0
- package/dist/identity/internal-adapter.js.map +1 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +48 -0
- package/dist/index.js.map +1 -0
- package/dist/metadata/completeness.d.ts +136 -0
- package/dist/metadata/completeness.d.ts.map +1 -0
- package/dist/metadata/completeness.js +106 -0
- package/dist/metadata/completeness.js.map +1 -0
- package/dist/metadata/dependencies.d.ts +114 -0
- package/dist/metadata/dependencies.d.ts.map +1 -0
- package/dist/metadata/dependencies.js +105 -0
- package/dist/metadata/dependencies.js.map +1 -0
- package/dist/metadata/index.d.ts +153 -0
- package/dist/metadata/index.d.ts.map +1 -0
- package/dist/metadata/index.js +51 -0
- package/dist/metadata/index.js.map +1 -0
- package/dist/metadata/registry.d.ts +23 -0
- package/dist/metadata/registry.d.ts.map +1 -0
- package/dist/metadata/registry.js +204 -0
- package/dist/metadata/registry.js.map +1 -0
- package/dist/risk/evaluator.d.ts +76 -0
- package/dist/risk/evaluator.d.ts.map +1 -0
- package/dist/risk/evaluator.js +59 -0
- package/dist/risk/evaluator.js.map +1 -0
- package/dist/risk/index.d.ts +40 -0
- package/dist/risk/index.d.ts.map +1 -0
- package/dist/risk/index.js +20 -0
- package/dist/risk/index.js.map +1 -0
- package/dist/risk/risk-engine.d.ts +76 -0
- package/dist/risk/risk-engine.d.ts.map +1 -0
- package/dist/risk/risk-engine.js +287 -0
- package/dist/risk/risk-engine.js.map +1 -0
- package/dist/risk/signals.d.ts +60 -0
- package/dist/risk/signals.d.ts.map +1 -0
- package/dist/risk/signals.js +104 -0
- package/dist/risk/signals.js.map +1 -0
- package/dist/risk/thresholds.d.ts +54 -0
- package/dist/risk/thresholds.d.ts.map +1 -0
- package/dist/risk/thresholds.js +60 -0
- package/dist/risk/thresholds.js.map +1 -0
- package/dist/session/index.d.ts +47 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/lifetimes.d.ts +50 -0
- package/dist/session/lifetimes.d.ts.map +1 -0
- package/dist/session/lifetimes.js +67 -0
- package/dist/session/lifetimes.js.map +1 -0
- package/dist/session/ports.d.ts +266 -0
- package/dist/session/ports.d.ts.map +1 -0
- package/dist/session/ports.js +23 -0
- package/dist/session/ports.js.map +1 -0
- package/dist/session/session-authority.d.ts +97 -0
- package/dist/session/session-authority.d.ts.map +1 -0
- package/dist/session/session-authority.js +393 -0
- package/dist/session/session-authority.js.map +1 -0
- package/package.json +32 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Audit **engine** — the body behind the FROZEN {@link AuditSink} seam
|
|
3
|
+
* (`./index.ts`). Validates → strips secrets → stamps → hash-CHAINS → appends
|
|
4
|
+
* ONE immutable, attributable, tenant-scoped audit record per event, so any later
|
|
5
|
+
* deletion / reordering / mutation is DETECTABLE ({@link verifyChain}).
|
|
6
|
+
*
|
|
7
|
+
* Mirrors the Session engine (`../session/session-authority.ts`): a pure
|
|
8
|
+
* `createAuditRecorder(...)` factory over INJECTED ports (store / hash / clock),
|
|
9
|
+
* a stateless impl, and a returned object that IS the frozen seam (drop-in
|
|
10
|
+
* `AuditSink`).
|
|
11
|
+
*
|
|
12
|
+
* ── THE TAMPER-EVIDENCE CORE (§3): a PER-TENANT hash chain.
|
|
13
|
+
* Each stored record carries `contentHash = H(canonicalize(cleanEvent))`,
|
|
14
|
+
* `prevHash` = the prior record's `entryHash` FOR THE SAME TENANT ({@link GENESIS}
|
|
15
|
+
* for a tenant's first record), and `entryHash = H(contentHash ‖ prevHash ‖
|
|
16
|
+
* sequenceNumber)`. Order is bound in via `sequenceNumber`, so deleting or
|
|
17
|
+
* reordering a record breaks EVERY downstream `entryHash`. The chain is
|
|
18
|
+
* per-tenant — a tamper in tenant A cannot be masked by tenant B's events, and
|
|
19
|
+
* B stays verifiable when A is broken (AC-5).
|
|
20
|
+
*
|
|
21
|
+
* ── APPEND-ONLY IS STRUCTURAL: the returned object exposes ONLY `record()` (the
|
|
22
|
+
* seam) — no update/delete path anywhere in the engine surface (AC-1). The
|
|
23
|
+
* store port likewise has no mutate/delete method (`./ports.ts`).
|
|
24
|
+
*
|
|
25
|
+
* ── FAIL-LOUD, NOT FAIL-CLOSED: unlike Session (which genericizes every failure),
|
|
26
|
+
* the audit engine must NEVER silently drop an event. A validation failure
|
|
27
|
+
* THROWS a typed {@link AuditValidationError} (AC-2); a store-append failure is
|
|
28
|
+
* let PROPAGATE unchanged (AC-11) so the emitting adapter — not the engine —
|
|
29
|
+
* decides whether the audited operation proceeds. The engine catches NOTHING on
|
|
30
|
+
* the write path.
|
|
31
|
+
*
|
|
32
|
+
* ── CONCURRENCY ASSUMPTION: `record()` reads the tenant's chain tail, then
|
|
33
|
+
* appends the successor. Correctness of the per-tenant `sequenceNumber` +
|
|
34
|
+
* `prevHash` link assumes the store SERIALIZES appends per tenant (the adapter's
|
|
35
|
+
* append-only table has a per-tenant unique `(tenantId, sequenceNumber)` key, so
|
|
36
|
+
* a racing duplicate sequence fails the constraint and the append rejects —
|
|
37
|
+
* surfacing to the caller rather than silently forking the chain). The pure
|
|
38
|
+
* engine does not itself lock; it relies on that store guarantee (documented on
|
|
39
|
+
* {@link import('./ports.js').AuditEventStore}).
|
|
40
|
+
*
|
|
41
|
+
* ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
|
|
42
|
+
*/
|
|
43
|
+
import type { AuditSink } from './index.js';
|
|
44
|
+
import type { AuditEventStore, Clock, HashFunction, StoredAuditRecord } from './ports.js';
|
|
45
|
+
/**
|
|
46
|
+
* The fixed genesis `prevHash` for the FIRST record of every tenant's chain
|
|
47
|
+
* (§3.2). A constant (not a random/per-tenant value) so verification is fully
|
|
48
|
+
* reproducible from the records + the hash function alone — no hidden seed. The
|
|
49
|
+
* `shield:` namespace + `genesis:v1` version keeps it distinct from any real
|
|
50
|
+
* `entryHash` and lets the scheme version later without ambiguity.
|
|
51
|
+
*/
|
|
52
|
+
export declare const GENESIS = "shield:audit:genesis:v1";
|
|
53
|
+
/** Injected capabilities for {@link createAuditRecorder}. */
|
|
54
|
+
export interface AuditRecorderDeps {
|
|
55
|
+
/** Append-only record store PORT (MariaDB adapter in `@astram/guard`). */
|
|
56
|
+
readonly store: AuditEventStore;
|
|
57
|
+
/** Deterministic content/chain hash PORT (SHA-256 adapter). */
|
|
58
|
+
readonly hash: HashFunction;
|
|
59
|
+
/** Clock PORT (UTC epoch ms) — injected for deterministic `recordedAtMs` tests. */
|
|
60
|
+
readonly clock: Clock;
|
|
61
|
+
/**
|
|
62
|
+
* OPTIONAL replacement sensitive-key denylist (case-insensitive substring
|
|
63
|
+
* match). Defaults to {@link DEFAULT_SENSITIVE_DENYLIST}; passing `[]` disables
|
|
64
|
+
* stripping (a documented, caller-owned risk).
|
|
65
|
+
*/
|
|
66
|
+
readonly sensitiveDenylist?: readonly string[];
|
|
67
|
+
}
|
|
68
|
+
/** Options for {@link createAuditRecorder} (mirrors CreateSessionAuthorityOptions). */
|
|
69
|
+
export type CreateAuditRecorderOptions = AuditRecorderDeps;
|
|
70
|
+
/**
|
|
71
|
+
* Wire the injected ports and return an object implementing the FROZEN
|
|
72
|
+
* {@link AuditSink} — the engine's public entry point (mirrors
|
|
73
|
+
* `createSessionAuthority`). The returned value is a drop-in `AuditSink`: its ONLY
|
|
74
|
+
* public mutating method is `record()` (AC-1, no update/delete surface).
|
|
75
|
+
*
|
|
76
|
+
* ── APPEND-ONLY / ISOLATION IS STRUCTURAL (AC-1). The injected ports
|
|
77
|
+
* (`store`/`hash`/`clock`/`denylist`) are captured in THIS closure and are NOT
|
|
78
|
+
* fields on the returned object. A TS `private` field is compile-time-only — at
|
|
79
|
+
* runtime it is an enumerable own-property, so a class instance would leak
|
|
80
|
+
* `sink.store.append(forged)` / `sink.store.readChain(anyTenant)` as an
|
|
81
|
+
* append-only + cross-tenant escape hatch. Returning a frozen bare object whose
|
|
82
|
+
* ONLY own-property is `record` closes that hatch:
|
|
83
|
+
* `Object.getOwnPropertyNames(sink)` === `['record']`, `sink.store` is `undefined`.
|
|
84
|
+
*
|
|
85
|
+
* The independent tamper-detection primitive {@link verifyChain} is a SEPARATE
|
|
86
|
+
* exported pure function (an auditor/adapter verifies a chain it read back; it is
|
|
87
|
+
* not a method on the sink).
|
|
88
|
+
*/
|
|
89
|
+
export declare function createAuditRecorder(deps: AuditRecorderDeps): AuditSink;
|
|
90
|
+
/** Why {@link verifyChain} reports a chain BROKEN. */
|
|
91
|
+
export type ChainBreakReason = 'content_mismatch' | 'prev_mismatch' | 'sequence_gap' | 'tenant_mismatch';
|
|
92
|
+
/** The result of {@link verifyChain}: intact, or the FIRST break (index + reason). */
|
|
93
|
+
export type ChainVerification = {
|
|
94
|
+
readonly intact: true;
|
|
95
|
+
} | {
|
|
96
|
+
readonly intact: false;
|
|
97
|
+
readonly brokenIndex: number;
|
|
98
|
+
readonly reason: ChainBreakReason;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* The PURE, independent TAMPER-DETECTION primitive (§3.4, AC-3/4/5). Recompute
|
|
102
|
+
* each record's `contentHash` and `entryHash` from the SAME injected
|
|
103
|
+
* {@link HashFunction} and the chain rule, and check the links, reporting the
|
|
104
|
+
* FIRST break (0-based index + reason) or `{ intact: true }`.
|
|
105
|
+
*
|
|
106
|
+
* Needs NO secret (integrity, not confidentiality) — anyone with the ordered
|
|
107
|
+
* records + the hash function can re-verify. Pass the records for ONE tenant,
|
|
108
|
+
* ordered by `sequenceNumber` ascending (e.g. from
|
|
109
|
+
* {@link import('./ports.js').AuditEventStore.readChain}). An empty chain is
|
|
110
|
+
* vacuously intact.
|
|
111
|
+
*
|
|
112
|
+
* Break kinds, in the order they are checked per record:
|
|
113
|
+
* - `tenant_mismatch` — a record's `tenantId` ≠ `records[0].tenantId`: the chain
|
|
114
|
+
* is contractually SINGLE-tenant, so a foreign-tenant
|
|
115
|
+
* record spliced in (e.g. to mask a deletion) is rejected
|
|
116
|
+
* BEFORE any hash math, even if it self-verifies (AC-5);
|
|
117
|
+
* - `sequence_gap` — `sequenceNumber` is not `previousSequence + 1` (starting
|
|
118
|
+
* at `0`): a deletion or reorder shifted positions;
|
|
119
|
+
* - `prev_mismatch` — `prevHash` ≠ the prior record's recomputed `entryHash`
|
|
120
|
+
* (or ≠ {@link GENESIS} for index 0): a link was cut,
|
|
121
|
+
* a record was removed, or two records were swapped;
|
|
122
|
+
* - `content_mismatch` — the recomputed `contentHash`/`entryHash` ≠ the stored
|
|
123
|
+
* ones: a field of the record was mutated.
|
|
124
|
+
*
|
|
125
|
+
* @param records An ordered, single-tenant chain (sequence ascending).
|
|
126
|
+
* @param hash The SAME deterministic hash used to write the chain.
|
|
127
|
+
*/
|
|
128
|
+
export declare function verifyChain(records: readonly StoredAuditRecord[], hash: HashFunction): ChainVerification;
|
|
129
|
+
//# sourceMappingURL=audit-recorder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audit-recorder.d.ts","sourceRoot":"","sources":["../../src/audit/audit-recorder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,OAAO,KAAK,EAAc,SAAS,EAAE,MAAM,YAAY,CAAC;AAGxD,OAAO,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAG1F;;;;;;GAMG;AACH,eAAO,MAAM,OAAO,4BAA4B,CAAC;AAcjD,6DAA6D;AAC7D,MAAM,WAAW,iBAAiB;IAChC,0EAA0E;IAC1E,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC;IAChC,+DAA+D;IAC/D,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B,mFAAmF;IACnF,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB;;;;OAIG;IACH,QAAQ,CAAC,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAChD;AAUD,uFAAuF;AACvF,MAAM,MAAM,0BAA0B,GAAG,iBAAiB,CAAC;AAE3D;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,iBAAiB,GAAG,SAAS,CAgGtE;AAED,sDAAsD;AACtD,MAAM,MAAM,gBAAgB,GACxB,kBAAkB,GAClB,eAAe,GACf,cAAc,GACd,iBAAiB,CAAC;AAEtB,sFAAsF;AACtF,MAAM,MAAM,iBAAiB,GACzB;IAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAA;CAAE,GACzB;IAAE,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAA;CAAE,CAAC;AAEhG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,SAAS,iBAAiB,EAAE,EACrC,IAAI,EAAE,YAAY,GACjB,iBAAiB,CAsEnB"}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Audit **engine** — the body behind the FROZEN {@link AuditSink} seam
|
|
3
|
+
* (`./index.ts`). Validates → strips secrets → stamps → hash-CHAINS → appends
|
|
4
|
+
* ONE immutable, attributable, tenant-scoped audit record per event, so any later
|
|
5
|
+
* deletion / reordering / mutation is DETECTABLE ({@link verifyChain}).
|
|
6
|
+
*
|
|
7
|
+
* Mirrors the Session engine (`../session/session-authority.ts`): a pure
|
|
8
|
+
* `createAuditRecorder(...)` factory over INJECTED ports (store / hash / clock),
|
|
9
|
+
* a stateless impl, and a returned object that IS the frozen seam (drop-in
|
|
10
|
+
* `AuditSink`).
|
|
11
|
+
*
|
|
12
|
+
* ── THE TAMPER-EVIDENCE CORE (§3): a PER-TENANT hash chain.
|
|
13
|
+
* Each stored record carries `contentHash = H(canonicalize(cleanEvent))`,
|
|
14
|
+
* `prevHash` = the prior record's `entryHash` FOR THE SAME TENANT ({@link GENESIS}
|
|
15
|
+
* for a tenant's first record), and `entryHash = H(contentHash ‖ prevHash ‖
|
|
16
|
+
* sequenceNumber)`. Order is bound in via `sequenceNumber`, so deleting or
|
|
17
|
+
* reordering a record breaks EVERY downstream `entryHash`. The chain is
|
|
18
|
+
* per-tenant — a tamper in tenant A cannot be masked by tenant B's events, and
|
|
19
|
+
* B stays verifiable when A is broken (AC-5).
|
|
20
|
+
*
|
|
21
|
+
* ── APPEND-ONLY IS STRUCTURAL: the returned object exposes ONLY `record()` (the
|
|
22
|
+
* seam) — no update/delete path anywhere in the engine surface (AC-1). The
|
|
23
|
+
* store port likewise has no mutate/delete method (`./ports.ts`).
|
|
24
|
+
*
|
|
25
|
+
* ── FAIL-LOUD, NOT FAIL-CLOSED: unlike Session (which genericizes every failure),
|
|
26
|
+
* the audit engine must NEVER silently drop an event. A validation failure
|
|
27
|
+
* THROWS a typed {@link AuditValidationError} (AC-2); a store-append failure is
|
|
28
|
+
* let PROPAGATE unchanged (AC-11) so the emitting adapter — not the engine —
|
|
29
|
+
* decides whether the audited operation proceeds. The engine catches NOTHING on
|
|
30
|
+
* the write path.
|
|
31
|
+
*
|
|
32
|
+
* ── CONCURRENCY ASSUMPTION: `record()` reads the tenant's chain tail, then
|
|
33
|
+
* appends the successor. Correctness of the per-tenant `sequenceNumber` +
|
|
34
|
+
* `prevHash` link assumes the store SERIALIZES appends per tenant (the adapter's
|
|
35
|
+
* append-only table has a per-tenant unique `(tenantId, sequenceNumber)` key, so
|
|
36
|
+
* a racing duplicate sequence fails the constraint and the append rejects —
|
|
37
|
+
* surfacing to the caller rather than silently forking the chain). The pure
|
|
38
|
+
* engine does not itself lock; it relies on that store guarantee (documented on
|
|
39
|
+
* {@link import('./ports.js').AuditEventStore}).
|
|
40
|
+
*
|
|
41
|
+
* ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
|
|
42
|
+
*/
|
|
43
|
+
import { canonicalizeEvent } from './canonicalize.js';
|
|
44
|
+
import { AuditValidationError } from './errors.js';
|
|
45
|
+
import { DEFAULT_SENSITIVE_DENYLIST, stripSensitive } from './sensitive.js';
|
|
46
|
+
/**
|
|
47
|
+
* The fixed genesis `prevHash` for the FIRST record of every tenant's chain
|
|
48
|
+
* (§3.2). A constant (not a random/per-tenant value) so verification is fully
|
|
49
|
+
* reproducible from the records + the hash function alone — no hidden seed. The
|
|
50
|
+
* `shield:` namespace + `genesis:v1` version keeps it distinct from any real
|
|
51
|
+
* `entryHash` and lets the scheme version later without ambiguity.
|
|
52
|
+
*/
|
|
53
|
+
export const GENESIS = 'shield:audit:genesis:v1';
|
|
54
|
+
/** The field separator used when composing the `entryHash` preimage. */
|
|
55
|
+
const CHAIN_SEP = '|';
|
|
56
|
+
/**
|
|
57
|
+
* Compose the `entryHash` preimage: `contentHash ‖ prevHash ‖ sequenceNumber`.
|
|
58
|
+
* A single source of truth so the write path and {@link verifyChain} bind order
|
|
59
|
+
* IDENTICALLY (any drift here would make every chain fail verification).
|
|
60
|
+
*/
|
|
61
|
+
function entryPreimage(contentHash, prevHash, sequenceNumber) {
|
|
62
|
+
return `${contentHash}${CHAIN_SEP}${prevHash}${CHAIN_SEP}${sequenceNumber}`;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A non-blank string guard — an actor/tenant id must be a present, non-whitespace
|
|
66
|
+
* string. (`.trim()` catches `' '`, which a bare `length === 0` would miss.)
|
|
67
|
+
*/
|
|
68
|
+
function isNonBlank(value) {
|
|
69
|
+
return typeof value === 'string' && value.trim().length > 0;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Wire the injected ports and return an object implementing the FROZEN
|
|
73
|
+
* {@link AuditSink} — the engine's public entry point (mirrors
|
|
74
|
+
* `createSessionAuthority`). The returned value is a drop-in `AuditSink`: its ONLY
|
|
75
|
+
* public mutating method is `record()` (AC-1, no update/delete surface).
|
|
76
|
+
*
|
|
77
|
+
* ── APPEND-ONLY / ISOLATION IS STRUCTURAL (AC-1). The injected ports
|
|
78
|
+
* (`store`/`hash`/`clock`/`denylist`) are captured in THIS closure and are NOT
|
|
79
|
+
* fields on the returned object. A TS `private` field is compile-time-only — at
|
|
80
|
+
* runtime it is an enumerable own-property, so a class instance would leak
|
|
81
|
+
* `sink.store.append(forged)` / `sink.store.readChain(anyTenant)` as an
|
|
82
|
+
* append-only + cross-tenant escape hatch. Returning a frozen bare object whose
|
|
83
|
+
* ONLY own-property is `record` closes that hatch:
|
|
84
|
+
* `Object.getOwnPropertyNames(sink)` === `['record']`, `sink.store` is `undefined`.
|
|
85
|
+
*
|
|
86
|
+
* The independent tamper-detection primitive {@link verifyChain} is a SEPARATE
|
|
87
|
+
* exported pure function (an auditor/adapter verifies a chain it read back; it is
|
|
88
|
+
* not a method on the sink).
|
|
89
|
+
*/
|
|
90
|
+
export function createAuditRecorder(deps) {
|
|
91
|
+
// Capture the ports in the closure — never expose them off the returned object.
|
|
92
|
+
const store = deps.store;
|
|
93
|
+
const hash = deps.hash;
|
|
94
|
+
const clock = deps.clock;
|
|
95
|
+
const denylist = deps.sensitiveDenylist ?? DEFAULT_SENSITIVE_DENYLIST;
|
|
96
|
+
async function record(event) {
|
|
97
|
+
// ── (1) VALIDATE (AC-2). Reject a malformed event LOUD — never store under a
|
|
98
|
+
// blank actor/tenant or an invalid time. Thrown BEFORE any hashing/append.
|
|
99
|
+
if (event === null || typeof event !== 'object') {
|
|
100
|
+
throw new AuditValidationError('missing_actor');
|
|
101
|
+
}
|
|
102
|
+
if (!isNonBlank(event.actorId)) {
|
|
103
|
+
throw new AuditValidationError('missing_actor');
|
|
104
|
+
}
|
|
105
|
+
if (!isNonBlank(event.tenantId)) {
|
|
106
|
+
throw new AuditValidationError('missing_tenant');
|
|
107
|
+
}
|
|
108
|
+
if (typeof event.occurredAtMs !== 'number' || !Number.isFinite(event.occurredAtMs)) {
|
|
109
|
+
throw new AuditValidationError('invalid_occurred_at');
|
|
110
|
+
}
|
|
111
|
+
// ── (2) STRIP SECRETS (AC-7). No raw secret value reaches the content hash or
|
|
112
|
+
// the store; only stripped key NAMES/PATHS are retained (never values). The
|
|
113
|
+
// stripper RECURSES through nested objects and arrays at every depth.
|
|
114
|
+
const { cleaned, strippedKeys } = stripSensitive(event.attributes, denylist);
|
|
115
|
+
// The event whose CONTENT is fingerprinted — the caller's fields with the
|
|
116
|
+
// attributes replaced by the secret-stripped bag. Engine metadata (sequence,
|
|
117
|
+
// hashes, recordedAtMs) is NOT part of the content hash (see canonicalize).
|
|
118
|
+
const cleanEvent = {
|
|
119
|
+
type: event.type,
|
|
120
|
+
occurredAtMs: event.occurredAtMs,
|
|
121
|
+
actorId: event.actorId,
|
|
122
|
+
tenantId: event.tenantId,
|
|
123
|
+
...(event.action !== undefined ? { action: event.action } : {}),
|
|
124
|
+
...(event.resource !== undefined ? { resource: event.resource } : {}),
|
|
125
|
+
...(event.decision !== undefined ? { decision: event.decision } : {}),
|
|
126
|
+
...(cleaned !== undefined ? { attributes: cleaned } : {}),
|
|
127
|
+
};
|
|
128
|
+
// ── (3) CHAIN (§3, AC-3/4/5). Read this tenant's tail; compute sequence +
|
|
129
|
+
// prevHash from it. Per-tenant: `readChain` only returns THIS tenant's records.
|
|
130
|
+
const chain = await store.readChain(event.tenantId);
|
|
131
|
+
const tail = chain.length > 0 ? chain[chain.length - 1] : undefined;
|
|
132
|
+
const sequenceNumber = tail !== undefined ? tail.sequenceNumber + 1 : 0;
|
|
133
|
+
const prevHash = tail !== undefined ? tail.entryHash : GENESIS;
|
|
134
|
+
const contentHash = hash.hash(canonicalizeEvent(cleanEvent));
|
|
135
|
+
const entryHash = hash.hash(entryPreimage(contentHash, prevHash, sequenceNumber));
|
|
136
|
+
// ── (4) STAMP (AC-9). The engine's own clock — distinct from occurredAtMs.
|
|
137
|
+
const recordedAtMs = clock.nowMs();
|
|
138
|
+
const stored = {
|
|
139
|
+
type: cleanEvent.type,
|
|
140
|
+
occurredAtMs: cleanEvent.occurredAtMs,
|
|
141
|
+
actorId: cleanEvent.actorId,
|
|
142
|
+
tenantId: cleanEvent.tenantId,
|
|
143
|
+
...(cleanEvent.action !== undefined ? { action: cleanEvent.action } : {}),
|
|
144
|
+
...(cleanEvent.resource !== undefined ? { resource: cleanEvent.resource } : {}),
|
|
145
|
+
...(cleanEvent.decision !== undefined ? { decision: cleanEvent.decision } : {}),
|
|
146
|
+
...(cleaned !== undefined ? { attributes: cleaned } : {}),
|
|
147
|
+
...(strippedKeys.length > 0 ? { strippedKeys } : {}),
|
|
148
|
+
sequenceNumber,
|
|
149
|
+
recordedAtMs,
|
|
150
|
+
contentHash,
|
|
151
|
+
prevHash,
|
|
152
|
+
entryHash,
|
|
153
|
+
};
|
|
154
|
+
// ── (5) APPEND (AC-1/11). If the store rejects, let it PROPAGATE — the engine
|
|
155
|
+
// NEVER swallows a failed append (that would silently drop an event). The
|
|
156
|
+
// emitting adapter decides whether the audited operation proceeds.
|
|
157
|
+
await store.append(Object.freeze(stored));
|
|
158
|
+
}
|
|
159
|
+
// The returned sink is a BARE, FROZEN object whose only own enumerable is
|
|
160
|
+
// `record` — no injected port is reachable off it (AC-1 append-only + isolation):
|
|
161
|
+
// • `Object.getOwnPropertyNames(sink)` === ['record'] (no store/hash/clock).
|
|
162
|
+
// • `sink.store` / `sink.hash` / `sink.clock` are `undefined`.
|
|
163
|
+
// • No mutate/delete/edit method anywhere on the surface OR its prototype.
|
|
164
|
+
// The prototype is a minimal `{ record }` (NOT `Object.prototype`) so a
|
|
165
|
+
// prototype-method scan sees ONLY `record`, never `Object.prototype`'s
|
|
166
|
+
// `hasOwnProperty`/`toString`/… — the surface is `record`, and nothing else,
|
|
167
|
+
// whether inspected as own-properties or as prototype methods.
|
|
168
|
+
const sinkProto = { record };
|
|
169
|
+
const sink = Object.create(sinkProto);
|
|
170
|
+
Object.defineProperty(sink, 'record', {
|
|
171
|
+
value: record,
|
|
172
|
+
enumerable: true,
|
|
173
|
+
writable: false,
|
|
174
|
+
configurable: false,
|
|
175
|
+
});
|
|
176
|
+
return Object.freeze(sink);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The PURE, independent TAMPER-DETECTION primitive (§3.4, AC-3/4/5). Recompute
|
|
180
|
+
* each record's `contentHash` and `entryHash` from the SAME injected
|
|
181
|
+
* {@link HashFunction} and the chain rule, and check the links, reporting the
|
|
182
|
+
* FIRST break (0-based index + reason) or `{ intact: true }`.
|
|
183
|
+
*
|
|
184
|
+
* Needs NO secret (integrity, not confidentiality) — anyone with the ordered
|
|
185
|
+
* records + the hash function can re-verify. Pass the records for ONE tenant,
|
|
186
|
+
* ordered by `sequenceNumber` ascending (e.g. from
|
|
187
|
+
* {@link import('./ports.js').AuditEventStore.readChain}). An empty chain is
|
|
188
|
+
* vacuously intact.
|
|
189
|
+
*
|
|
190
|
+
* Break kinds, in the order they are checked per record:
|
|
191
|
+
* - `tenant_mismatch` — a record's `tenantId` ≠ `records[0].tenantId`: the chain
|
|
192
|
+
* is contractually SINGLE-tenant, so a foreign-tenant
|
|
193
|
+
* record spliced in (e.g. to mask a deletion) is rejected
|
|
194
|
+
* BEFORE any hash math, even if it self-verifies (AC-5);
|
|
195
|
+
* - `sequence_gap` — `sequenceNumber` is not `previousSequence + 1` (starting
|
|
196
|
+
* at `0`): a deletion or reorder shifted positions;
|
|
197
|
+
* - `prev_mismatch` — `prevHash` ≠ the prior record's recomputed `entryHash`
|
|
198
|
+
* (or ≠ {@link GENESIS} for index 0): a link was cut,
|
|
199
|
+
* a record was removed, or two records were swapped;
|
|
200
|
+
* - `content_mismatch` — the recomputed `contentHash`/`entryHash` ≠ the stored
|
|
201
|
+
* ones: a field of the record was mutated.
|
|
202
|
+
*
|
|
203
|
+
* @param records An ordered, single-tenant chain (sequence ascending).
|
|
204
|
+
* @param hash The SAME deterministic hash used to write the chain.
|
|
205
|
+
*/
|
|
206
|
+
export function verifyChain(records, hash) {
|
|
207
|
+
let expectedPrevHash = GENESIS;
|
|
208
|
+
let expectedSequence = 0;
|
|
209
|
+
// The chain is contractually SINGLE-tenant. Pin the expected tenant to the first
|
|
210
|
+
// record's; any later record with a different `tenantId` is a cross-tenant splice
|
|
211
|
+
// (a foreign record chained on at the right sequence can self-verify) and MUST be
|
|
212
|
+
// rejected. An empty array has no tenant → vacuously intact (loop does not run).
|
|
213
|
+
const expectedTenantId = records.length > 0 ? records[0]?.tenantId : undefined;
|
|
214
|
+
for (let i = 0; i < records.length; i++) {
|
|
215
|
+
const record = records[i];
|
|
216
|
+
if (record === undefined) {
|
|
217
|
+
// A sparse/holey array is itself a corruption of the chain — treat the hole
|
|
218
|
+
// as a break at its index rather than dereferencing undefined.
|
|
219
|
+
return { intact: false, brokenIndex: i, reason: 'sequence_gap' };
|
|
220
|
+
}
|
|
221
|
+
// (0) TENANT UNIFORMITY (AC-5): every record must belong to the SAME tenant as
|
|
222
|
+
// the first. A foreign-tenant record — even one crafted to chain cleanly onto
|
|
223
|
+
// the prior entryHash at the right sequence — is a cross-tenant splice and is
|
|
224
|
+
// rejected here, before the hash checks that it would otherwise pass.
|
|
225
|
+
if (record.tenantId !== expectedTenantId) {
|
|
226
|
+
return { intact: false, brokenIndex: i, reason: 'tenant_mismatch' };
|
|
227
|
+
}
|
|
228
|
+
// (a) ORDER: sequence must be dense + monotonic from 0. A gap/reorder here
|
|
229
|
+
// means a record was removed or moved (AC-4).
|
|
230
|
+
if (record.sequenceNumber !== expectedSequence) {
|
|
231
|
+
return { intact: false, brokenIndex: i, reason: 'sequence_gap' };
|
|
232
|
+
}
|
|
233
|
+
// (b) LINK: prevHash must equal the prior record's entryHash (GENESIS at 0).
|
|
234
|
+
// A cut link means a record was deleted/swapped/inserted (AC-4/5) — this also
|
|
235
|
+
// catches an attempt to "borrow" another tenant's hash (AC-5): a foreign
|
|
236
|
+
// prevHash won't match this chain's recomputed prior entryHash.
|
|
237
|
+
if (record.prevHash !== expectedPrevHash) {
|
|
238
|
+
return { intact: false, brokenIndex: i, reason: 'prev_mismatch' };
|
|
239
|
+
}
|
|
240
|
+
// (c) CONTENT + BINDING: recompute from the record's OWN stored fields with
|
|
241
|
+
// the SAME hash. If a field was mutated, the recomputed contentHash (and thus
|
|
242
|
+
// entryHash) diverges from what is stored (AC-3).
|
|
243
|
+
const cleanEvent = {
|
|
244
|
+
type: record.type,
|
|
245
|
+
occurredAtMs: record.occurredAtMs,
|
|
246
|
+
actorId: record.actorId,
|
|
247
|
+
tenantId: record.tenantId,
|
|
248
|
+
...(record.action !== undefined ? { action: record.action } : {}),
|
|
249
|
+
...(record.resource !== undefined ? { resource: record.resource } : {}),
|
|
250
|
+
...(record.decision !== undefined ? { decision: record.decision } : {}),
|
|
251
|
+
...(record.attributes !== undefined ? { attributes: record.attributes } : {}),
|
|
252
|
+
};
|
|
253
|
+
const recomputedContentHash = hash.hash(canonicalizeEvent(cleanEvent));
|
|
254
|
+
const recomputedEntryHash = hash.hash(entryPreimage(recomputedContentHash, record.prevHash, record.sequenceNumber));
|
|
255
|
+
if (recomputedContentHash !== record.contentHash ||
|
|
256
|
+
recomputedEntryHash !== record.entryHash) {
|
|
257
|
+
return { intact: false, brokenIndex: i, reason: 'content_mismatch' };
|
|
258
|
+
}
|
|
259
|
+
// Advance the expected link/sequence to THIS record's recomputed entryHash.
|
|
260
|
+
expectedPrevHash = recomputedEntryHash;
|
|
261
|
+
expectedSequence = record.sequenceNumber + 1;
|
|
262
|
+
}
|
|
263
|
+
return { intact: true };
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=audit-recorder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audit-recorder.js","sourceRoot":"","sources":["../../src/audit/audit-recorder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,0BAA0B,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAE5E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,yBAAyB,CAAC;AAEjD,wEAAwE;AACxE,MAAM,SAAS,GAAG,GAAG,CAAC;AAEtB;;;;GAIG;AACH,SAAS,aAAa,CAAC,WAAmB,EAAE,QAAgB,EAAE,cAA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,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACvE,GAAG,CAAC,MAAM,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACvE,GAAG,CAAC,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC9E,CAAC;QACF,MAAM,qBAAqB,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC;QACvE,MAAM,mBAAmB,GAAG,IAAI,CAAC,IAAI,CACnC,aAAa,CAAC,qBAAqB,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,cAAc,CAAC,CAC7E,CAAC;QACF,IACE,qBAAqB,KAAK,MAAM,CAAC,WAAW;YAC5C,mBAAmB,KAAK,MAAM,CAAC,SAAS,EACxC,CAAC;YACD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC;QACvE,CAAC;QAED,4EAA4E;QAC5E,gBAAgB,GAAG,mBAAmB,CAAC;QACvC,gBAAgB,GAAG,MAAM,CAAC,cAAc,GAAG,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AAC1B,CAAC"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **Canonical event serialization** — the load-bearing determinism at the heart
|
|
3
|
+
* of tamper-evidence (§3.1, AC-6).
|
|
4
|
+
*
|
|
5
|
+
* `contentHash = hash(canonicalizeEvent(event))`. For the hash to be a stable
|
|
6
|
+
* fingerprint, the SAME logical event MUST serialize to BYTE-IDENTICAL output
|
|
7
|
+
* regardless of the insertion order of its attribute keys — otherwise two
|
|
8
|
+
* equivalent events hash differently and the write path and the independent
|
|
9
|
+
* verification path disagree, DEFEATING tamper-detection.
|
|
10
|
+
*
|
|
11
|
+
* `JSON.stringify` alone is INSUFFICIENT: it preserves object key INSERTION
|
|
12
|
+
* order, so `{a,b}` and `{b,a}` stringify differently. This module therefore does
|
|
13
|
+
* a RECURSIVE, KEY-SORTED walk producing a deterministic string, stable across:
|
|
14
|
+
* - object key order (keys emitted sorted);
|
|
15
|
+
* - nested objects/arrays (recursed, arrays keep their order as order IS data);
|
|
16
|
+
* - the `Decision`/`Action`/`Resource` sub-objects (they are plain objects →
|
|
17
|
+
* handled by the same recursive rule, no special-casing needed).
|
|
18
|
+
*
|
|
19
|
+
* PURE + DETERMINISTIC — no I/O, no clock, no randomness, no state. ADR-0003:
|
|
20
|
+
* framework-agnostic — no framework / HTTP / DB / node imports.
|
|
21
|
+
*/
|
|
22
|
+
import type { AuditEvent } from './index.js';
|
|
23
|
+
/**
|
|
24
|
+
* Produce the PURE, DETERMINISTIC, key-ordered canonical string for an
|
|
25
|
+
* {@link AuditEvent}. The SAME event with `attributes` in a different key order
|
|
26
|
+
* yields BYTE-IDENTICAL output (AC-6) — the input to {@link HashFunction.hash}
|
|
27
|
+
* for the record's `contentHash`.
|
|
28
|
+
*
|
|
29
|
+
* Only {@link CONTENT_FIELDS} participate; engine metadata (recordedAtMs,
|
|
30
|
+
* sequence, hashes) is excluded so the content fingerprint reflects the caller's
|
|
31
|
+
* event alone. Absent optional fields are encoded identically to a present-but-
|
|
32
|
+
* `undefined` field, so their presence/absence never changes the bytes.
|
|
33
|
+
*
|
|
34
|
+
* @param event The (already secret-stripped) event to fingerprint.
|
|
35
|
+
* @returns A deterministic canonical serialization suitable for hashing.
|
|
36
|
+
*/
|
|
37
|
+
export declare function canonicalizeEvent(event: AuditEvent): string;
|
|
38
|
+
//# sourceMappingURL=canonicalize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"canonicalize.d.ts","sourceRoot":"","sources":["../../src/audit/canonicalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAoI7C;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAU3D"}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **Canonical event serialization** — the load-bearing determinism at the heart
|
|
3
|
+
* of tamper-evidence (§3.1, AC-6).
|
|
4
|
+
*
|
|
5
|
+
* `contentHash = hash(canonicalizeEvent(event))`. For the hash to be a stable
|
|
6
|
+
* fingerprint, the SAME logical event MUST serialize to BYTE-IDENTICAL output
|
|
7
|
+
* regardless of the insertion order of its attribute keys — otherwise two
|
|
8
|
+
* equivalent events hash differently and the write path and the independent
|
|
9
|
+
* verification path disagree, DEFEATING tamper-detection.
|
|
10
|
+
*
|
|
11
|
+
* `JSON.stringify` alone is INSUFFICIENT: it preserves object key INSERTION
|
|
12
|
+
* order, so `{a,b}` and `{b,a}` stringify differently. This module therefore does
|
|
13
|
+
* a RECURSIVE, KEY-SORTED walk producing a deterministic string, stable across:
|
|
14
|
+
* - object key order (keys emitted sorted);
|
|
15
|
+
* - nested objects/arrays (recursed, arrays keep their order as order IS data);
|
|
16
|
+
* - the `Decision`/`Action`/`Resource` sub-objects (they are plain objects →
|
|
17
|
+
* handled by the same recursive rule, no special-casing needed).
|
|
18
|
+
*
|
|
19
|
+
* PURE + DETERMINISTIC — no I/O, no clock, no randomness, no state. ADR-0003:
|
|
20
|
+
* framework-agnostic — no framework / HTTP / DB / node imports.
|
|
21
|
+
*/
|
|
22
|
+
import { AuditValidationError } from './errors.js';
|
|
23
|
+
import { guardDescent, isDescendableObject, specialLeafTag } from './walk.js';
|
|
24
|
+
/**
|
|
25
|
+
* The ordered top-level fields of an {@link AuditEvent} that participate in the
|
|
26
|
+
* content hash. Listed EXPLICITLY (not derived from `Object.keys`) so the content
|
|
27
|
+
* fingerprint is stable even if the event object is built with a different key
|
|
28
|
+
* order, and so engine-only metadata (sequence/hashes/stamp) never leaks into the
|
|
29
|
+
* content hash. `attributes` is canonicalized recursively (key-sorted).
|
|
30
|
+
*
|
|
31
|
+
* ⛔ Deliberately EXCLUDES `recordedAtMs` (engine provenance, AC-9) and all chain
|
|
32
|
+
* metadata — the content hash fingerprints the CALLER's event only.
|
|
33
|
+
*/
|
|
34
|
+
const CONTENT_FIELDS = [
|
|
35
|
+
'type',
|
|
36
|
+
'occurredAtMs',
|
|
37
|
+
'actorId',
|
|
38
|
+
'tenantId',
|
|
39
|
+
'action',
|
|
40
|
+
'resource',
|
|
41
|
+
'decision',
|
|
42
|
+
'attributes',
|
|
43
|
+
];
|
|
44
|
+
/**
|
|
45
|
+
* Deterministically serialize an arbitrary JSON-ish value with object keys SORTED
|
|
46
|
+
* recursively. Arrays keep their element order (order is semantically meaningful);
|
|
47
|
+
* objects emit `{ "k":<canon>,... }` with keys in ascending `<` order.
|
|
48
|
+
*
|
|
49
|
+
* Encoding notes (chosen for stability, not readability). Every JS value type is
|
|
50
|
+
* handled EXPLICITLY — NONE reaches a raw `TypeError` mid-hash. Legitimate JSON-ish
|
|
51
|
+
* values are NORMALIZED; genuinely non-serializable values are REJECTED with a
|
|
52
|
+
* TYPED {@link AuditValidationError} (never an untyped throw / `JSON.stringify`
|
|
53
|
+
* crash on a `bigint`):
|
|
54
|
+
* - `undefined` → the token `null` (JSON has no `undefined`; treating it as null
|
|
55
|
+
* keeps "key absent" and "key present but undefined" indistinguishable, which
|
|
56
|
+
* is correct — neither carries information);
|
|
57
|
+
* - a non-finite number (`NaN`/`±Infinity`) → the token `null` (matches
|
|
58
|
+
* `JSON.stringify`), so it can never introduce non-determinism;
|
|
59
|
+
* - `Date` → a COLLISION-FREE STRUCTURAL tag ({@link specialLeafTag} in
|
|
60
|
+
* `./walk.ts`): `{"__shieldType":"date","v":"<ms>"}` (`getTime()`; an invalid
|
|
61
|
+
* Date → `v:"null"`). This is an OBJECT shape a plain string value can NEVER
|
|
62
|
+
* serialize to — a plain string `"date:0"` serializes as the JSON string
|
|
63
|
+
* `"date:0"`, which cannot equal the object form — so the previous string-prefix
|
|
64
|
+
* tag collision (a Date and the literal `"date:0"` hashing identically) is now
|
|
65
|
+
* structurally impossible (round-2 Finding D);
|
|
66
|
+
* - `-0` → normalized to `0`; `NaN` / `±Infinity` → the bare `null` token (both
|
|
67
|
+
* inline, matching `JSON.stringify` semantics). These are BARE JSON tokens, not
|
|
68
|
+
* quoted strings, so a plain string value (`"0"`/`"null"`, which JSON-encode to
|
|
69
|
+
* the QUOTED forms) can never collide with them — no structural tag needed;
|
|
70
|
+
* - `bigint` / `symbol` / `function` → REJECTED with a typed
|
|
71
|
+
* {@link AuditValidationError} (`reason: 'unserializable_attribute'`). A `bigint`
|
|
72
|
+
* passes `AuditEvent`'s `Record<string, unknown>` validation but has no
|
|
73
|
+
* unambiguous, `JSON.stringify`-safe canonical form; surfacing it as a TYPED
|
|
74
|
+
* rejection at hash time (rather than a raw `TypeError`) is the secure bar — the
|
|
75
|
+
* emitting adapter fixes the call site instead of seeing a leaky internal crash;
|
|
76
|
+
* - a CYCLIC / pathologically-deep object graph → REJECTED with a typed
|
|
77
|
+
* {@link AuditValidationError} (`reason: 'cyclic_attribute'`) via the shared
|
|
78
|
+
* visited-`WeakSet` + depth guard ({@link guardDescent}), never an untyped
|
|
79
|
+
* `RangeError` from stack overflow mid-hash;
|
|
80
|
+
* - remaining primitives (string / finite number / boolean / null) via
|
|
81
|
+
* `JSON.stringify` (stable and sufficient).
|
|
82
|
+
*
|
|
83
|
+
* ⛔ DESCEND-SET PARITY: the object/array recursion here uses the SHARED
|
|
84
|
+
* {@link isDescendableObject} predicate — the SAME one the secret stripper
|
|
85
|
+
* (`./sensitive.ts`) uses — so the two walkers descend the EXACT same objects
|
|
86
|
+
* (regardless of prototype: a null-proto or class-instance object is descended by
|
|
87
|
+
* both). This is the invariant that prevents a value being hashed-but-not-stripped.
|
|
88
|
+
*/
|
|
89
|
+
function canonicalizeValue(value, visited, depth) {
|
|
90
|
+
if (value === undefined || value === null) {
|
|
91
|
+
return 'null';
|
|
92
|
+
}
|
|
93
|
+
if (typeof value === 'bigint' || typeof value === 'symbol' || typeof value === 'function') {
|
|
94
|
+
// Non-serializable for a deterministic content hash → TYPED rejection (never a
|
|
95
|
+
// raw TypeError from JSON.stringify(bigint) mid-hash). Carries NO value (the
|
|
96
|
+
// reason names the invariant; a value could be a secret — see errors.ts).
|
|
97
|
+
throw new AuditValidationError('unserializable_attribute');
|
|
98
|
+
}
|
|
99
|
+
// Collision-free STRUCTURAL tag for a Date leaf — an object shape a plain string
|
|
100
|
+
// can never serialize to (closes the Date-vs-"date:0" collision, Finding D).
|
|
101
|
+
// Recurse into the tag object by the same rule so it is key-sorted like any object.
|
|
102
|
+
const tag = specialLeafTag(value);
|
|
103
|
+
if (tag !== undefined) {
|
|
104
|
+
return canonicalizeValue(tag, visited, depth);
|
|
105
|
+
}
|
|
106
|
+
if (Array.isArray(value)) {
|
|
107
|
+
// Order IS data — do NOT sort array elements; recurse each in place. Guard the
|
|
108
|
+
// array itself against a cycle/over-depth before descending its elements.
|
|
109
|
+
guardDescent(value, visited, depth);
|
|
110
|
+
visited.add(value);
|
|
111
|
+
try {
|
|
112
|
+
return `[${value.map((v) => canonicalizeValue(v, visited, depth + 1)).join(',')}]`;
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
visited.delete(value);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (isDescendableObject(value)) {
|
|
119
|
+
// Descend by the SHARED predicate (regardless of prototype). Guard against a
|
|
120
|
+
// cycle/over-depth, then sort keys so insertion order can't change the bytes.
|
|
121
|
+
// Skip `undefined` values entirely (a key mapping to undefined carries no
|
|
122
|
+
// information and JSON would drop it anyway) — keeping them would only add noise.
|
|
123
|
+
guardDescent(value, visited, depth);
|
|
124
|
+
visited.add(value);
|
|
125
|
+
try {
|
|
126
|
+
const obj = value;
|
|
127
|
+
const keys = Object.keys(obj)
|
|
128
|
+
.filter((k) => obj[k] !== undefined)
|
|
129
|
+
.sort();
|
|
130
|
+
const parts = keys.map((k) => `${JSON.stringify(k)}:${canonicalizeValue(obj[k], visited, depth + 1)}`);
|
|
131
|
+
return `{${parts.join(',')}}`;
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
visited.delete(value);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (typeof value === 'number') {
|
|
138
|
+
if (!Number.isFinite(value)) {
|
|
139
|
+
// NaN / ±Infinity are not representable in JSON; normalize to the bare `null`
|
|
140
|
+
// token so they can never introduce non-determinism. A plain string `"null"`
|
|
141
|
+
// JSON-encodes to the QUOTED `"null"`, so it can never collide with this token.
|
|
142
|
+
return 'null';
|
|
143
|
+
}
|
|
144
|
+
// Normalize -0 to 0 explicitly (JSON.stringify already does this; keep it pinned
|
|
145
|
+
// so the two zeros can never diverge). A finite number needs no structural tag.
|
|
146
|
+
return JSON.stringify(value === 0 ? 0 : value);
|
|
147
|
+
}
|
|
148
|
+
// string | boolean → JSON.stringify is stable and sufficient.
|
|
149
|
+
return JSON.stringify(value);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Produce the PURE, DETERMINISTIC, key-ordered canonical string for an
|
|
153
|
+
* {@link AuditEvent}. The SAME event with `attributes` in a different key order
|
|
154
|
+
* yields BYTE-IDENTICAL output (AC-6) — the input to {@link HashFunction.hash}
|
|
155
|
+
* for the record's `contentHash`.
|
|
156
|
+
*
|
|
157
|
+
* Only {@link CONTENT_FIELDS} participate; engine metadata (recordedAtMs,
|
|
158
|
+
* sequence, hashes) is excluded so the content fingerprint reflects the caller's
|
|
159
|
+
* event alone. Absent optional fields are encoded identically to a present-but-
|
|
160
|
+
* `undefined` field, so their presence/absence never changes the bytes.
|
|
161
|
+
*
|
|
162
|
+
* @param event The (already secret-stripped) event to fingerprint.
|
|
163
|
+
* @returns A deterministic canonical serialization suitable for hashing.
|
|
164
|
+
*/
|
|
165
|
+
export function canonicalizeEvent(event) {
|
|
166
|
+
const bag = event;
|
|
167
|
+
// One visited-set per event walk (a fresh WeakSet, depth 0) backs the shared
|
|
168
|
+
// cycle/over-depth guard so a self-referential attribute graph rejects with a
|
|
169
|
+
// TYPED AuditValidationError('cyclic_attribute') instead of overflowing the stack.
|
|
170
|
+
const visited = new WeakSet();
|
|
171
|
+
const parts = CONTENT_FIELDS.map((field) => `${JSON.stringify(field)}:${canonicalizeValue(bag[field], visited, 0)}`);
|
|
172
|
+
return `{${parts.join(',')}}`;
|
|
173
|
+
}
|
|
174
|
+
//# sourceMappingURL=canonicalize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"canonicalize.js","sourceRoot":"","sources":["../../src/audit/canonicalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE9E;;;;;;;;;GASG;AACH,MAAM,cAAc,GAAG;IACrB,MAAM;IACN,cAAc;IACd,SAAS;IACT,UAAU;IACV,QAAQ;IACR,UAAU;IACV,UAAU;IACV,YAAY;CACJ,CAAC;AAEX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,SAAS,iBAAiB,CAAC,KAAc,EAAE,OAAwB,EAAE,KAAa;IAChF,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAC1C,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,O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