@astram/core 1.2.0 → 1.4.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 (187) hide show
  1. package/dist/admin/admin-service.d.ts +15 -7
  2. package/dist/admin/admin-service.d.ts.map +1 -1
  3. package/dist/admin/admin-service.js +18 -10
  4. package/dist/admin/admin-service.js.map +1 -1
  5. package/dist/admin/command/grants.d.ts.map +1 -1
  6. package/dist/admin/command/grants.js +2 -5
  7. package/dist/admin/command/grants.js.map +1 -1
  8. package/dist/admin/command/invitations.d.ts.map +1 -1
  9. package/dist/admin/command/invitations.js +3 -6
  10. package/dist/admin/command/invitations.js.map +1 -1
  11. package/dist/admin/command/permissions.d.ts.map +1 -1
  12. package/dist/admin/command/permissions.js +2 -6
  13. package/dist/admin/command/permissions.js.map +1 -1
  14. package/dist/admin/command/pipeline.d.ts +5 -2
  15. package/dist/admin/command/pipeline.d.ts.map +1 -1
  16. package/dist/admin/command/pipeline.js +6 -3
  17. package/dist/admin/command/pipeline.js.map +1 -1
  18. package/dist/admin/command/policies.d.ts.map +1 -1
  19. package/dist/admin/command/policies.js +7 -22
  20. package/dist/admin/command/policies.js.map +1 -1
  21. package/dist/admin/command/service-accounts.d.ts +17 -11
  22. package/dist/admin/command/service-accounts.d.ts.map +1 -1
  23. package/dist/admin/command/service-accounts.js +18 -24
  24. package/dist/admin/command/service-accounts.js.map +1 -1
  25. package/dist/admin/command/service.d.ts +5 -1
  26. package/dist/admin/command/service.d.ts.map +1 -1
  27. package/dist/admin/command/service.js +3 -5
  28. package/dist/admin/command/service.js.map +1 -1
  29. package/dist/admin/command/tiers.d.ts.map +1 -1
  30. package/dist/admin/command/tiers.js.map +1 -1
  31. package/dist/admin/index.d.ts.map +1 -1
  32. package/dist/admin/index.js +3 -2
  33. package/dist/admin/index.js.map +1 -1
  34. package/dist/admin/ports.d.ts.map +1 -1
  35. package/dist/admin/ports.js.map +1 -1
  36. package/dist/admin/query/catalog.d.ts.map +1 -1
  37. package/dist/admin/query/catalog.js +5 -13
  38. package/dist/admin/query/catalog.js.map +1 -1
  39. package/dist/admin/query/index.d.ts +2 -2
  40. package/dist/admin/query/index.d.ts.map +1 -1
  41. package/dist/admin/query/index.js +2 -2
  42. package/dist/admin/query/index.js.map +1 -1
  43. package/dist/admin/safeguards-impl.d.ts.map +1 -1
  44. package/dist/admin/safeguards-impl.js +3 -7
  45. package/dist/admin/safeguards-impl.js.map +1 -1
  46. package/dist/admin/safeguards.d.ts.map +1 -1
  47. package/dist/admin/safeguards.js.map +1 -1
  48. package/dist/admin/types.d.ts +12 -0
  49. package/dist/admin/types.d.ts.map +1 -1
  50. package/dist/admin/types.js.map +1 -1
  51. package/dist/audit/audit-recorder.d.ts.map +1 -1
  52. package/dist/audit/audit-recorder.js +1 -2
  53. package/dist/audit/audit-recorder.js.map +1 -1
  54. package/dist/audit/sensitive.d.ts.map +1 -1
  55. package/dist/audit/sensitive.js.map +1 -1
  56. package/dist/audit/walk.d.ts.map +1 -1
  57. package/dist/audit/walk.js +1 -4
  58. package/dist/audit/walk.js.map +1 -1
  59. package/dist/authentication/authenticator.d.ts.map +1 -1
  60. package/dist/authentication/authenticator.js.map +1 -1
  61. package/dist/authentication/index.d.ts +1 -0
  62. package/dist/authentication/index.d.ts.map +1 -1
  63. package/dist/authentication/index.js +2 -0
  64. package/dist/authentication/index.js.map +1 -1
  65. package/dist/authentication/service-account-authenticator.d.ts +82 -0
  66. package/dist/authentication/service-account-authenticator.d.ts.map +1 -0
  67. package/dist/authentication/service-account-authenticator.js +72 -0
  68. package/dist/authentication/service-account-authenticator.js.map +1 -0
  69. package/dist/authentication/totp.d.ts.map +1 -1
  70. package/dist/authentication/totp.js.map +1 -1
  71. package/dist/authorization/cross-tenant/grant-evaluator.d.ts.map +1 -1
  72. package/dist/authorization/cross-tenant/grant-evaluator.js.map +1 -1
  73. package/dist/authorization/decision-authority.d.ts +1 -1
  74. package/dist/authorization/decision-authority.d.ts.map +1 -1
  75. package/dist/authorization/decision-authority.js +5 -6
  76. package/dist/authorization/decision-authority.js.map +1 -1
  77. package/dist/authorization/default-gates.d.ts.map +1 -1
  78. package/dist/authorization/default-gates.js.map +1 -1
  79. package/dist/authorization/delegation/operation-identity.d.ts.map +1 -1
  80. package/dist/authorization/delegation/operation-identity.js.map +1 -1
  81. package/dist/authorization/errors.d.ts.map +1 -1
  82. package/dist/authorization/errors.js.map +1 -1
  83. package/dist/authorization/gates/object-type.d.ts +2 -2
  84. package/dist/authorization/gates/object-type.d.ts.map +1 -1
  85. package/dist/authorization/gates/object-type.js +5 -7
  86. package/dist/authorization/gates/object-type.js.map +1 -1
  87. package/dist/authorization/gates/wiring.d.ts.map +1 -1
  88. package/dist/authorization/gates/wiring.js.map +1 -1
  89. package/dist/authorization/ports.d.ts +17 -0
  90. package/dist/authorization/ports.d.ts.map +1 -1
  91. package/dist/authorization/reason-codes.js.map +1 -1
  92. package/dist/authorization/record/owner-baseline.d.ts.map +1 -1
  93. package/dist/authorization/record/owner-baseline.js +1 -3
  94. package/dist/authorization/record/owner-baseline.js.map +1 -1
  95. package/dist/authorization/record/permit-tier.d.ts.map +1 -1
  96. package/dist/authorization/record/permit-tier.js.map +1 -1
  97. package/dist/authorization/record/shares.d.ts.map +1 -1
  98. package/dist/authorization/record/shares.js.map +1 -1
  99. package/dist/encryption/encryption-service.d.ts +63 -0
  100. package/dist/encryption/encryption-service.d.ts.map +1 -0
  101. package/dist/encryption/encryption-service.js +229 -0
  102. package/dist/encryption/encryption-service.js.map +1 -0
  103. package/dist/encryption/index.d.ts +17 -0
  104. package/dist/encryption/index.d.ts.map +1 -0
  105. package/dist/encryption/index.js +15 -0
  106. package/dist/encryption/index.js.map +1 -0
  107. package/dist/encryption/ports.d.ts +88 -0
  108. package/dist/encryption/ports.d.ts.map +1 -0
  109. package/dist/encryption/ports.js +18 -0
  110. package/dist/encryption/ports.js.map +1 -0
  111. package/dist/identity/broker.d.ts.map +1 -1
  112. package/dist/identity/broker.js +2 -4
  113. package/dist/identity/broker.js.map +1 -1
  114. package/dist/identity/internal-adapter.d.ts.map +1 -1
  115. package/dist/identity/internal-adapter.js.map +1 -1
  116. package/dist/index.d.ts +2 -0
  117. package/dist/index.d.ts.map +1 -1
  118. package/dist/index.js +2 -0
  119. package/dist/index.js.map +1 -1
  120. package/dist/metadata/completeness.d.ts.map +1 -1
  121. package/dist/metadata/completeness.js +2 -2
  122. package/dist/metadata/completeness.js.map +1 -1
  123. package/dist/metadata/dependencies.d.ts.map +1 -1
  124. package/dist/metadata/dependencies.js.map +1 -1
  125. package/dist/metadata/index.d.ts +19 -0
  126. package/dist/metadata/index.d.ts.map +1 -1
  127. package/dist/metadata/index.js +24 -0
  128. package/dist/metadata/index.js.map +1 -1
  129. package/dist/metadata/registry.d.ts.map +1 -1
  130. package/dist/metadata/registry.js +24 -0
  131. package/dist/metadata/registry.js.map +1 -1
  132. package/dist/risk/risk-engine.d.ts.map +1 -1
  133. package/dist/risk/risk-engine.js +1 -3
  134. package/dist/risk/risk-engine.js.map +1 -1
  135. package/dist/risk/signals.d.ts.map +1 -1
  136. package/dist/risk/signals.js +1 -2
  137. package/dist/risk/signals.js.map +1 -1
  138. package/dist/risk/thresholds.d.ts.map +1 -1
  139. package/dist/risk/thresholds.js.map +1 -1
  140. package/dist/secrets/index.d.ts +15 -0
  141. package/dist/secrets/index.d.ts.map +1 -0
  142. package/dist/secrets/index.js +14 -0
  143. package/dist/secrets/index.js.map +1 -0
  144. package/dist/secrets/ports.d.ts +45 -0
  145. package/dist/secrets/ports.d.ts.map +1 -0
  146. package/dist/secrets/ports.js +26 -0
  147. package/dist/secrets/ports.js.map +1 -0
  148. package/dist/secrets/resolve.d.ts +29 -0
  149. package/dist/secrets/resolve.d.ts.map +1 -0
  150. package/dist/secrets/resolve.js +49 -0
  151. package/dist/secrets/resolve.js.map +1 -0
  152. package/dist/session/lifetimes.d.ts.map +1 -1
  153. package/dist/session/lifetimes.js.map +1 -1
  154. package/dist/session/session-authority.d.ts.map +1 -1
  155. package/dist/session/session-authority.js.map +1 -1
  156. package/dist-cjs/admin/admin-service.js +18 -10
  157. package/dist-cjs/admin/command/grants.js +2 -5
  158. package/dist-cjs/admin/command/invitations.js +3 -6
  159. package/dist-cjs/admin/command/permissions.js +2 -6
  160. package/dist-cjs/admin/command/pipeline.js +6 -3
  161. package/dist-cjs/admin/command/policies.js +7 -22
  162. package/dist-cjs/admin/command/service-accounts.js +18 -24
  163. package/dist-cjs/admin/command/service.js +2 -4
  164. package/dist-cjs/admin/index.js +3 -2
  165. package/dist-cjs/admin/query/catalog.js +5 -13
  166. package/dist-cjs/admin/safeguards-impl.js +3 -7
  167. package/dist-cjs/audit/audit-recorder.js +1 -2
  168. package/dist-cjs/audit/walk.js +1 -4
  169. package/dist-cjs/authentication/index.js +2 -0
  170. package/dist-cjs/authentication/service-account-authenticator.js +76 -0
  171. package/dist-cjs/authorization/decision-authority.js +5 -6
  172. package/dist-cjs/authorization/gates/object-type.js +4 -6
  173. package/dist-cjs/authorization/record/owner-baseline.js +1 -3
  174. package/dist-cjs/encryption/encryption-service.js +234 -0
  175. package/dist-cjs/encryption/index.js +20 -0
  176. package/dist-cjs/encryption/ports.js +18 -0
  177. package/dist-cjs/identity/broker.js +1 -3
  178. package/dist-cjs/index.js +2 -0
  179. package/dist-cjs/metadata/completeness.js +2 -2
  180. package/dist-cjs/metadata/index.js +25 -0
  181. package/dist-cjs/metadata/registry.js +24 -0
  182. package/dist-cjs/risk/risk-engine.js +1 -3
  183. package/dist-cjs/risk/signals.js +1 -2
  184. package/dist-cjs/secrets/index.js +21 -0
  185. package/dist-cjs/secrets/ports.js +29 -0
  186. package/dist-cjs/secrets/resolve.js +54 -0
  187. package/package.json +1 -1
@@ -54,6 +54,7 @@ exports.gateContinue = gateContinue;
54
54
  exports.gateAllow = gateAllow;
55
55
  exports.gateDeny = gateDeny;
56
56
  exports.createDecisionAuthority = createDecisionAuthority;
57
+ const index_js_1 = require("../metadata/index.js");
57
58
  const errors_js_1 = require("./errors.js");
58
59
  const reason_codes_js_1 = require("./reason-codes.js");
59
60
  /** Constructor: this gate is satisfied / not applicable — proceed. */
@@ -112,12 +113,10 @@ class DecisionAuthorityImpl {
112
113
  // A `public` action is reachable with NO authz and consults NO port. Resolve
113
114
  // the action's baseline tier from the registry via the canonical `resolveTier`
114
115
  // rule (never re-implement the `?? 'gated'` default). We locate the registered
115
- // action by its (typeKey, actionKey) over the frozen `listActions()` surface;
116
- // an action not registered for this type resolves to the fail-closed `gated`
117
- // default (it will be denied downstream — never silently opened).
118
- const registered = registry
119
- .listActions()
120
- .find((a) => a.action.typeKey === resource.typeKey && a.action.actionKey === action.key);
116
+ // action by its (typeKey, actionKey) via `findRegisteredAction` (indexed;
117
+ // ambiguity fails closed — B-4 / D12); an action not registered for this type
118
+ // resolves to the fail-closed `gated` default (denied downstream).
119
+ const registered = (0, index_js_1.findRegisteredAction)(registry, resource.typeKey, action.key);
121
120
  // Prefer the registry's ALREADY-RESOLVED `tier` (single-source; the registry
122
121
  // derived it via the canonical `resolveTier` at registration) over re-calling
123
122
  // `resolveTier(registered.action)` here — behavior identical. An action not
@@ -13,8 +13,8 @@
13
13
  * permission key (ADR-0010) — `moduleKey:typeKey:actionKey`. The pipeline
14
14
  * resolved the {@link RegisteredAction} at gate 1 but does NOT stash it on the
15
15
  * read-only {@link GateContext}, so this gate re-resolves it over the FROZEN
16
- * registry surface (`listActions()` matched by `typeKey + actionKey`), exactly
17
- * as the pipeline does, and reads its `permissionKey`. An action not registered
16
+ * registry via `findRegisteredAction(typeKey, actionKey)` (indexed; ambiguity
17
+ * fails closed), exactly as the pipeline does, and reads its `permissionKey`. An action not registered
18
18
  * for this type has no derivable grant → `deny(missing_object_type_grant)`.
19
19
  *
20
20
  * ── Coarse-grants source (ADR-0011, hot path, in order):
@@ -144,10 +144,8 @@ function createObjectTypeGate() {
144
144
  }
145
145
  // ── Same-tenant (or root) path — coarse feature/object-type grants
146
146
  // (ADR-0011). Derive the required stable permission key by re-resolving the
147
- // registered action over the frozen registry surface.
148
- const registered = deps.registry
149
- .listActions()
150
- .find((a) => a.action.typeKey === resource.typeKey && a.action.actionKey === action.key);
147
+ // registered action (indexed; ambiguity fails closed — B-4 / D12).
148
+ const registered = (0, index_js_1.findRegisteredAction)(deps.registry, resource.typeKey, action.key);
151
149
  if (registered === undefined) {
152
150
  // Unregistered action for this type ⇒ no permission key to grant against.
153
151
  return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyMissingObjectTypeGrant)());
@@ -64,9 +64,7 @@ function evaluateOwnerBaseline(ctx) {
64
64
  // but this security primitive must not depend on that — it fails closed on empty identity.
65
65
  if (access.owned === true) {
66
66
  const ownerId = ctx.context.attributes?.ownerId;
67
- return (typeof ownerId === 'string' &&
68
- ownerId.length > 0 &&
69
- ownerId === ctx.principal.id);
67
+ return typeof ownerId === 'string' && ownerId.length > 0 && ownerId === ctx.principal.id;
70
68
  }
71
69
  // owned:false, tenantScoped:false, system:false — an explicitly ungoverned posture.
72
70
  // No baseline permit (fail-closed).
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ /**
3
+ * The **Encryption engine** (ADR-0031) — per-tenant envelope encryption for data at rest.
4
+ *
5
+ * `createEncryptionService({ crypto, dekStore, dekCache })` returns the ONE service the platform
6
+ * uses to encrypt/decrypt a tenant's data with that tenant's own DEK. It is PURE + zero-dep: all
7
+ * crypto, KMS, and persistence are injected ports (ADR-0003). The service:
8
+ * • resolves a tenant's DEK: cache → else load the WRAPPED DEK from the store → `crypto.unwrapDek`
9
+ * → cache it (so the hot path unwraps at most once per tenant per TTL);
10
+ * • PROVISIONS a DEK on first encrypt for a tenant (generate → wrap → persist the wrapped DEK);
11
+ * • binds the versioned ciphertext so a decrypt loads the exact DEK the data was written under
12
+ * (survives key rotation);
13
+ * • supports rotation (`rotateDek`) — the engine mints + persists a new DEK version; the batch
14
+ * re-encryption of existing rows is the consumer's job (the engine exposes the primitive).
15
+ *
16
+ * FAIL-CLOSED: a decrypt that can't resolve/unwrap the DEK or fails the AEAD tag THROWS — never
17
+ * returns plaintext, ciphertext, or empty. An encrypt that can't provision/wrap a DEK THROWS — a
18
+ * plaintext is NEVER written unencrypted as a fallback.
19
+ *
20
+ * THREAT MODEL (ADR-0031): defends the STORAGE boundary (disk/dump/backup → ciphertext only). Does
21
+ * NOT defend a compromised app host (it must hold the DEK in memory) or a compromised KMS.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.EncryptionError = exports.DecryptionError = void 0;
25
+ exports.createEncryptionService = createEncryptionService;
26
+ /** Thrown when a decrypt cannot proceed (missing/unwrappable DEK, tag mismatch). Fail-closed. */
27
+ class DecryptionError extends Error {
28
+ /** Underlying cause (a port outage, a tag mismatch) — for admin logging; never surfaced/leaked. */
29
+ cause;
30
+ constructor(message, cause) {
31
+ super(message);
32
+ this.name = 'DecryptionError';
33
+ this.cause = cause;
34
+ }
35
+ }
36
+ exports.DecryptionError = DecryptionError;
37
+ /** Thrown when an encrypt cannot provision/wrap a DEK. No plaintext is ever written unencrypted. */
38
+ class EncryptionError extends Error {
39
+ /** Underlying cause — for admin logging; never surfaced/leaked. */
40
+ cause;
41
+ constructor(message, cause) {
42
+ super(message);
43
+ this.name = 'EncryptionError';
44
+ this.cause = cause;
45
+ }
46
+ }
47
+ exports.EncryptionError = EncryptionError;
48
+ function requireTenant(tenantId) {
49
+ if (typeof tenantId !== 'string' || tenantId.trim() === '') {
50
+ throw new EncryptionError('tenantId is required (non-empty).');
51
+ }
52
+ }
53
+ /**
54
+ * The {@link DekCache} key for ONE specific wrapped DEK: tenant + version + the wrapped bytes (hex).
55
+ *
56
+ * B-1 (security-hardening Phase 5): the cache used to be keyed by tenant alone and a hit was
57
+ * labelled with the store's current version, so after a rotation on ANOTHER instance this instance
58
+ * encrypted under its stale cached key while stamping the new version (permanently undecryptable).
59
+ * Binding the key to the exact `(version, wrapped)` record means a cache entry can only ever be
60
+ * served for the DEK it was unwrapped from: a rotation (new version) or a shred + re-provision
61
+ * (same version, new wrapped bytes) is a cache MISS, never a wrong key. The wrapped DEK is the
62
+ * already-persisted, KEK-encrypted form — not secret material — and the cache is memory-only.
63
+ */
64
+ function dekCacheKey(tenantId, version, wrapped) {
65
+ let hex = '';
66
+ for (const byte of wrapped)
67
+ hex += byte.toString(16).padStart(2, '0');
68
+ return `${tenantId}#v${String(version)}#${hex}`;
69
+ }
70
+ function createEncryptionService(deps) {
71
+ const { crypto, dekStore, dekCache } = deps;
72
+ /** Cache keys this instance has written, per tenant — so rotate/shred can evict them locally. */
73
+ const cachedKeysByTenant = new Map();
74
+ function cachePut(tenantId, version, wrapped, dek) {
75
+ if (dekCache === undefined)
76
+ return;
77
+ const key = dekCacheKey(tenantId, version, wrapped);
78
+ dekCache.put(key, dek);
79
+ let keys = cachedKeysByTenant.get(tenantId);
80
+ if (keys === undefined) {
81
+ keys = new Set();
82
+ cachedKeysByTenant.set(tenantId, keys);
83
+ }
84
+ keys.add(key);
85
+ }
86
+ function evictTenant(tenantId) {
87
+ if (dekCache === undefined)
88
+ return;
89
+ for (const key of cachedKeysByTenant.get(tenantId) ?? [])
90
+ dekCache.evict(key);
91
+ cachedKeysByTenant.delete(tenantId);
92
+ // Legacy tenant-only key (pre-1.4 entries in a shared cache adapter): drop it too.
93
+ dekCache.evict(tenantId);
94
+ }
95
+ /** Resolve a tenant's CURRENT DEK: store(current) → cache(version-bound) → unwrap → cache. Provisions on absence. */
96
+ async function currentDek(tenantId) {
97
+ let record;
98
+ try {
99
+ record = await dekStore.getCurrent(tenantId);
100
+ }
101
+ catch (cause) {
102
+ // Store outage is NOT "no key" — fail closed loudly, never provision-over-an-outage.
103
+ throw new EncryptionError('DEK store unavailable', cause);
104
+ }
105
+ if (record === null) {
106
+ // First use for this tenant: provision a DEK (generate → wrap → persist v1).
107
+ return provisionDek(tenantId);
108
+ }
109
+ // The cache entry is bound to THIS record's (version, wrapped) — a hit is always the right DEK.
110
+ const cached = dekCache?.get(dekCacheKey(tenantId, record.version, record.wrapped));
111
+ if (cached !== undefined)
112
+ return { dek: cached, version: record.version };
113
+ let dek;
114
+ try {
115
+ dek = await crypto.unwrapDek(record.wrapped, tenantId);
116
+ }
117
+ catch (cause) {
118
+ throw new EncryptionError('could not unwrap the current DEK', cause);
119
+ }
120
+ // A newer version superseded whatever this instance cached for the tenant: drop it.
121
+ evictTenant(tenantId);
122
+ cachePut(tenantId, record.version, record.wrapped, dek);
123
+ return { dek, version: record.version };
124
+ }
125
+ /** Resolve a SPECIFIC version's DEK (for decrypting data under an older key). No provisioning. */
126
+ async function dekForVersion(tenantId, version) {
127
+ let record;
128
+ try {
129
+ record = await dekStore.getVersion(tenantId, version);
130
+ }
131
+ catch (cause) {
132
+ throw new DecryptionError('DEK store unavailable', cause);
133
+ }
134
+ if (record === null) {
135
+ throw new DecryptionError(`no DEK version ${version} for tenant '${tenantId}'`);
136
+ }
137
+ try {
138
+ return await crypto.unwrapDek(record.wrapped, tenantId);
139
+ }
140
+ catch (cause) {
141
+ throw new DecryptionError('could not unwrap the DEK', cause);
142
+ }
143
+ }
144
+ async function provisionDek(tenantId) {
145
+ let dek;
146
+ let wrapped;
147
+ try {
148
+ dek = await crypto.generateDek();
149
+ wrapped = await crypto.wrapDek(dek, tenantId);
150
+ }
151
+ catch (cause) {
152
+ throw new EncryptionError('could not generate/wrap a new DEK', cause);
153
+ }
154
+ const version = 1;
155
+ try {
156
+ await dekStore.put({ tenantId, version, wrapped });
157
+ }
158
+ catch (cause) {
159
+ // A concurrent provision may have created v1 first — re-read the current and use it (idempotent-ish).
160
+ const existing = await dekStore.getCurrent(tenantId).catch(() => null);
161
+ if (existing) {
162
+ const existingDek = await crypto.unwrapDek(existing.wrapped, tenantId);
163
+ evictTenant(tenantId);
164
+ cachePut(tenantId, existing.version, existing.wrapped, existingDek);
165
+ return { dek: existingDek, version: existing.version };
166
+ }
167
+ throw new EncryptionError('could not persist the new DEK', cause);
168
+ }
169
+ evictTenant(tenantId);
170
+ cachePut(tenantId, version, wrapped, dek);
171
+ return { dek, version };
172
+ }
173
+ return {
174
+ async encryptFor(tenantId, plaintext) {
175
+ requireTenant(tenantId);
176
+ const { dek, version } = await currentDek(tenantId);
177
+ let ciphertext;
178
+ try {
179
+ ciphertext = await crypto.encrypt(plaintext, dek, tenantId);
180
+ }
181
+ catch (cause) {
182
+ throw new EncryptionError('encryption failed', cause);
183
+ }
184
+ return { tenantId, version, ciphertext };
185
+ },
186
+ async decryptFor(tenantId, envelope) {
187
+ requireTenant(tenantId);
188
+ // Defence in depth: the caller-supplied tenant MUST match the envelope's stamp.
189
+ if (envelope.tenantId !== tenantId) {
190
+ throw new DecryptionError('tenant mismatch between caller and envelope (cross-tenant guard)');
191
+ }
192
+ // Always load the DEK for the envelope's OWN version from the store (never the cache).
193
+ const dek = await dekForVersion(tenantId, envelope.version);
194
+ try {
195
+ return await crypto.decrypt(envelope.ciphertext, dek, tenantId);
196
+ }
197
+ catch (cause) {
198
+ // A tag/AAD mismatch or malformed ciphertext → fail closed. Never leak plaintext/ciphertext.
199
+ throw new DecryptionError('decryption failed (tag mismatch or malformed ciphertext)', cause);
200
+ }
201
+ },
202
+ async rotateDek(tenantId) {
203
+ requireTenant(tenantId);
204
+ let current;
205
+ try {
206
+ current = await dekStore.getCurrent(tenantId);
207
+ }
208
+ catch (cause) {
209
+ throw new EncryptionError('DEK store unavailable', cause);
210
+ }
211
+ const nextVersion = (current?.version ?? 0) + 1;
212
+ let dek;
213
+ let wrapped;
214
+ try {
215
+ dek = await crypto.generateDek();
216
+ wrapped = await crypto.wrapDek(dek, tenantId);
217
+ await dekStore.put({ tenantId, version: nextVersion, wrapped });
218
+ }
219
+ catch (cause) {
220
+ throw new EncryptionError('could not rotate the DEK', cause);
221
+ }
222
+ // The new DEK is now current; drop this instance's stale entries and cache the new one
223
+ // (version-bound, so other instances simply miss on their next op — see dekCacheKey).
224
+ evictTenant(tenantId);
225
+ cachePut(tenantId, nextVersion, wrapped, dek);
226
+ return nextVersion;
227
+ },
228
+ async destroyTenantKeys(tenantId) {
229
+ requireTenant(tenantId);
230
+ evictTenant(tenantId);
231
+ await dekStore.destroy(tenantId);
232
+ },
233
+ };
234
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ /**
3
+ * Engine seam: **Encryption** — per-tenant envelope encryption for data at rest (ADR-0031).
4
+ *
5
+ * `createEncryptionService` encrypts/decrypts a tenant's data with that tenant's own DEK; DEKs are
6
+ * wrapped by a KMS-held KEK and only wrapped DEKs are ever persisted. Pure + zero-dep (ADR-0003):
7
+ * crypto/KMS/persistence are injected ports, shipped as adapters in `@astram/guard`.
8
+ *
9
+ * THREAT MODEL (ADR-0031, stated honestly): defends the STORAGE boundary (stolen disk / DB dump /
10
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). Does NOT defend a compromised app host
11
+ * or a compromised KMS. See `docs/Shield/140_Security_Hardening` + ADR-0031.
12
+ *
13
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.EncryptionError = exports.DecryptionError = exports.createEncryptionService = void 0;
17
+ var encryption_service_js_1 = require("./encryption-service.js");
18
+ Object.defineProperty(exports, "createEncryptionService", { enumerable: true, get: function () { return encryption_service_js_1.createEncryptionService; } });
19
+ Object.defineProperty(exports, "DecryptionError", { enumerable: true, get: function () { return encryption_service_js_1.DecryptionError; } });
20
+ Object.defineProperty(exports, "EncryptionError", { enumerable: true, get: function () { return encryption_service_js_1.EncryptionError; } });
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /**
3
+ * Encryption engine PORTS — the framework-agnostic contracts the {@link EncryptionService} uses,
4
+ * WITHOUT the engine ever knowing the algorithm, the KMS, or where wrapped DEKs are stored.
5
+ *
6
+ * ADR-0031 (envelope encryption / per-tenant DEKs) + ADR-0003 (zero-dep core): real crypto needs a
7
+ * library + native bindings and a KMS needs network/SDK — neither can live in `@astram/core`. The
8
+ * core defines only these interfaces; `@astram/guard` ships the concrete AEAD + KMS + DEK-store
9
+ * adapters and INJECTS them into `createEncryptionService`. Core stays at ZERO runtime deps.
10
+ *
11
+ * THREAT MODEL (ADR-0031, honest): this defends the STORAGE boundary (stolen disk / DB dump /
12
+ * backup / leaked bucket → only ciphertext + wrapped DEKs). It does NOT defend a compromised app
13
+ * host (the app must hold a tenant's DEK in memory to serve it) or a compromised KMS.
14
+ *
15
+ * SECURITY: no port implementation may log a plaintext, a DEK, or a plaintext key. DEKs and
16
+ * plaintext are transient inputs; they are never surfaced in a result, a reason, or a log.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -132,9 +132,7 @@ class BrokerImpl {
132
132
  function createIdentityBroker(options = {}) {
133
133
  const registry = new claim_mapper_js_1.IdentityClaimMapperRegistry();
134
134
  if (options.mappers === undefined) {
135
- registry.register((0, internal_adapter_js_1.createInternalIdentityAdapter)(options.internalRootIds !== undefined
136
- ? { rootIds: options.internalRootIds }
137
- : {}));
135
+ registry.register((0, internal_adapter_js_1.createInternalIdentityAdapter)(options.internalRootIds !== undefined ? { rootIds: options.internalRootIds } : {}));
138
136
  }
139
137
  else {
140
138
  for (const mapper of options.mappers) {
package/dist-cjs/index.js CHANGED
@@ -55,6 +55,8 @@ __exportStar(require("./session/index.js"), exports);
55
55
  __exportStar(require("./risk/index.js"), exports);
56
56
  __exportStar(require("./authorization/index.js"), exports);
57
57
  __exportStar(require("./audit/index.js"), exports);
58
+ __exportStar(require("./encryption/index.js"), exports);
59
+ __exportStar(require("./secrets/index.js"), exports);
58
60
  // Module-registers-metadata contract + pure derivation rules + completeness check.
59
61
  __exportStar(require("./metadata/index.js"), exports);
60
62
  // Admin Console (Layer 10) — a NEW top-level module (append-only; no frozen
@@ -95,8 +95,8 @@ function checkCompleteness(inventory, registry) {
95
95
  }
96
96
  }
97
97
  // Deterministic ordering — stable, total sort keys.
98
- unclassifiedOperations.sort((a, b) => (a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0));
99
- strandedOperations.sort((a, b) => (a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0));
98
+ unclassifiedOperations.sort((a, b) => a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0);
99
+ strandedOperations.sort((a, b) => a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0);
100
100
  orphanedPermissions.sort((a, b) => a.permissionKey < b.permissionKey ? -1 : a.permissionKey > b.permissionKey ? 1 : 0);
101
101
  const passed = unclassifiedOperations.length === 0 && strandedOperations.length === 0;
102
102
  return {
@@ -34,6 +34,7 @@ exports.DEFAULT_CAPABILITY_PLANE = void 0;
34
34
  exports.resolveTier = resolveTier;
35
35
  exports.resolvePlane = resolvePlane;
36
36
  exports.resolveActionPermissionKey = resolveActionPermissionKey;
37
+ exports.findRegisteredAction = findRegisteredAction;
37
38
  const index_js_1 = require("../authorization/index.js");
38
39
  // The boot-completeness-check contract (ADR-0002/0010) — types + signature only.
39
40
  __exportStar(require("./completeness.js"), exports);
@@ -74,3 +75,27 @@ function resolvePlane(action) {
74
75
  function resolveActionPermissionKey(moduleKey, action) {
75
76
  return (0, index_js_1.derivePermissionKey)(moduleKey, action.typeKey, action.actionKey);
76
77
  }
78
+ /**
79
+ * Resolve the registered action for `(typeKey, actionKey)` — the ONE lookup the
80
+ * decision path uses for tier / permission-key resolution (B-4 / D12).
81
+ *
82
+ * Uses the registry's indexed {@link ModuleRegistry.resolveAction} when present.
83
+ * Otherwise scans `listActions()`; if MORE THAN ONE action matches the pair (a
84
+ * registry that does not enforce uniqueness), returns `undefined` so the caller
85
+ * treats the action as unregistered ⇒ `gated` ⇒ denied downstream. Fail closed:
86
+ * an ambiguous declaration can never resolve to whichever came first.
87
+ */
88
+ function findRegisteredAction(registry, typeKey, actionKey) {
89
+ if (typeof registry.resolveAction === 'function') {
90
+ return registry.resolveAction(typeKey, actionKey);
91
+ }
92
+ let found;
93
+ for (const a of registry.listActions()) {
94
+ if (a.action.typeKey === typeKey && a.action.actionKey === actionKey) {
95
+ if (found !== undefined)
96
+ return undefined; // ambiguous ⇒ fail closed
97
+ found = a;
98
+ }
99
+ }
100
+ return found;
101
+ }
@@ -36,6 +36,15 @@ class InMemoryModuleRegistry {
36
36
  objectTypeIndex = new Map();
37
37
  /** Index: stable {@link PermissionKey} → the resolved action that owns it. */
38
38
  actionIndex = new Map();
39
+ /**
40
+ * Index: `(typeKey, actionKey)` → the ONE resolved action declaring it, across
41
+ * ALL modules (D12: cross-module actions allowed, duplicates rejected). Keyed by
42
+ * a JSON tuple so no separator can make two distinct pairs collide.
43
+ */
44
+ typeActionIndex = new Map();
45
+ static pairKey(typeKey, actionKey) {
46
+ return JSON.stringify([typeKey, actionKey]);
47
+ }
39
48
  register(metadata) {
40
49
  const { moduleKey } = metadata;
41
50
  if (moduleKey.length === 0) {
@@ -74,6 +83,15 @@ class InMemoryModuleRegistry {
74
83
  if (this.actionIndex.has(permissionKey)) {
75
84
  throw new Error(`ModuleRegistry.register: permission key "${permissionKey}" (module "${moduleKey}") collides with an already-registered action`);
76
85
  }
86
+ // (2b) D12 / B-4: a module MAY declare an action on another module's type,
87
+ // but the (typeKey, actionKey) pair must be unique across ALL modules —
88
+ // a second declaration could otherwise change the action's tier/plane
89
+ // depending on registration order. (Within-module duplicates were
90
+ // already rejected by assertActionUnique above.)
91
+ const owner = this.typeActionIndex.get(InMemoryModuleRegistry.pairKey(action.typeKey, action.actionKey));
92
+ if (owner !== undefined) {
93
+ throw new Error(`ModuleRegistry.register: module "${moduleKey}" declares duplicate action "${action.actionKey}" on object type "${action.typeKey}", already declared by module "${owner.moduleKey}"`);
94
+ }
77
95
  resolvedActions.push({
78
96
  moduleKey,
79
97
  action,
@@ -107,8 +125,14 @@ class InMemoryModuleRegistry {
107
125
  }
108
126
  for (const resolved of resolvedActions) {
109
127
  this.actionIndex.set(resolved.permissionKey, resolved);
128
+ this.typeActionIndex.set(InMemoryModuleRegistry.pairKey(resolved.action.typeKey, resolved.action.actionKey), resolved);
110
129
  }
111
130
  }
131
+ resolveAction(typeKey, actionKey) {
132
+ // Indexed (D12). A miss ⇒ the decision path treats the action as `gated`
133
+ // (denied downstream). Return undefined, NEVER throw.
134
+ return this.typeActionIndex.get(InMemoryModuleRegistry.pairKey(typeKey, actionKey));
135
+ }
112
136
  registerDynamicObjectType(objectType) {
113
137
  const { typeKey } = objectType;
114
138
  if (typeKey.length === 0) {
@@ -78,9 +78,7 @@ function combine(contributions) {
78
78
  // then SORT ascending so the fold order is deterministic for a given multiset —
79
79
  // making `value` order-independent to the BIT (IEEE-754 is commutative but not
80
80
  // associative, so a fixed order is required, not just commutativity).
81
- const sorted = contributions
82
- .map((c) => (c < 0 ? 0 : c > 1 ? 1 : c))
83
- .sort((a, b) => a - b);
81
+ const sorted = contributions.map((c) => (c < 0 ? 0 : c > 1 ? 1 : c)).sort((a, b) => a - b);
84
82
  let complement = 1;
85
83
  for (const c of sorted) {
86
84
  complement *= 1 - c;
@@ -86,8 +86,7 @@ exports.SENSITIVE_ACTION_EVALUATOR = Object.freeze({
86
86
  name: exports.SENSITIVE_ACTION_EVALUATOR_NAME,
87
87
  kind: 'context',
88
88
  evaluate(signal) {
89
- const flag = signal?.value
90
- ?.sensitiveAction;
89
+ const flag = signal?.value?.sensitiveAction;
91
90
  if (flag === true) {
92
91
  return Object.freeze({ contribution: CONFIRMED_RISK_CONTRIBUTION, kind: 'context' });
93
92
  }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * Engine seam: **Secrets** — env holds references, credentials resolved at runtime + rotatable
4
+ * (ADR-0032). `secret-ref:<path>` in env is a pointer (safe to commit/log); `resolveSecretRefs`
5
+ * fetches the real value at boot via an injected `SecretsProvider`. Pure + zero-dep (ADR-0003);
6
+ * backends (encrypted on-box store now; Vault / AWS SM / GCP SM later) ship in `@astram/guard`.
7
+ *
8
+ * SECURITY: a secret value is never logged/surfaced (only paths + versions). Fail-closed: an
9
+ * unresolvable reference aborts boot; a literal value is unchanged (backward compatible).
10
+ *
11
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / fs imports.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.resolveSecretRefs = exports.secretRefPath = exports.isSecretRef = exports.SECRET_REF_PREFIX = exports.SecretNotFoundError = void 0;
15
+ var ports_js_1 = require("./ports.js");
16
+ Object.defineProperty(exports, "SecretNotFoundError", { enumerable: true, get: function () { return ports_js_1.SecretNotFoundError; } });
17
+ var resolve_js_1 = require("./resolve.js");
18
+ Object.defineProperty(exports, "SECRET_REF_PREFIX", { enumerable: true, get: function () { return resolve_js_1.SECRET_REF_PREFIX; } });
19
+ Object.defineProperty(exports, "isSecretRef", { enumerable: true, get: function () { return resolve_js_1.isSecretRef; } });
20
+ Object.defineProperty(exports, "secretRefPath", { enumerable: true, get: function () { return resolve_js_1.secretRefPath; } });
21
+ Object.defineProperty(exports, "resolveSecretRefs", { enumerable: true, get: function () { return resolve_js_1.resolveSecretRefs; } });
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ /**
3
+ * Secrets provider PORT (ADR-0032) — the framework-agnostic contract for fetching + rotating
4
+ * credentials, so the runtime reads a REFERENCE from env (`secret-ref:db/prod/password`) and the
5
+ * real value is resolved at boot from a secrets backend, NEVER hard-coded in env/Git.
6
+ *
7
+ * ADR-0003 (zero-dep core): the backend is a real dependency (a network vault SDK, or an encrypted
8
+ * on-box store using node crypto) — it cannot live here. Core defines only this interface;
9
+ * `@astram/guard` ships the concrete backends (a reference encrypted on-box store now; Vault / AWS
10
+ * Secrets Manager / GCP Secret Manager as drop-in adapters) and INJECTS one. Core stays zero-dep.
11
+ *
12
+ * SECURITY: a secret VALUE is never logged, never in an error message, never in an audit record —
13
+ * only the PATH + version. A `SecretsProvider` implementation MUST likewise never log a value.
14
+ * Fail-closed: a missing secret THROWS (must never silently resolve to '' — that would start the
15
+ * app with a hole where a credential belongs).
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.SecretNotFoundError = void 0;
19
+ /** Thrown by `resolve` when a referenced secret is absent — fail-closed (never a silent empty). */
20
+ class SecretNotFoundError extends Error {
21
+ cause;
22
+ constructor(path, cause) {
23
+ // NOTE: includes the PATH (safe — a pointer, not a value), never the value.
24
+ super(`secret not found: '${path}'`);
25
+ this.name = 'SecretNotFoundError';
26
+ this.cause = cause;
27
+ }
28
+ }
29
+ exports.SecretNotFoundError = SecretNotFoundError;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SECRET_REF_PREFIX = void 0;
4
+ exports.isSecretRef = isSecretRef;
5
+ exports.secretRefPath = secretRefPath;
6
+ exports.resolveSecretRefs = resolveSecretRefs;
7
+ /** The prefix that marks an env value as a secret REFERENCE (a pointer, safe to log/commit). */
8
+ exports.SECRET_REF_PREFIX = 'secret-ref:';
9
+ /** True if `value` is a secret reference (not a literal). */
10
+ function isSecretRef(value) {
11
+ return typeof value === 'string' && value.startsWith(exports.SECRET_REF_PREFIX);
12
+ }
13
+ /** Extract the secret path from a reference (`secret-ref:db/prod/pw` → `db/prod/pw`). */
14
+ function secretRefPath(ref) {
15
+ return ref.slice(exports.SECRET_REF_PREFIX.length);
16
+ }
17
+ /**
18
+ * Resolve every `secret-ref:` value in `env` via `provider`, returning a NEW bag where references
19
+ * are replaced by their real values and literals are copied unchanged. Async (a fetch is I/O).
20
+ *
21
+ * Fail-closed: a reference with an EMPTY path, or one the provider cannot resolve, THROWS — the
22
+ * error names the ENV KEY + PATH (safe pointers), never the value. Non-string values are copied
23
+ * as-is. The input bag is not mutated.
24
+ */
25
+ async function resolveSecretRefs(env, provider) {
26
+ const out = {};
27
+ // Resolve sequentially-collected refs; a single failure aborts the whole resolution (fail-closed).
28
+ const refs = [];
29
+ for (const [key, value] of Object.entries(env)) {
30
+ if (isSecretRef(value)) {
31
+ const path = secretRefPath(value);
32
+ if (path.trim() === '') {
33
+ throw new Error(`invalid secret reference for env '${key}': empty path`);
34
+ }
35
+ refs.push({ key, path });
36
+ out[key] = undefined; // placeholder; filled below
37
+ }
38
+ else {
39
+ out[key] = value;
40
+ }
41
+ }
42
+ for (const { key, path } of refs) {
43
+ let resolved;
44
+ try {
45
+ resolved = await provider.resolve(path);
46
+ }
47
+ catch (cause) {
48
+ // Include the key + path (safe pointers), NEVER a value.
49
+ throw new Error(`could not resolve secret for env '${key}' (path '${path}')`, { cause });
50
+ }
51
+ out[key] = resolved;
52
+ }
53
+ return out;
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astram/core",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "license": "MIT",
5
5
  "description": "Astram framework — sealed security core (Identity, Authentication, Session, Risk, Authorization, Audit). ZERO framework deps — the portable decision brain (ADR-0003). The frozen public contract consumers build against; installed, not edited (ADR-0023).",
6
6
  "type": "module",