@astram/core 1.3.0 → 1.5.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 (166) 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/credential-resolver.d.ts +1 -1
  62. package/dist/authentication/service-account-authenticator.d.ts.map +1 -1
  63. package/dist/authentication/service-account-authenticator.js +1 -3
  64. package/dist/authentication/service-account-authenticator.js.map +1 -1
  65. package/dist/authentication/totp.d.ts.map +1 -1
  66. package/dist/authentication/totp.js.map +1 -1
  67. package/dist/authorization/cross-tenant/grant-evaluator.d.ts.map +1 -1
  68. package/dist/authorization/cross-tenant/grant-evaluator.js.map +1 -1
  69. package/dist/authorization/decision-authority.d.ts +1 -1
  70. package/dist/authorization/decision-authority.d.ts.map +1 -1
  71. package/dist/authorization/decision-authority.js +5 -6
  72. package/dist/authorization/decision-authority.js.map +1 -1
  73. package/dist/authorization/default-gates.d.ts.map +1 -1
  74. package/dist/authorization/default-gates.js.map +1 -1
  75. package/dist/authorization/delegation/operation-identity.d.ts.map +1 -1
  76. package/dist/authorization/delegation/operation-identity.js.map +1 -1
  77. package/dist/authorization/errors.d.ts.map +1 -1
  78. package/dist/authorization/errors.js.map +1 -1
  79. package/dist/authorization/gates/object-type.d.ts +2 -2
  80. package/dist/authorization/gates/object-type.d.ts.map +1 -1
  81. package/dist/authorization/gates/object-type.js +5 -7
  82. package/dist/authorization/gates/object-type.js.map +1 -1
  83. package/dist/authorization/gates/wiring.d.ts.map +1 -1
  84. package/dist/authorization/gates/wiring.js.map +1 -1
  85. package/dist/authorization/ports.d.ts +17 -0
  86. package/dist/authorization/ports.d.ts.map +1 -1
  87. package/dist/authorization/reason-codes.js.map +1 -1
  88. package/dist/authorization/record/owner-baseline.d.ts.map +1 -1
  89. package/dist/authorization/record/owner-baseline.js +1 -3
  90. package/dist/authorization/record/owner-baseline.js.map +1 -1
  91. package/dist/authorization/record/permit-tier.d.ts.map +1 -1
  92. package/dist/authorization/record/permit-tier.js.map +1 -1
  93. package/dist/authorization/record/shares.d.ts.map +1 -1
  94. package/dist/authorization/record/shares.js.map +1 -1
  95. package/dist/encryption/encryption-service.d.ts.map +1 -1
  96. package/dist/encryption/encryption-service.js +56 -11
  97. package/dist/encryption/encryption-service.js.map +1 -1
  98. package/dist/encryption/index.d.ts +2 -2
  99. package/dist/encryption/index.d.ts.map +1 -1
  100. package/dist/encryption/index.js +1 -1
  101. package/dist/encryption/index.js.map +1 -1
  102. package/dist/encryption/ports.d.ts +4 -0
  103. package/dist/encryption/ports.d.ts.map +1 -1
  104. package/dist/identity/broker.d.ts.map +1 -1
  105. package/dist/identity/broker.js +2 -4
  106. package/dist/identity/broker.js.map +1 -1
  107. package/dist/identity/internal-adapter.d.ts.map +1 -1
  108. package/dist/identity/internal-adapter.js.map +1 -1
  109. package/dist/metadata/completeness.d.ts.map +1 -1
  110. package/dist/metadata/completeness.js +2 -2
  111. package/dist/metadata/completeness.js.map +1 -1
  112. package/dist/metadata/dependencies.d.ts.map +1 -1
  113. package/dist/metadata/dependencies.js.map +1 -1
  114. package/dist/metadata/index.d.ts +19 -0
  115. package/dist/metadata/index.d.ts.map +1 -1
  116. package/dist/metadata/index.js +24 -0
  117. package/dist/metadata/index.js.map +1 -1
  118. package/dist/metadata/registry.d.ts.map +1 -1
  119. package/dist/metadata/registry.js +24 -0
  120. package/dist/metadata/registry.js.map +1 -1
  121. package/dist/risk/risk-engine.d.ts.map +1 -1
  122. package/dist/risk/risk-engine.js +1 -3
  123. package/dist/risk/risk-engine.js.map +1 -1
  124. package/dist/risk/signals.d.ts.map +1 -1
  125. package/dist/risk/signals.js +1 -2
  126. package/dist/risk/signals.js.map +1 -1
  127. package/dist/risk/thresholds.d.ts.map +1 -1
  128. package/dist/risk/thresholds.js.map +1 -1
  129. package/dist/secrets/index.d.ts +1 -1
  130. package/dist/secrets/index.d.ts.map +1 -1
  131. package/dist/secrets/index.js +1 -1
  132. package/dist/secrets/index.js.map +1 -1
  133. package/dist/session/lifetimes.d.ts.map +1 -1
  134. package/dist/session/lifetimes.js.map +1 -1
  135. package/dist/session/ports.d.ts +34 -0
  136. package/dist/session/ports.d.ts.map +1 -1
  137. package/dist/session/session-authority.d.ts +21 -1
  138. package/dist/session/session-authority.d.ts.map +1 -1
  139. package/dist/session/session-authority.js +152 -6
  140. package/dist/session/session-authority.js.map +1 -1
  141. package/dist-cjs/admin/admin-service.js +18 -10
  142. package/dist-cjs/admin/command/grants.js +2 -5
  143. package/dist-cjs/admin/command/invitations.js +3 -6
  144. package/dist-cjs/admin/command/permissions.js +2 -6
  145. package/dist-cjs/admin/command/pipeline.js +6 -3
  146. package/dist-cjs/admin/command/policies.js +7 -22
  147. package/dist-cjs/admin/command/service-accounts.js +18 -24
  148. package/dist-cjs/admin/command/service.js +2 -4
  149. package/dist-cjs/admin/index.js +3 -2
  150. package/dist-cjs/admin/query/catalog.js +5 -13
  151. package/dist-cjs/admin/safeguards-impl.js +3 -7
  152. package/dist-cjs/audit/audit-recorder.js +1 -2
  153. package/dist-cjs/audit/walk.js +1 -4
  154. package/dist-cjs/authentication/service-account-authenticator.js +1 -3
  155. package/dist-cjs/authorization/decision-authority.js +5 -6
  156. package/dist-cjs/authorization/gates/object-type.js +4 -6
  157. package/dist-cjs/authorization/record/owner-baseline.js +1 -3
  158. package/dist-cjs/encryption/encryption-service.js +56 -11
  159. package/dist-cjs/identity/broker.js +1 -3
  160. package/dist-cjs/metadata/completeness.js +2 -2
  161. package/dist-cjs/metadata/index.js +25 -0
  162. package/dist-cjs/metadata/registry.js +24 -0
  163. package/dist-cjs/risk/risk-engine.js +1 -3
  164. package/dist-cjs/risk/signals.js +1 -2
  165. package/dist-cjs/session/session-authority.js +153 -7
  166. package/package.json +1 -1
@@ -51,25 +51,14 @@ const NULLARY_OPERATORS = new Set([
51
51
  /** Operators whose operand MUST be an array (set membership). */
52
52
  const ARRAY_OPERATORS = new Set(['in', 'not_in']);
53
53
  /** Operators that are ownership predicates — only valid on a REFERENCE field. */
54
- const OWNERSHIP_OPERATORS = new Set([
55
- 'is_owner',
56
- 'is_not_owner',
57
- ]);
54
+ const OWNERSHIP_OPERATORS = new Set(['is_owner', 'is_not_owner']);
58
55
  /**
59
56
  * Ordered/relational operators (`gt`/`lt`/`gte`/`lte`) — valid on scalar
60
57
  * (non-reference) fields, never on a reference field (you don't order a reference).
61
58
  */
62
- const RELATIONAL_OPERATORS = new Set([
63
- 'gt',
64
- 'lt',
65
- 'gte',
66
- 'lte',
67
- ]);
59
+ const RELATIONAL_OPERATORS = new Set(['gt', 'lt', 'gte', 'lte']);
68
60
  /** Text operators (`contains`/`not_contains`) — valid on scalar fields only. */
69
- const TEXT_OPERATORS = new Set([
70
- 'contains',
71
- 'not_contains',
72
- ]);
61
+ const TEXT_OPERATORS = new Set(['contains', 'not_contains']);
73
62
  /**
74
63
  * Is `operator` valid for a field, given whether the field is a REFERENCE field
75
64
  * (carries `referencesTypeKey`)? This is the field-type↔operator compatibility
@@ -81,8 +70,7 @@ const TEXT_OPERATORS = new Set([
81
70
  * valid on any field.
82
71
  */
83
72
  function operatorValidForField(operator, field) {
84
- const isReference = typeof field.referencesTypeKey === 'string' &&
85
- field.referencesTypeKey.length > 0;
73
+ const isReference = typeof field.referencesTypeKey === 'string' && field.referencesTypeKey.length > 0;
86
74
  if (OWNERSHIP_OPERATORS.has(operator)) {
87
75
  return isReference;
88
76
  }
@@ -103,14 +91,12 @@ function valueWellFormed(operator, value) {
103
91
  return value === undefined || value === null;
104
92
  }
105
93
  if (ARRAY_OPERATORS.has(operator)) {
106
- return (Array.isArray(value) &&
107
- value.length > 0 &&
108
- value.every((v) => isPrimitive(v)));
94
+ return Array.isArray(value) && value.length > 0 && value.every((v) => isPrimitive(v));
109
95
  }
110
96
  return isPrimitive(value);
111
97
  }
112
98
  function isPrimitive(v) {
113
- return (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean');
99
+ return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';
114
100
  }
115
101
  /**
116
102
  * SHAPE validation of a single condition, WITHOUT the registry (used by the grant
@@ -127,8 +113,7 @@ function isValidCondition(condition) {
127
113
  if (typeof c.field !== 'string' || c.field.length === 0) {
128
114
  return false;
129
115
  }
130
- if (typeof c.operator !== 'string' ||
131
- !ALL_OPERATORS.has(c.operator)) {
116
+ if (typeof c.operator !== 'string' || !ALL_OPERATORS.has(c.operator)) {
132
117
  return false;
133
118
  }
134
119
  return valueWellFormed(c.operator, c.value);
@@ -11,10 +11,12 @@
11
11
  *
12
12
  * ⛔ CREDENTIAL CRYPTO. The credential HASH is produced by the Auth layer's hasher
13
13
  * port (never here), then persisted via {@link ServiceAccountStore.setCredentialHash}.
14
- * `AdminCommandDeps` carries no hasher, so rotate takes an OPTIONAL injected
15
- * {@link PasswordHasher}; when absent it stores a caller-provided pre-computed hash
16
- * (the credential is minted/hashed by the adapter). This file NEVER logs/returns a
17
- * secret or a hash.
14
+ * The NEW secret is always CALLER-held (B-6, security-hardening Phase 5): the caller
15
+ * generates it with a CSPRNG and delivers it to the account owner; rotate hashes the
16
+ * caller's `secret` with the injected {@link PasswordHasher}, or stores the caller's
17
+ * `precomputedHash`. Rotate NEVER mints a secret (a minted secret could not be
18
+ * returned, so the rotation would leave an unusable credential). This file NEVER
19
+ * logs/returns a secret or a hash.
18
20
  *
19
21
  * Revocation is IMMEDIATE (the store's revoke is idempotent).
20
22
  *
@@ -28,12 +30,6 @@ exports.makeRevokeServiceAccount = makeRevokeServiceAccount;
28
30
  exports.makeSetServiceAccountExpiry = makeSetServiceAccountExpiry;
29
31
  const grants_js_1 = require("./grants.js");
30
32
  const pipeline_js_1 = require("./pipeline.js");
31
- function defaultSecret() {
32
- // A non-cryptographic placeholder is acceptable ONLY because the real secret
33
- // generation is the adapter's job (this Core file has no crypto dep); the value
34
- // is immediately hashed and never returned. Adapters inject a CSPRNG generator.
35
- return `sa-secret-${String(Date.now())}-${String(Math.random()).slice(2)}`;
36
- }
37
33
  function makeCreateServiceAccount(deps) {
38
34
  const clock = deps.now ?? Date.now;
39
35
  return async function createServiceAccount(mutation, input) {
@@ -63,9 +59,7 @@ function makeCreateServiceAccount(deps) {
63
59
  tenantId: input.tenantId,
64
60
  label: input.label,
65
61
  scope: input.scope,
66
- ...(input.expiresAtMs !== undefined
67
- ? { expiresAtMs: input.expiresAtMs }
68
- : {}),
62
+ ...(input.expiresAtMs !== undefined ? { expiresAtMs: input.expiresAtMs } : {}),
69
63
  }),
70
64
  emitAudit: async (value, blastRadius) => {
71
65
  await deps.audit.record({
@@ -131,7 +125,6 @@ function makeScopeServiceAccount(deps) {
131
125
  }
132
126
  function makeRotateServiceAccountCredential(deps) {
133
127
  const clock = deps.now ?? Date.now;
134
- const mintSecret = deps.newSecret ?? defaultSecret;
135
128
  return async function rotateServiceAccountCredential(mutation, input) {
136
129
  return (0, pipeline_js_1.runAdminCommand)({
137
130
  mutation,
@@ -153,21 +146,23 @@ function makeRotateServiceAccountCredential(deps) {
153
146
  return null;
154
147
  },
155
148
  mutate: async () => {
156
- // Produce the HASH (never a raw secret leaves this scope). Prefer the
157
- // injected Auth hasher; else accept a caller pre-computed hash.
149
+ // Produce the HASH from CALLER-held material only (B-6): hash the
150
+ // caller's secret with the injected Auth hasher, else accept the
151
+ // caller's pre-computed hash. NEVER mint-and-discard a secret.
158
152
  let hash;
159
- if (deps.hasher !== undefined) {
160
- const secret = mintSecret();
161
- hash = await deps.hasher.hash(secret);
153
+ if (deps.hasher !== undefined &&
154
+ typeof input.secret === 'string' &&
155
+ input.secret.length > 0) {
156
+ hash = await deps.hasher.hash(input.secret);
162
157
  }
163
158
  else if (typeof input.precomputedHash === 'string' &&
164
159
  input.precomputedHash.length > 0) {
165
160
  hash = input.precomputedHash;
166
161
  }
167
162
  else {
168
- // No hasher + no pre-computed hash → cannot rotate safely. Throw so the
169
- // caller sees a failure rather than persisting an empty credential.
170
- throw new Error('rotateServiceAccountCredential: no hasher injected and no precomputedHash provided');
163
+ // No usable caller material → cannot rotate safely. Throw BEFORE any
164
+ // write so the old credential stays valid and nothing is audited.
165
+ throw new Error('rotateServiceAccountCredential: supply the caller-generated `secret` (with a hasher injected) or a `precomputedHash`');
171
166
  }
172
167
  await deps.serviceAccountStore.setCredentialHash(input.id, hash);
173
168
  },
@@ -240,8 +235,7 @@ function makeSetServiceAccountExpiry(deps) {
240
235
  return { ok: false, reason: 'not_found' };
241
236
  }
242
237
  if (input.expiresAtMs !== null &&
243
- (typeof input.expiresAtMs !== 'number' ||
244
- !Number.isFinite(input.expiresAtMs))) {
238
+ (typeof input.expiresAtMs !== 'number' || !Number.isFinite(input.expiresAtMs))) {
245
239
  return { ok: false, reason: 'invalid_policy' };
246
240
  }
247
241
  const existing = await deps.serviceAccountStore.get(input.id);
@@ -30,9 +30,7 @@ const tiers_js_1 = require("./tiers.js");
30
30
  function curatePermissionKey(mutation) {
31
31
  const payload = mutation.payload;
32
32
  const key = payload?.permissionKey;
33
- return typeof key === 'string' && key.length > 0
34
- ? key
35
- : undefined;
33
+ return typeof key === 'string' && key.length > 0 ? key : undefined;
36
34
  }
37
35
  /**
38
36
  * Create the REAL admin COMMAND service. Conforms to the frozen
@@ -69,7 +67,7 @@ function createRealAdminCommandService(deps) {
69
67
  serviceAccountStore: deps.serviceAccountStore,
70
68
  ...common,
71
69
  ...(deps.hasher !== undefined ? { hasher: deps.hasher } : {}),
72
- ...(deps.newSecret !== undefined ? { newSecret: deps.newSecret } : {}),
70
+ // `deps.newSecret` is deprecated and deliberately NOT forwarded (B-6).
73
71
  };
74
72
  const createServiceAccount = (0, service_accounts_js_1.makeCreateServiceAccount)(saDeps);
75
73
  const scopeServiceAccount = (0, service_accounts_js_1.makeScopeServiceAccount)(saDeps);
@@ -51,8 +51,9 @@ __exportStar(require("./ports.js"), exports);
51
51
  __exportStar(require("./types.js"), exports);
52
52
  // The §11.3 SAFEGUARD signatures + fail-closed defaults (Team B implements bodies):
53
53
  __exportStar(require("./safeguards.js"), exports);
54
- // The query/command service factories + interfaces + the §11.3 command pipeline
55
- // order (the seam Teams A/B fill method-by-method):
54
+ // The query/command service interfaces + the §11.3 command pipeline order + the
55
+ // DEPRECATED fail-closed stub factories (`createAdminQueryService` /
56
+ // `createAdminCommandService`; use the real composers appended below):
56
57
  __exportStar(require("./admin-service.js"), exports);
57
58
  // ---------------------------------------------------------------------------
58
59
  // INTEGRATION APPEND (Layer-10 integration owner) — surface the REAL engine
@@ -48,9 +48,7 @@ function humanizeKey(key) {
48
48
  if (words.length === 0) {
49
49
  return key;
50
50
  }
51
- return words
52
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
53
- .join(' ');
51
+ return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
54
52
  }
55
53
  /**
56
54
  * Resolve a permission's human display label. Preference order (no raw ids):
@@ -116,7 +114,7 @@ async function getCatalog(deps, tenantId) {
116
114
  entries.push(await buildEntry(action.permissionKey, action, curation, labels, tenantId));
117
115
  }
118
116
  // Deterministic ordering by the stable permission key.
119
- entries.sort((x, y) => (x.permissionKey < y.permissionKey ? -1 : x.permissionKey > y.permissionKey ? 1 : 0));
117
+ entries.sort((x, y) => x.permissionKey < y.permissionKey ? -1 : x.permissionKey > y.permissionKey ? 1 : 0);
120
118
  return entries;
121
119
  }
122
120
  /**
@@ -127,11 +125,7 @@ async function getCatalog(deps, tenantId) {
127
125
  * - NO live action (curation only) → `orphaned` (drift)
128
126
  */
129
127
  async function buildEntry(permissionKey, action, curation, labels, tenantId) {
130
- const classification = action === undefined
131
- ? 'orphaned'
132
- : curation !== null
133
- ? 'classified'
134
- : 'unclassified';
128
+ const classification = action === undefined ? 'orphaned' : curation !== null ? 'classified' : 'unclassified';
135
129
  const label = await resolvePermissionLabel(permissionKey, action, curation, labels, tenantId);
136
130
  const tier = action?.tier ?? 'gated';
137
131
  const actionEntries = action !== undefined ? [toActionEntry(action)] : [];
@@ -143,9 +137,7 @@ async function buildEntry(permissionKey, action, curation, labels, tenantId) {
143
137
  actions: actionEntries,
144
138
  classification,
145
139
  };
146
- return group !== undefined && group.length > 0
147
- ? { ...base, group }
148
- : base;
140
+ return group !== undefined && group.length > 0 ? { ...base, group } : base;
149
141
  }
150
142
  /**
151
143
  * Classify an explicit set of permission keys (e.g. the keys a set of grants
@@ -169,6 +161,6 @@ async function classifyKnownKeys(deps, keys, tenantId) {
169
161
  const curation = await catalogStore.getCuration(key);
170
162
  entries.push(await buildEntry(key, action, curation, labels, tenantId));
171
163
  }
172
- entries.sort((x, y) => (x.permissionKey < y.permissionKey ? -1 : x.permissionKey > y.permissionKey ? 1 : 0));
164
+ entries.sort((x, y) => x.permissionKey < y.permissionKey ? -1 : x.permissionKey > y.permissionKey ? 1 : 0);
173
165
  return entries;
174
166
  }
@@ -115,8 +115,7 @@ function requiredAuthorities(command) {
115
115
  // Payload carries the target permission key (the tier command's subject).
116
116
  const key = typeof command.payload === 'string'
117
117
  ? command.payload
118
- : command.payload
119
- ?.permissionKey;
118
+ : command.payload?.permissionKey;
120
119
  if (typeof key !== 'string') {
121
120
  return null;
122
121
  }
@@ -181,8 +180,7 @@ async function checkDelegatedAdminImpl(admin, command, decide) {
181
180
  // tenant than their own is refused. The ONLY non-root cross-tenant
182
181
  // path is the consent invitation (invitation_create), which is not an
183
182
  // authority-bounded direct grant and is allowed through here.
184
- if (AUTHORITY_BOUNDED_KINDS.has(command.kind) &&
185
- command.targetTenantId !== admin.tenantId) {
183
+ if (AUTHORITY_BOUNDED_KINDS.has(command.kind) && command.targetTenantId !== admin.tenantId) {
186
184
  return { ok: false, reason: 'unilateral_cross_tenant' };
187
185
  }
188
186
  // (2) NON-AUTHORITY-BROADENING kinds (curate, invitation create/transition,
@@ -255,9 +253,7 @@ async function computeBlastRadiusImpl(command, deps = {}) {
255
253
  // Cross-tenant whole-object-type invitation — describe the ceiling (§3.7).
256
254
  if (command.kind === 'invitation_create') {
257
255
  const payload = command.payload;
258
- const types = Array.isArray(payload?.objectTypeKeys)
259
- ? payload.objectTypeKeys.length
260
- : 0;
256
+ const types = Array.isArray(payload?.objectTypeKeys) ? payload.objectTypeKeys.length : 0;
261
257
  return {
262
258
  affectedPrincipalCount: 0,
263
259
  description: types > 0
@@ -257,8 +257,7 @@ function verifyChain(records, hash) {
257
257
  };
258
258
  const recomputedContentHash = hash.hash((0, canonicalize_js_1.canonicalizeEvent)(cleanEvent));
259
259
  const recomputedEntryHash = hash.hash(entryPreimage(recomputedContentHash, record.prevHash, record.sequenceNumber));
260
- if (recomputedContentHash !== record.contentHash ||
261
- recomputedEntryHash !== record.entryHash) {
260
+ if (recomputedContentHash !== record.contentHash || recomputedEntryHash !== record.entryHash) {
262
261
  return { intact: false, brokenIndex: i, reason: 'content_mismatch' };
263
262
  }
264
263
  // Advance the expected link/sequence to THIS record's recomputed entryHash.
@@ -77,10 +77,7 @@ function isSpecialLeaf(value) {
77
77
  * `Object.create(null)` bag and a `class Foo {}` instance both qualify.
78
78
  */
79
79
  function isDescendableObject(value) {
80
- return (value !== null &&
81
- typeof value === 'object' &&
82
- !Array.isArray(value) &&
83
- !isSpecialLeaf(value));
80
+ return (value !== null && typeof value === 'object' && !Array.isArray(value) && !isSpecialLeaf(value));
84
81
  }
85
82
  /**
86
83
  * Compute the collision-free structural tag for a `Date` leaf, or `undefined` for
@@ -65,9 +65,7 @@ function createServiceAuthenticator(deps) {
65
65
  kind: 'service_account',
66
66
  id: record.accountId,
67
67
  activeScopeNodeId: record.tenantId,
68
- scopeSubtreeNodeIds: record.scopeSubtreeNodeIds.length > 0
69
- ? record.scopeSubtreeNodeIds
70
- : [record.tenantId],
68
+ scopeSubtreeNodeIds: record.scopeSubtreeNodeIds.length > 0 ? record.scopeSubtreeNodeIds : [record.tenantId],
71
69
  tenantId: record.tenantId,
72
70
  roleIds: record.roleIds,
73
71
  isRoot: false,
@@ -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).
@@ -50,12 +50,50 @@ function requireTenant(tenantId) {
50
50
  throw new EncryptionError('tenantId is required (non-empty).');
51
51
  }
52
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
+ }
53
70
  function createEncryptionService(deps) {
54
71
  const { crypto, dekStore, dekCache } = deps;
55
- /** Resolve a tenant's CURRENT DEK: cache → store(current) → unwrap → cache. Provisions on absence. */
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. */
56
96
  async function currentDek(tenantId) {
57
- // The cache holds the CURRENT dek only; a version bump evicts it (see rotateDek).
58
- const cached = dekCache?.get(tenantId);
59
97
  let record;
60
98
  try {
61
99
  record = await dekStore.getCurrent(tenantId);
@@ -68,6 +106,8 @@ function createEncryptionService(deps) {
68
106
  // First use for this tenant: provision a DEK (generate → wrap → persist v1).
69
107
  return provisionDek(tenantId);
70
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));
71
111
  if (cached !== undefined)
72
112
  return { dek: cached, version: record.version };
73
113
  let dek;
@@ -77,7 +117,9 @@ function createEncryptionService(deps) {
77
117
  catch (cause) {
78
118
  throw new EncryptionError('could not unwrap the current DEK', cause);
79
119
  }
80
- dekCache?.put(tenantId, dek);
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);
81
123
  return { dek, version: record.version };
82
124
  }
83
125
  /** Resolve a SPECIFIC version's DEK (for decrypting data under an older key). No provisioning. */
@@ -118,12 +160,14 @@ function createEncryptionService(deps) {
118
160
  const existing = await dekStore.getCurrent(tenantId).catch(() => null);
119
161
  if (existing) {
120
162
  const existingDek = await crypto.unwrapDek(existing.wrapped, tenantId);
121
- dekCache?.put(tenantId, existingDek);
163
+ evictTenant(tenantId);
164
+ cachePut(tenantId, existing.version, existing.wrapped, existingDek);
122
165
  return { dek: existingDek, version: existing.version };
123
166
  }
124
167
  throw new EncryptionError('could not persist the new DEK', cause);
125
168
  }
126
- dekCache?.put(tenantId, dek);
169
+ evictTenant(tenantId);
170
+ cachePut(tenantId, version, wrapped, dek);
127
171
  return { dek, version };
128
172
  }
129
173
  return {
@@ -145,7 +189,7 @@ function createEncryptionService(deps) {
145
189
  if (envelope.tenantId !== tenantId) {
146
190
  throw new DecryptionError('tenant mismatch between caller and envelope (cross-tenant guard)');
147
191
  }
148
- // Prefer the cached current DEK when the envelope is at the current version; else load by version.
192
+ // Always load the DEK for the envelope's OWN version from the store (never the cache).
149
193
  const dek = await dekForVersion(tenantId, envelope.version);
150
194
  try {
151
195
  return await crypto.decrypt(envelope.ciphertext, dek, tenantId);
@@ -175,14 +219,15 @@ function createEncryptionService(deps) {
175
219
  catch (cause) {
176
220
  throw new EncryptionError('could not rotate the DEK', cause);
177
221
  }
178
- // The new DEK is now current; drop the stale cached one so the next op unwraps the new one.
179
- dekCache?.evict(tenantId);
180
- dekCache?.put(tenantId, dek);
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);
181
226
  return nextVersion;
182
227
  },
183
228
  async destroyTenantKeys(tenantId) {
184
229
  requireTenant(tenantId);
185
- dekCache?.evict(tenantId);
230
+ evictTenant(tenantId);
186
231
  await dekStore.destroy(tenantId);
187
232
  },
188
233
  };
@@ -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) {
@@ -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
  }