@astram/core 1.1.0 → 1.3.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 (74) hide show
  1. package/dist/authentication/index.d.ts +1 -0
  2. package/dist/authentication/index.d.ts.map +1 -1
  3. package/dist/authentication/index.js +2 -0
  4. package/dist/authentication/index.js.map +1 -1
  5. package/dist/authentication/service-account-authenticator.d.ts +82 -0
  6. package/dist/authentication/service-account-authenticator.d.ts.map +1 -0
  7. package/dist/authentication/service-account-authenticator.js +74 -0
  8. package/dist/authentication/service-account-authenticator.js.map +1 -0
  9. package/dist/authorization/gates/object-type.d.ts.map +1 -1
  10. package/dist/authorization/gates/object-type.js +17 -8
  11. package/dist/authorization/gates/object-type.js.map +1 -1
  12. package/dist/authorization/gates/tenant.d.ts +7 -4
  13. package/dist/authorization/gates/tenant.d.ts.map +1 -1
  14. package/dist/authorization/gates/tenant.js +30 -7
  15. package/dist/authorization/gates/tenant.js.map +1 -1
  16. package/dist/authorization/index.d.ts +1 -0
  17. package/dist/authorization/index.d.ts.map +1 -1
  18. package/dist/authorization/index.js +2 -0
  19. package/dist/authorization/index.js.map +1 -1
  20. package/dist/authorization/ports.d.ts +65 -0
  21. package/dist/authorization/ports.d.ts.map +1 -1
  22. package/dist/authorization/record/list-scope.d.ts +198 -0
  23. package/dist/authorization/record/list-scope.d.ts.map +1 -0
  24. package/dist/authorization/record/list-scope.js +153 -0
  25. package/dist/authorization/record/list-scope.js.map +1 -0
  26. package/dist/encryption/encryption-service.d.ts +63 -0
  27. package/dist/encryption/encryption-service.d.ts.map +1 -0
  28. package/dist/encryption/encryption-service.js +184 -0
  29. package/dist/encryption/encryption-service.js.map +1 -0
  30. package/dist/encryption/index.d.ts +17 -0
  31. package/dist/encryption/index.d.ts.map +1 -0
  32. package/dist/encryption/index.js +15 -0
  33. package/dist/encryption/index.js.map +1 -0
  34. package/dist/encryption/ports.d.ts +84 -0
  35. package/dist/encryption/ports.d.ts.map +1 -0
  36. package/dist/encryption/ports.js +18 -0
  37. package/dist/encryption/ports.js.map +1 -0
  38. package/dist/identity/broker.d.ts.map +1 -1
  39. package/dist/identity/broker.js +6 -0
  40. package/dist/identity/broker.js.map +1 -1
  41. package/dist/identity/index.d.ts +16 -1
  42. package/dist/identity/index.d.ts.map +1 -1
  43. package/dist/identity/index.js.map +1 -1
  44. package/dist/index.d.ts +2 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +2 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/secrets/index.d.ts +15 -0
  49. package/dist/secrets/index.d.ts.map +1 -0
  50. package/dist/secrets/index.js +14 -0
  51. package/dist/secrets/index.js.map +1 -0
  52. package/dist/secrets/ports.d.ts +45 -0
  53. package/dist/secrets/ports.d.ts.map +1 -0
  54. package/dist/secrets/ports.js +26 -0
  55. package/dist/secrets/ports.js.map +1 -0
  56. package/dist/secrets/resolve.d.ts +29 -0
  57. package/dist/secrets/resolve.d.ts.map +1 -0
  58. package/dist/secrets/resolve.js +49 -0
  59. package/dist/secrets/resolve.js.map +1 -0
  60. package/dist-cjs/authentication/index.js +2 -0
  61. package/dist-cjs/authentication/service-account-authenticator.js +78 -0
  62. package/dist-cjs/authorization/gates/object-type.js +17 -8
  63. package/dist-cjs/authorization/gates/tenant.js +30 -7
  64. package/dist-cjs/authorization/index.js +2 -0
  65. package/dist-cjs/authorization/record/list-scope.js +155 -0
  66. package/dist-cjs/encryption/encryption-service.js +189 -0
  67. package/dist-cjs/encryption/index.js +20 -0
  68. package/dist-cjs/encryption/ports.js +18 -0
  69. package/dist-cjs/identity/broker.js +6 -0
  70. package/dist-cjs/index.js +2 -0
  71. package/dist-cjs/secrets/index.js +21 -0
  72. package/dist-cjs/secrets/ports.js +29 -0
  73. package/dist-cjs/secrets/resolve.js +54 -0
  74. package/package.json +1 -1
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Phase 1 — the decision-DERIVED **list scope** ({@link computeListScope}), the NEW
3
+ * SIBLING to `decide()` (§7.1). `decide(principal, action, resource, context)` answers
4
+ * "may this ONE record be accessed?" — allow/deny. A LIST endpoint instead needs the
5
+ * *set* of visible rows pushed into the SQL WHERE (Invariant #8 — filter in the query,
6
+ * NEVER fetch-then-discard). `decide()`'s 4-arg signature is FROZEN and returns
7
+ * allow/deny only, so this module adds a sibling contract that produces an ABSTRACT,
8
+ * DB-agnostic description of the visible set — a {@link ListScopeSpec} — computed by a
9
+ * pure function that reproduces the EXACT composition semantics the record-permit tier
10
+ * (`permit-tier.ts`) uses. Phase 2 (the guard) translates the spec to SQL; Phase 3
11
+ * injects it into the engine's `list()`. THIS module is pure core logic — no DB, no
12
+ * SQL, no adapter.
13
+ *
14
+ * ── THE SEMANTICS IT REPRODUCES (this is the whole point). The visible set equals the
15
+ * set `decide()` allows, row-by-row. The record-permit tier it mirrors composes:
16
+ *
17
+ * 1. policy = evaluateRecordPolicy(ctx) // allow + explicitDeny booleans
18
+ * 2. explicitDeny ⇒ DENY (deny-wins, SHORT-CIRCUITS before share)
19
+ * 3. baseline = evaluateOwnerBaseline(ctx)
20
+ * policy.allow || baseline ⇒ ALLOW
21
+ * 4. share = evaluateRecordShare(ctx) // same-tenant share ∪ cross-tenant grant
22
+ * share ⇒ ALLOW
23
+ * 5. else ⇒ DENY
24
+ *
25
+ * ⇒ a record is VISIBLE iff:
26
+ * NOT policyDeny AND (policyAllow OR ownerBaseline OR share OR crossTenant),
27
+ * all WITHIN the tenant bound. Deny-wins is load-bearing: an explicit policy deny
28
+ * REMOVES a row even if a share/owner would include it — so the deny set is an
29
+ * EXCLUSION applied over the union (Phase 2 translates it as `AND NOT (…deny…)`).
30
+ *
31
+ * ── The OWNER-BASELINE posture mapping mirrors `owner-baseline.ts` EXACTLY (same branch
32
+ * precedence): `system` ⇒ all; `tenantScoped && !owned` ⇒ all; `owned` ⇒ owned-only
33
+ * (`ownerId === principal.id`, modeled as `{kind:'owned', ownerField:'ownerId', …}`);
34
+ * no access / unknown type ⇒ none (fail-closed — a rule/share must include the row).
35
+ *
36
+ * ── FAIL-CLOSED (ADR-0016). The ONE port call ({@link ListScopePort.listPolicyConditions})
37
+ * may throw a transient {@link AuthorizationUnavailableError}; this function does NOT
38
+ * catch it — a throw PROPAGATES so the read fails, never "unbounded". Swallowing it
39
+ * into an empty/unbounded spec would silently mis-scope the list (Invariant #8).
40
+ *
41
+ * ── PURE + zero-dep (ADR-0003). No framework / HTTP / DB / node imports; the only I/O is
42
+ * the single {@link ListScopePort} call (which reaches its store via the guard adapter).
43
+ */
44
+ import type { PolicyOperator } from '../../admin/types.js';
45
+ import type { Principal } from '../../identity/index.js';
46
+ import type { ObjectTypeDescriptor } from '../../metadata/index.js';
47
+ import type { ListScopePort } from '../ports.js';
48
+ /**
49
+ * One abstract condition of the visible set — the SAME 14-operator model the policy
50
+ * store uses ({@link PolicyOperator}). This is NOT SQL; Phase 2 (the guard translator)
51
+ * maps it to a real column + parameterized predicate.
52
+ */
53
+ export interface ScopeCondition {
54
+ /** Stable field key on the target object type (Phase 2 maps it to the real column). */
55
+ readonly field: string;
56
+ /** The comparison operator (closed set — no raw expression). */
57
+ readonly operator: PolicyOperator;
58
+ /** The comparand (operators that take no operand, e.g. `is_null`, ignore it). */
59
+ readonly value: unknown;
60
+ }
61
+ /**
62
+ * The tenant bound of the visible set. Every non-root list is bounded to the actor's
63
+ * REACHABLE SUBTREE (self + descendants, ADR-0027 — the scoped-hierarchy generalization
64
+ * of the flat tenant bound); root on the control-plane spans tenants.
65
+ *
66
+ * `tenantSubtree` carries the PRE-EXPANDED reachable node set (`principal.scopeSubtreeNodeIds`
67
+ * — resolved once at login from the closure and cached, Task 2.2), NOT just a root id: the
68
+ * guard translator emits `tenant_col IN (?, ...)` over these ids directly. This is the SAME
69
+ * set the tenant GATE tests membership against, so list ≡ decide holds BY CONSTRUCTION (no
70
+ * closure query at list time → no divergence from a stale/absent closure row). It is a STRICT,
71
+ * NON-BREAKING GENERALIZATION of the flat variant: a principal whose reachable subtree is just
72
+ * itself has `nodeIds = [activeScopeNodeId]` — identical to the old `tenantId = ?` behavior.
73
+ *
74
+ * The flat `tenantId` variant is KEPT for back-compat (some callers/tests may still
75
+ * construct it directly; the guard translator handles both).
76
+ */
77
+ export type ScopeTenantBound = {
78
+ readonly role: 'tenantId';
79
+ readonly value: string;
80
+ } | {
81
+ readonly role: 'tenantSubtree';
82
+ readonly nodeIds: readonly string[];
83
+ } | 'root-unbounded';
84
+ /**
85
+ * The owner-baseline contribution to the visible set — mirrors the `owner-baseline.ts`
86
+ * postures. `all` ⇒ every row of the type (system / tenantScoped); `owned` ⇒ only rows
87
+ * whose owner column equals the principal (DAC); `none` ⇒ no baseline (fail-closed —
88
+ * a rule/share must include the row).
89
+ */
90
+ export type ScopeOwnerBaseline = {
91
+ readonly kind: 'all';
92
+ } | {
93
+ readonly kind: 'owned';
94
+ readonly ownerField: string;
95
+ readonly principalId: string;
96
+ } | {
97
+ readonly kind: 'none';
98
+ };
99
+ /**
100
+ * A marker the guard adapter resolves to a `record_share` subquery (Phase 2/6). Kept
101
+ * abstract here — core has no DB. Its presence unions the principal's (and its roles')
102
+ * shared records into the visible set.
103
+ */
104
+ export type ScopeShareMarker = {
105
+ readonly kind: 'none';
106
+ } | {
107
+ readonly kind: 'shared-records';
108
+ readonly principalId: string;
109
+ readonly roleIds: readonly string[];
110
+ readonly action: string;
111
+ };
112
+ /**
113
+ * A cross-tenant grant descriptor the guard adapter resolves (Phase 4). Abstract here.
114
+ * Its presence unions the records reachable via an active, consented cross-tenant grant.
115
+ */
116
+ export type ScopeCrossTenant = {
117
+ readonly kind: 'none';
118
+ } | {
119
+ readonly kind: 'granted';
120
+ readonly principalId: string;
121
+ readonly roleIds: readonly string[];
122
+ readonly action: string;
123
+ };
124
+ /**
125
+ * The ABSTRACT, DB-agnostic description of the visible set — the list-form sibling to a
126
+ * `decide()` verdict. Mirrors the permit-tier composition:
127
+ *
128
+ * visible iff NOT policyDeny AND (policyAllow OR ownerBaseline OR share OR crossTenant),
129
+ * WITHIN {@link tenantBound}.
130
+ *
131
+ * {@link policyAllow} / {@link policyDeny} are AND-GROUPS OR'd together: a row satisfies
132
+ * the group iff it satisfies ALL conditions of the group; the subset is the UNION over
133
+ * groups. This preserves the guided-policy AND-of-conditions semantics (each policy is an
134
+ * AND of its conditions; multiple policies OR) so Phase 2 can translate WITHOUT losing
135
+ * AND-vs-OR. An empty `policyAllow`/`policyDeny` is a normal absence (no applicable policy).
136
+ */
137
+ export interface ListScopeSpec {
138
+ readonly typeKey: string;
139
+ readonly action: string;
140
+ readonly tenantBound: ScopeTenantBound;
141
+ readonly ownerBaseline: ScopeOwnerBaseline;
142
+ /** AND-groups OR'd: rows satisfying ALL conditions of ANY group are INCLUDED (unioned). */
143
+ readonly policyAllow: readonly (readonly ScopeCondition[])[];
144
+ /** AND-groups OR'd: rows satisfying ALL conditions of ANY group are EXCLUDED (deny-wins). */
145
+ readonly policyDeny: readonly (readonly ScopeCondition[])[];
146
+ /** shared records are INCLUDED (union) — resolved by the guard adapter. */
147
+ readonly share: ScopeShareMarker;
148
+ /** cross-tenant-granted records are INCLUDED (union) — resolved by the guard adapter. */
149
+ readonly crossTenant: ScopeCrossTenant;
150
+ }
151
+ /** The framework-owned dependencies {@link computeListScope} reads. */
152
+ export interface ComputeListScopeDeps {
153
+ /** Resolves the object type's access posture (same registry the engine uses). */
154
+ readonly registry: {
155
+ resolveObjectType(typeKey: string): ObjectTypeDescriptor | undefined;
156
+ };
157
+ /** The ONE port: the policy allow/deny condition-groups for the list scope. */
158
+ readonly listScope: ListScopePort;
159
+ }
160
+ /** The list-scope question — the actor + what/where they are listing. */
161
+ export interface ComputeListScopeQuery {
162
+ readonly principal: Principal;
163
+ readonly action: string;
164
+ readonly typeKey: string;
165
+ /** The actor's tenant — the bound for non-root. */
166
+ readonly tenantId: string;
167
+ }
168
+ /**
169
+ * Compute the abstract {@link ListScopeSpec} describing the set of records the principal
170
+ * may see for `(typeKey, action)` within their tenant — the list-form sibling to
171
+ * `decide()`, reproducing the record-permit tier's composition (§7.3.4 / ADR-0005/6/9).
172
+ *
173
+ * Logic (mirrors `permit-tier.ts`):
174
+ * - `tenantBound`: `principal.isRoot === true` ⇒ `'root-unbounded'` (root spans the
175
+ * control-plane; a data-plane list never reaches here for root — `decide()`'s coarse
176
+ * object-type gate already denied it upstream, so we simply honor `isRoot` for the
177
+ * bound). Else ⇒ `{role:'tenantSubtree', nodeIds: principal.scopeSubtreeNodeIds}`
178
+ * (every non-root list is bounded to the actor's REACHABLE SUBTREE — self + descendants,
179
+ * mirroring the tenant gate's `scopeSubtreeNodeIds` membership test, ADR-0027. Uniform —
180
+ * no per-type "is this hierarchy-scoped" flag. This is a NON-BREAKING generalization: a
181
+ * self-node-only principal's closure returns just that one node, i.e. the old flat
182
+ * `tenantId = ?` behavior. The guard translator, Task 3.3, expands the node set to the
183
+ * subtree via the `scope_closure` subquery — core carries only the root id(s), staying
184
+ * DB-agnostic).
185
+ * - `ownerBaseline`: root ⇒ `{kind:'all'}` (unbounded on control-plane). Else the
186
+ * posture mapping above.
187
+ * - `policyAllow`/`policyDeny`: from the ONE port call — mapped straight onto the spec.
188
+ * A transient throw PROPAGATES (NOT caught — fail-closed, ADR-0016).
189
+ * - `share`: always the abstract marker for the caller (Phase 2 resolves it). For root
190
+ * it is harmless (root's baseline is `all`, a superset); populated uniformly.
191
+ * - `crossTenant`: `{kind:'granted', …}` when NON-root (a non-root principal may hold a
192
+ * cross-tenant grant); root ⇒ `{kind:'none'}` — root needs no grant (it is unbounded
193
+ * on the control-plane; a data-plane list never reaches here for root).
194
+ *
195
+ * PURE except the ONE port call; NEVER throws except the propagated transient.
196
+ */
197
+ export declare function computeListScope(deps: ComputeListScopeDeps, query: ComputeListScopeQuery): Promise<ListScopeSpec>;
198
+ //# sourceMappingURL=list-scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-scope.d.ts","sourceRoot":"","sources":["../../../src/authorization/record/list-scope.ts"],"names":[],"m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EAAE,aAAa,CAAC;CACnC;AAED,yEAAyE;AACzE,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AA4BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,oBAAoB,EAC1B,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,aAAa,CAAC,CA6DxB"}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Phase 1 — the decision-DERIVED **list scope** ({@link computeListScope}), the NEW
3
+ * SIBLING to `decide()` (§7.1). `decide(principal, action, resource, context)` answers
4
+ * "may this ONE record be accessed?" — allow/deny. A LIST endpoint instead needs the
5
+ * *set* of visible rows pushed into the SQL WHERE (Invariant #8 — filter in the query,
6
+ * NEVER fetch-then-discard). `decide()`'s 4-arg signature is FROZEN and returns
7
+ * allow/deny only, so this module adds a sibling contract that produces an ABSTRACT,
8
+ * DB-agnostic description of the visible set — a {@link ListScopeSpec} — computed by a
9
+ * pure function that reproduces the EXACT composition semantics the record-permit tier
10
+ * (`permit-tier.ts`) uses. Phase 2 (the guard) translates the spec to SQL; Phase 3
11
+ * injects it into the engine's `list()`. THIS module is pure core logic — no DB, no
12
+ * SQL, no adapter.
13
+ *
14
+ * ── THE SEMANTICS IT REPRODUCES (this is the whole point). The visible set equals the
15
+ * set `decide()` allows, row-by-row. The record-permit tier it mirrors composes:
16
+ *
17
+ * 1. policy = evaluateRecordPolicy(ctx) // allow + explicitDeny booleans
18
+ * 2. explicitDeny ⇒ DENY (deny-wins, SHORT-CIRCUITS before share)
19
+ * 3. baseline = evaluateOwnerBaseline(ctx)
20
+ * policy.allow || baseline ⇒ ALLOW
21
+ * 4. share = evaluateRecordShare(ctx) // same-tenant share ∪ cross-tenant grant
22
+ * share ⇒ ALLOW
23
+ * 5. else ⇒ DENY
24
+ *
25
+ * ⇒ a record is VISIBLE iff:
26
+ * NOT policyDeny AND (policyAllow OR ownerBaseline OR share OR crossTenant),
27
+ * all WITHIN the tenant bound. Deny-wins is load-bearing: an explicit policy deny
28
+ * REMOVES a row even if a share/owner would include it — so the deny set is an
29
+ * EXCLUSION applied over the union (Phase 2 translates it as `AND NOT (…deny…)`).
30
+ *
31
+ * ── The OWNER-BASELINE posture mapping mirrors `owner-baseline.ts` EXACTLY (same branch
32
+ * precedence): `system` ⇒ all; `tenantScoped && !owned` ⇒ all; `owned` ⇒ owned-only
33
+ * (`ownerId === principal.id`, modeled as `{kind:'owned', ownerField:'ownerId', …}`);
34
+ * no access / unknown type ⇒ none (fail-closed — a rule/share must include the row).
35
+ *
36
+ * ── FAIL-CLOSED (ADR-0016). The ONE port call ({@link ListScopePort.listPolicyConditions})
37
+ * may throw a transient {@link AuthorizationUnavailableError}; this function does NOT
38
+ * catch it — a throw PROPAGATES so the read fails, never "unbounded". Swallowing it
39
+ * into an empty/unbounded spec would silently mis-scope the list (Invariant #8).
40
+ *
41
+ * ── PURE + zero-dep (ADR-0003). No framework / HTTP / DB / node imports; the only I/O is
42
+ * the single {@link ListScopePort} call (which reaches its store via the guard adapter).
43
+ */
44
+ /**
45
+ * Map the object type's access posture to the owner-baseline scope contribution,
46
+ * mirroring `owner-baseline.ts` branch precedence EXACTLY:
47
+ * - no access posture / unknown type ⇒ `{kind:'none'}` (fail-closed).
48
+ * - `system` ⇒ `{kind:'all'}`.
49
+ * - `tenantScoped === true && owned !== true` ⇒ `{kind:'all'}` (the tenant bound
50
+ * already isolates; the record baseline adds no narrowing).
51
+ * - `owned === true` ⇒ `{kind:'owned', ownerField:'ownerId', principalId}` (DAC:
52
+ * only rows the principal owns). NOTE the precedence — a type that is BOTH
53
+ * `owned` and `tenantScoped` resolves via the OWNED branch (matches the baseline:
54
+ * its `tenantScoped` branch requires `owned !== true`).
55
+ * - explicitly ungoverned (all flags false) ⇒ `{kind:'none'}` (fail-closed).
56
+ */
57
+ function ownerBaselineFor(access, principalId) {
58
+ if (!access)
59
+ return { kind: 'none' };
60
+ if (access.system === true)
61
+ return { kind: 'all' };
62
+ if (access.tenantScoped === true && access.owned !== true)
63
+ return { kind: 'all' };
64
+ if (access.owned === true) {
65
+ return { kind: 'owned', ownerField: 'ownerId', principalId };
66
+ }
67
+ return { kind: 'none' };
68
+ }
69
+ /**
70
+ * Compute the abstract {@link ListScopeSpec} describing the set of records the principal
71
+ * may see for `(typeKey, action)` within their tenant — the list-form sibling to
72
+ * `decide()`, reproducing the record-permit tier's composition (§7.3.4 / ADR-0005/6/9).
73
+ *
74
+ * Logic (mirrors `permit-tier.ts`):
75
+ * - `tenantBound`: `principal.isRoot === true` ⇒ `'root-unbounded'` (root spans the
76
+ * control-plane; a data-plane list never reaches here for root — `decide()`'s coarse
77
+ * object-type gate already denied it upstream, so we simply honor `isRoot` for the
78
+ * bound). Else ⇒ `{role:'tenantSubtree', nodeIds: principal.scopeSubtreeNodeIds}`
79
+ * (every non-root list is bounded to the actor's REACHABLE SUBTREE — self + descendants,
80
+ * mirroring the tenant gate's `scopeSubtreeNodeIds` membership test, ADR-0027. Uniform —
81
+ * no per-type "is this hierarchy-scoped" flag. This is a NON-BREAKING generalization: a
82
+ * self-node-only principal's closure returns just that one node, i.e. the old flat
83
+ * `tenantId = ?` behavior. The guard translator, Task 3.3, expands the node set to the
84
+ * subtree via the `scope_closure` subquery — core carries only the root id(s), staying
85
+ * DB-agnostic).
86
+ * - `ownerBaseline`: root ⇒ `{kind:'all'}` (unbounded on control-plane). Else the
87
+ * posture mapping above.
88
+ * - `policyAllow`/`policyDeny`: from the ONE port call — mapped straight onto the spec.
89
+ * A transient throw PROPAGATES (NOT caught — fail-closed, ADR-0016).
90
+ * - `share`: always the abstract marker for the caller (Phase 2 resolves it). For root
91
+ * it is harmless (root's baseline is `all`, a superset); populated uniformly.
92
+ * - `crossTenant`: `{kind:'granted', …}` when NON-root (a non-root principal may hold a
93
+ * cross-tenant grant); root ⇒ `{kind:'none'}` — root needs no grant (it is unbounded
94
+ * on the control-plane; a data-plane list never reaches here for root).
95
+ *
96
+ * PURE except the ONE port call; NEVER throws except the propagated transient.
97
+ */
98
+ export async function computeListScope(deps, query) {
99
+ const { principal, action, typeKey } = query;
100
+ const isRoot = principal.isRoot === true;
101
+ // The reachable node set is the principal's CACHED subtree (self + descendants, resolved
102
+ // once at login — Task 2.2), the SAME set the tenant gate tests membership against. Using
103
+ // it directly (not re-querying the closure at list time) makes list ≡ decide equivalence
104
+ // hold BY CONSTRUCTION and keeps the list hot path closure-free. A fail-safe self-node-only
105
+ // principal has `[activeScopeNodeId]` here — identical to the old flat `tenantId = ?`.
106
+ const subtree = Array.isArray(principal.scopeSubtreeNodeIds) && principal.scopeSubtreeNodeIds.length > 0
107
+ ? principal.scopeSubtreeNodeIds
108
+ : [principal.activeScopeNodeId];
109
+ const tenantBound = isRoot
110
+ ? 'root-unbounded'
111
+ : { role: 'tenantSubtree', nodeIds: subtree };
112
+ const ownerBaseline = isRoot
113
+ ? { kind: 'all' }
114
+ : ownerBaselineFor(deps.registry.resolveObjectType(typeKey)?.access, principal.id);
115
+ // The ONE I/O call. A transient AuthorizationUnavailableError PROPAGATES (fail-closed):
116
+ // it is NEVER caught here — swallowing it into an empty/unbounded spec would silently
117
+ // mis-scope the list (ADR-0016 / Invariant #8).
118
+ //
119
+ // The SUBJECT (principal id + role ids) is threaded so the adapter filters each policy
120
+ // rule group by its `rpr_subject_kind` / `rpr_subject_value` EXACTLY as decide()'s
121
+ // per-record `subjectMatches` does — otherwise a role-scoped rule would project to EVERY
122
+ // principal, a fail-open leak (HIGH-1). Root's baseline is already 'all' (a superset), so
123
+ // passing the subject is harmless for root and correct for non-root.
124
+ // Fetch policy rules for the WHOLE reachable subtree (`subtree` = the active node +
125
+ // descendants), NOT just the active node: a DENY rule scoped to a DESCENDANT node must
126
+ // exclude that node's records for a parent admin (deny-wins inherits DOWN, exactly as
127
+ // decide() applies it per-record at the record's own node). Plus global (NULL-tenant)
128
+ // rules. For a flat/self-node caller this is `[activeScopeNodeId]` — the old behavior.
129
+ const policy = await deps.listScope.listPolicyConditions(typeKey, subtree, action, {
130
+ principalId: principal.id,
131
+ roleIds: principal.roleIds,
132
+ });
133
+ const share = {
134
+ kind: 'shared-records',
135
+ principalId: principal.id,
136
+ roleIds: principal.roleIds,
137
+ action,
138
+ };
139
+ const crossTenant = isRoot
140
+ ? { kind: 'none' }
141
+ : { kind: 'granted', principalId: principal.id, roleIds: principal.roleIds, action };
142
+ return {
143
+ typeKey,
144
+ action,
145
+ tenantBound,
146
+ ownerBaseline,
147
+ policyAllow: policy.allow,
148
+ policyDeny: policy.deny,
149
+ share,
150
+ crossTenant,
151
+ };
152
+ }
153
+ //# sourceMappingURL=list-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-scope.js","sourceRoot":"","sources":["../../../src/authorization/record/list-scope.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AAwIH;;;;;;;;;;;;GAYG;AACH,SAAS,gBAAgB,CACvB,MAAsC,EACtC,WAAmB;IAEnB,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IACrC,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IACnD,IAAI,MAAM,CAAC,YAAY,KAAK,IAAI,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAClF,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;QAC1B,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,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,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE;QACjF,WAAW,EAAE,SAAS,CAAC,EAAE;QACzB,OAAO,EAAE,SAAS,CAAC,OAAO;KAC3B,CAAC,CAAC;IAEH,MAAM,KAAK,GAAqB;QAC9B,IAAI,EAAE,gBAAgB;QACtB,WAAW,EAAE,SAAS,CAAC,EAAE;QACzB,OAAO,EAAE,SAAS,CAAC,OAAO;QAC1B,MAAM;KACP,CAAC;IAEF,MAAM,WAAW,GAAqB,MAAM;QAC1C,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;QAClB,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;IAEvF,OAAO;QACL,OAAO;QACP,MAAM;QACN,WAAW;QACX,aAAa;QACb,WAAW,EAAE,MAAM,CAAC,KAAK;QACzB,UAAU,EAAE,MAAM,CAAC,IAAI;QACvB,KAAK;QACL,WAAW;KACZ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The **Encryption engine** (ADR-0031) — per-tenant envelope encryption for data at rest.
3
+ *
4
+ * `createEncryptionService({ crypto, dekStore, dekCache })` returns the ONE service the platform
5
+ * uses to encrypt/decrypt a tenant's data with that tenant's own DEK. It is PURE + zero-dep: all
6
+ * crypto, KMS, and persistence are injected ports (ADR-0003). The service:
7
+ * • resolves a tenant's DEK: cache → else load the WRAPPED DEK from the store → `crypto.unwrapDek`
8
+ * → cache it (so the hot path unwraps at most once per tenant per TTL);
9
+ * • PROVISIONS a DEK on first encrypt for a tenant (generate → wrap → persist the wrapped DEK);
10
+ * • binds the versioned ciphertext so a decrypt loads the exact DEK the data was written under
11
+ * (survives key rotation);
12
+ * • supports rotation (`rotateDek`) — the engine mints + persists a new DEK version; the batch
13
+ * re-encryption of existing rows is the consumer's job (the engine exposes the primitive).
14
+ *
15
+ * FAIL-CLOSED: a decrypt that can't resolve/unwrap the DEK or fails the AEAD tag THROWS — never
16
+ * returns plaintext, ciphertext, or empty. An encrypt that can't provision/wrap a DEK THROWS — a
17
+ * plaintext is NEVER written unencrypted as a fallback.
18
+ *
19
+ * THREAT MODEL (ADR-0031): defends the STORAGE boundary (disk/dump/backup → ciphertext only). Does
20
+ * NOT defend a compromised app host (it must hold the DEK in memory) or a compromised KMS.
21
+ */
22
+ import type { CryptoPort, DekStore, DekCache, Ciphertext } from './ports.js';
23
+ /** The dependencies the engine composes (all injected — ADR-0003 zero-dep). */
24
+ export interface EncryptionServiceDeps {
25
+ readonly crypto: CryptoPort;
26
+ readonly dekStore: DekStore;
27
+ /** Optional hot-path DEK cache. Absent ⇒ every op unwraps (correct, just slower). */
28
+ readonly dekCache?: DekCache;
29
+ }
30
+ /**
31
+ * A stored, encrypted value — the versioned envelope. Persist THIS (not the raw ciphertext): the
32
+ * `version` tells a later decrypt which DEK the data was written under, so rotation never orphans
33
+ * old data. `tenantId` is stored for defence-in-depth (the caller must also pass it to decrypt).
34
+ */
35
+ export interface Envelope {
36
+ readonly tenantId: string;
37
+ readonly version: number;
38
+ readonly ciphertext: Ciphertext;
39
+ }
40
+ export interface EncryptionService {
41
+ /** Encrypt `plaintext` for `tenantId` (provisioning the tenant's DEK on first use). */
42
+ encryptFor(tenantId: string, plaintext: Uint8Array): Promise<Envelope>;
43
+ /** Decrypt an {@link Envelope} for `tenantId`. Throws (fail-closed) on any failure. */
44
+ decryptFor(tenantId: string, envelope: Envelope): Promise<Uint8Array>;
45
+ /** Rotate a tenant's DEK: mint + persist a new version. Returns the new version number. */
46
+ rotateDek(tenantId: string): Promise<number>;
47
+ /** Crypto-shred a tenant (destroy all its DEKs) — its at-rest data becomes unrecoverable. */
48
+ destroyTenantKeys(tenantId: string): Promise<void>;
49
+ }
50
+ /** Thrown when a decrypt cannot proceed (missing/unwrappable DEK, tag mismatch). Fail-closed. */
51
+ export declare class DecryptionError extends Error {
52
+ /** Underlying cause (a port outage, a tag mismatch) — for admin logging; never surfaced/leaked. */
53
+ readonly cause?: unknown;
54
+ constructor(message: string, cause?: unknown);
55
+ }
56
+ /** Thrown when an encrypt cannot provision/wrap a DEK. No plaintext is ever written unencrypted. */
57
+ export declare class EncryptionError extends Error {
58
+ /** Underlying cause — for admin logging; never surfaced/leaked. */
59
+ readonly cause?: unknown;
60
+ constructor(message: string, cause?: unknown);
61
+ }
62
+ export declare function createEncryptionService(deps: EncryptionServiceDeps): EncryptionService;
63
+ //# sourceMappingURL=encryption-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption-service.d.ts","sourceRoot":"","sources":["../../src/encryption/encryption-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EACV,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,UAAU,EAEX,MAAM,YAAY,CAAC;AAEpB,+EAA+E;AAC/E,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,qFAAqF;IACrF,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;CAC9B;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;CACjC;AAED,MAAM,WAAW,iBAAiB;IAChC,uFAAuF;IACvF,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvE,uFAAuF;IACvF,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACtE,2FAA2F;IAC3F,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7C,6FAA6F;IAC7F,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACpD;AAED,iGAAiG;AACjG,qBAAa,eAAgB,SAAQ,KAAK;IACxC,mGAAmG;IACnG,SAAkB,KAAK,CAAC,EAAE,OAAO,CAAC;gBACtB,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAK7C;AAED,oGAAoG;AACpG,qBAAa,eAAgB,SAAQ,KAAK;IACxC,mEAAmE;IACnE,SAAkB,KAAK,CAAC,EAAE,OAAO,CAAC;gBACtB,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAK7C;AAQD,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,qBAAqB,GAAG,iBAAiB,CAoItF"}
@@ -0,0 +1,184 @@
1
+ /**
2
+ * The **Encryption engine** (ADR-0031) — per-tenant envelope encryption for data at rest.
3
+ *
4
+ * `createEncryptionService({ crypto, dekStore, dekCache })` returns the ONE service the platform
5
+ * uses to encrypt/decrypt a tenant's data with that tenant's own DEK. It is PURE + zero-dep: all
6
+ * crypto, KMS, and persistence are injected ports (ADR-0003). The service:
7
+ * • resolves a tenant's DEK: cache → else load the WRAPPED DEK from the store → `crypto.unwrapDek`
8
+ * → cache it (so the hot path unwraps at most once per tenant per TTL);
9
+ * • PROVISIONS a DEK on first encrypt for a tenant (generate → wrap → persist the wrapped DEK);
10
+ * • binds the versioned ciphertext so a decrypt loads the exact DEK the data was written under
11
+ * (survives key rotation);
12
+ * • supports rotation (`rotateDek`) — the engine mints + persists a new DEK version; the batch
13
+ * re-encryption of existing rows is the consumer's job (the engine exposes the primitive).
14
+ *
15
+ * FAIL-CLOSED: a decrypt that can't resolve/unwrap the DEK or fails the AEAD tag THROWS — never
16
+ * returns plaintext, ciphertext, or empty. An encrypt that can't provision/wrap a DEK THROWS — a
17
+ * plaintext is NEVER written unencrypted as a fallback.
18
+ *
19
+ * THREAT MODEL (ADR-0031): defends the STORAGE boundary (disk/dump/backup → ciphertext only). Does
20
+ * NOT defend a compromised app host (it must hold the DEK in memory) or a compromised KMS.
21
+ */
22
+ /** Thrown when a decrypt cannot proceed (missing/unwrappable DEK, tag mismatch). Fail-closed. */
23
+ export class DecryptionError extends Error {
24
+ /** Underlying cause (a port outage, a tag mismatch) — for admin logging; never surfaced/leaked. */
25
+ cause;
26
+ constructor(message, cause) {
27
+ super(message);
28
+ this.name = 'DecryptionError';
29
+ this.cause = cause;
30
+ }
31
+ }
32
+ /** Thrown when an encrypt cannot provision/wrap a DEK. No plaintext is ever written unencrypted. */
33
+ export class EncryptionError extends Error {
34
+ /** Underlying cause — for admin logging; never surfaced/leaked. */
35
+ cause;
36
+ constructor(message, cause) {
37
+ super(message);
38
+ this.name = 'EncryptionError';
39
+ this.cause = cause;
40
+ }
41
+ }
42
+ function requireTenant(tenantId) {
43
+ if (typeof tenantId !== 'string' || tenantId.trim() === '') {
44
+ throw new EncryptionError('tenantId is required (non-empty).');
45
+ }
46
+ }
47
+ export function createEncryptionService(deps) {
48
+ const { crypto, dekStore, dekCache } = deps;
49
+ /** Resolve a tenant's CURRENT DEK: cache → store(current) → unwrap → cache. Provisions on absence. */
50
+ async function currentDek(tenantId) {
51
+ // The cache holds the CURRENT dek only; a version bump evicts it (see rotateDek).
52
+ const cached = dekCache?.get(tenantId);
53
+ let record;
54
+ try {
55
+ record = await dekStore.getCurrent(tenantId);
56
+ }
57
+ catch (cause) {
58
+ // Store outage is NOT "no key" — fail closed loudly, never provision-over-an-outage.
59
+ throw new EncryptionError('DEK store unavailable', cause);
60
+ }
61
+ if (record === null) {
62
+ // First use for this tenant: provision a DEK (generate → wrap → persist v1).
63
+ return provisionDek(tenantId);
64
+ }
65
+ if (cached !== undefined)
66
+ return { dek: cached, version: record.version };
67
+ let dek;
68
+ try {
69
+ dek = await crypto.unwrapDek(record.wrapped, tenantId);
70
+ }
71
+ catch (cause) {
72
+ throw new EncryptionError('could not unwrap the current DEK', cause);
73
+ }
74
+ dekCache?.put(tenantId, dek);
75
+ return { dek, version: record.version };
76
+ }
77
+ /** Resolve a SPECIFIC version's DEK (for decrypting data under an older key). No provisioning. */
78
+ async function dekForVersion(tenantId, version) {
79
+ let record;
80
+ try {
81
+ record = await dekStore.getVersion(tenantId, version);
82
+ }
83
+ catch (cause) {
84
+ throw new DecryptionError('DEK store unavailable', cause);
85
+ }
86
+ if (record === null) {
87
+ throw new DecryptionError(`no DEK version ${version} for tenant '${tenantId}'`);
88
+ }
89
+ try {
90
+ return await crypto.unwrapDek(record.wrapped, tenantId);
91
+ }
92
+ catch (cause) {
93
+ throw new DecryptionError('could not unwrap the DEK', cause);
94
+ }
95
+ }
96
+ async function provisionDek(tenantId) {
97
+ let dek;
98
+ let wrapped;
99
+ try {
100
+ dek = await crypto.generateDek();
101
+ wrapped = await crypto.wrapDek(dek, tenantId);
102
+ }
103
+ catch (cause) {
104
+ throw new EncryptionError('could not generate/wrap a new DEK', cause);
105
+ }
106
+ const version = 1;
107
+ try {
108
+ await dekStore.put({ tenantId, version, wrapped });
109
+ }
110
+ catch (cause) {
111
+ // A concurrent provision may have created v1 first — re-read the current and use it (idempotent-ish).
112
+ const existing = await dekStore.getCurrent(tenantId).catch(() => null);
113
+ if (existing) {
114
+ const existingDek = await crypto.unwrapDek(existing.wrapped, tenantId);
115
+ dekCache?.put(tenantId, existingDek);
116
+ return { dek: existingDek, version: existing.version };
117
+ }
118
+ throw new EncryptionError('could not persist the new DEK', cause);
119
+ }
120
+ dekCache?.put(tenantId, dek);
121
+ return { dek, version };
122
+ }
123
+ return {
124
+ async encryptFor(tenantId, plaintext) {
125
+ requireTenant(tenantId);
126
+ const { dek, version } = await currentDek(tenantId);
127
+ let ciphertext;
128
+ try {
129
+ ciphertext = await crypto.encrypt(plaintext, dek, tenantId);
130
+ }
131
+ catch (cause) {
132
+ throw new EncryptionError('encryption failed', cause);
133
+ }
134
+ return { tenantId, version, ciphertext };
135
+ },
136
+ async decryptFor(tenantId, envelope) {
137
+ requireTenant(tenantId);
138
+ // Defence in depth: the caller-supplied tenant MUST match the envelope's stamp.
139
+ if (envelope.tenantId !== tenantId) {
140
+ throw new DecryptionError('tenant mismatch between caller and envelope (cross-tenant guard)');
141
+ }
142
+ // Prefer the cached current DEK when the envelope is at the current version; else load by version.
143
+ const dek = await dekForVersion(tenantId, envelope.version);
144
+ try {
145
+ return await crypto.decrypt(envelope.ciphertext, dek, tenantId);
146
+ }
147
+ catch (cause) {
148
+ // A tag/AAD mismatch or malformed ciphertext → fail closed. Never leak plaintext/ciphertext.
149
+ throw new DecryptionError('decryption failed (tag mismatch or malformed ciphertext)', cause);
150
+ }
151
+ },
152
+ async rotateDek(tenantId) {
153
+ requireTenant(tenantId);
154
+ let current;
155
+ try {
156
+ current = await dekStore.getCurrent(tenantId);
157
+ }
158
+ catch (cause) {
159
+ throw new EncryptionError('DEK store unavailable', cause);
160
+ }
161
+ const nextVersion = (current?.version ?? 0) + 1;
162
+ let dek;
163
+ let wrapped;
164
+ try {
165
+ dek = await crypto.generateDek();
166
+ wrapped = await crypto.wrapDek(dek, tenantId);
167
+ await dekStore.put({ tenantId, version: nextVersion, wrapped });
168
+ }
169
+ catch (cause) {
170
+ throw new EncryptionError('could not rotate the DEK', cause);
171
+ }
172
+ // The new DEK is now current; drop the stale cached one so the next op unwraps the new one.
173
+ dekCache?.evict(tenantId);
174
+ dekCache?.put(tenantId, dek);
175
+ return nextVersion;
176
+ },
177
+ async destroyTenantKeys(tenantId) {
178
+ requireTenant(tenantId);
179
+ dekCache?.evict(tenantId);
180
+ await dekStore.destroy(tenantId);
181
+ },
182
+ };
183
+ }
184
+ //# sourceMappingURL=encryption-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption-service.js","sourceRoot":"","sources":["../../src/encryption/encryption-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;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,QAAQ,CAAC,CAAC;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,eAAe,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC;YAC5D,CAAC;YACD,MAAM,WAAW,GAAG,CAAC,OAAO,EAAE,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;YAChD,IAAI,GAAQ,CAAC;YACb,IAAI,OAAO,CAAC;YACZ,IAAI,CAAC;gBACH,GAAG,GAAG,MAAM,MAAM,CAAC,WAAW,EAAE,CAAC;gBACjC,OAAO,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;gBAC9C,MAAM,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC;YAClE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,eAAe,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YAC/D,CAAC;YACD,4FAA4F;YAC5F,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC1B,QAAQ,EAAE,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC7B,OAAO,WAAW,CAAC;QACrB,CAAC;QAED,KAAK,CAAC,iBAAiB,CAAC,QAAQ;YAC9B,aAAa,CAAC,QAAQ,CAAC,CAAC;YACxB,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC1B,MAAM,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACnC,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Engine seam: **Encryption** — per-tenant envelope encryption for data at rest (ADR-0031).
3
+ *
4
+ * `createEncryptionService` encrypts/decrypts a tenant's data with that tenant's own DEK; DEKs are
5
+ * wrapped by a KMS-held KEK and only wrapped DEKs are ever persisted. Pure + zero-dep (ADR-0003):
6
+ * crypto/KMS/persistence are injected ports, shipped as adapters in `@astram/guard`.
7
+ *
8
+ * THREAT MODEL (ADR-0031, stated honestly): defends the STORAGE boundary (stolen disk / DB dump /
9
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). Does NOT defend a compromised app host
10
+ * or a compromised KMS. See `docs/Shield/140_Security_Hardening` + ADR-0031.
11
+ *
12
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
13
+ */
14
+ export type { Dek, WrappedDek, Ciphertext, CryptoPort, DekStore, DekCache, WrappedDekRecord, } from './ports.js';
15
+ export { createEncryptionService, DecryptionError, EncryptionError, } from './encryption-service.js';
16
+ export type { EncryptionService, EncryptionServiceDeps, Envelope, } from './encryption-service.js';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/encryption/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,YAAY,EACV,GAAG,EACH,UAAU,EACV,UAAU,EACV,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,gBAAgB,GACjB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,eAAe,GAChB,MAAM,yBAAyB,CAAC;AAEjC,YAAY,EACV,iBAAiB,EACjB,qBAAqB,EACrB,QAAQ,GACT,MAAM,yBAAyB,CAAC"}