@astram/core 0.1.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/admin/admin-service.d.ts +1 -1
  2. package/dist/admin/command/grants.js +3 -3
  3. package/dist/admin/command/grants.js.map +1 -1
  4. package/dist/admin/command/invitations.d.ts +2 -2
  5. package/dist/admin/command/invitations.js +8 -8
  6. package/dist/admin/command/invitations.js.map +1 -1
  7. package/dist/admin/command/service-accounts.d.ts +1 -1
  8. package/dist/admin/command/service-accounts.js +1 -1
  9. package/dist/admin/query/simulate.d.ts.map +1 -1
  10. package/dist/admin/query/simulate.js +4 -0
  11. package/dist/admin/query/simulate.js.map +1 -1
  12. package/dist/admin/safeguards-impl.d.ts +2 -2
  13. package/dist/admin/safeguards-impl.js +9 -9
  14. package/dist/admin/safeguards-impl.js.map +1 -1
  15. package/dist/admin/safeguards.d.ts +4 -4
  16. package/dist/admin/safeguards.js +4 -4
  17. package/dist/admin/types.d.ts +1 -1
  18. package/dist/admin/types.d.ts.map +1 -1
  19. package/dist/authentication/authenticator.d.ts +2 -2
  20. package/dist/authentication/authenticator.js +2 -2
  21. package/dist/authentication/authenticator.js.map +1 -1
  22. package/dist/authentication/credential-resolver.d.ts +1 -1
  23. package/dist/authorization/cross-tenant/grant-evaluator.d.ts +2 -2
  24. package/dist/authorization/cross-tenant/grant-evaluator.js +2 -2
  25. package/dist/authorization/decision-authority.d.ts +2 -2
  26. package/dist/authorization/decision-authority.d.ts.map +1 -1
  27. package/dist/authorization/decision-authority.js +11 -3
  28. package/dist/authorization/decision-authority.js.map +1 -1
  29. package/dist/authorization/errors.d.ts +37 -0
  30. package/dist/authorization/errors.d.ts.map +1 -1
  31. package/dist/authorization/errors.js +43 -0
  32. package/dist/authorization/errors.js.map +1 -1
  33. package/dist/authorization/gates/object-type.d.ts +2 -2
  34. package/dist/authorization/gates/object-type.d.ts.map +1 -1
  35. package/dist/authorization/gates/object-type.js +20 -7
  36. package/dist/authorization/gates/object-type.js.map +1 -1
  37. package/dist/authorization/gates/tenant.d.ts +3 -3
  38. package/dist/authorization/gates/tenant.js +7 -7
  39. package/dist/authorization/gates/tenant.js.map +1 -1
  40. package/dist/authorization/index.d.ts +33 -4
  41. package/dist/authorization/index.d.ts.map +1 -1
  42. package/dist/authorization/index.js +39 -4
  43. package/dist/authorization/index.js.map +1 -1
  44. package/dist/authorization/ports.d.ts +3 -3
  45. package/dist/authorization/reason-codes.d.ts +7 -1
  46. package/dist/authorization/reason-codes.d.ts.map +1 -1
  47. package/dist/authorization/reason-codes.js +9 -1
  48. package/dist/authorization/reason-codes.js.map +1 -1
  49. package/dist/authorization/record/owner-baseline.d.ts +43 -0
  50. package/dist/authorization/record/owner-baseline.d.ts.map +1 -0
  51. package/dist/authorization/record/owner-baseline.js +72 -0
  52. package/dist/authorization/record/owner-baseline.js.map +1 -0
  53. package/dist/authorization/record/permit-tier.d.ts.map +1 -1
  54. package/dist/authorization/record/permit-tier.js +16 -5
  55. package/dist/authorization/record/permit-tier.js.map +1 -1
  56. package/dist/identity/broker.d.ts +8 -8
  57. package/dist/identity/broker.d.ts.map +1 -1
  58. package/dist/identity/broker.js +8 -8
  59. package/dist/identity/broker.js.map +1 -1
  60. package/dist/identity/claim-mapper.d.ts +8 -8
  61. package/dist/identity/claim-mapper.d.ts.map +1 -1
  62. package/dist/identity/claim-mapper.js +4 -4
  63. package/dist/identity/index.d.ts +2 -2
  64. package/dist/identity/index.d.ts.map +1 -1
  65. package/dist/identity/internal-adapter.d.ts +12 -12
  66. package/dist/identity/internal-adapter.d.ts.map +1 -1
  67. package/dist/identity/internal-adapter.js +9 -9
  68. package/dist/identity/internal-adapter.js.map +1 -1
  69. package/dist/metadata/index.d.ts +43 -0
  70. package/dist/metadata/index.d.ts.map +1 -1
  71. package/dist/metadata/index.js +6 -0
  72. package/dist/metadata/index.js.map +1 -1
  73. package/dist/metadata/registry.d.ts.map +1 -1
  74. package/dist/metadata/registry.js +2 -1
  75. package/dist/metadata/registry.js.map +1 -1
  76. package/dist-cjs/admin/admin-service.js +159 -0
  77. package/dist-cjs/admin/command/grants.js +200 -0
  78. package/dist-cjs/admin/command/index.js +38 -0
  79. package/dist-cjs/admin/command/invitations.js +246 -0
  80. package/dist-cjs/admin/command/permissions.js +69 -0
  81. package/dist-cjs/admin/command/pipeline.js +110 -0
  82. package/dist-cjs/admin/command/policies.js +223 -0
  83. package/dist-cjs/admin/command/service-accounts.js +278 -0
  84. package/dist-cjs/admin/command/service.js +130 -0
  85. package/dist-cjs/admin/command/tiers.js +81 -0
  86. package/dist-cjs/admin/index.js +78 -0
  87. package/dist-cjs/admin/ports.js +41 -0
  88. package/dist-cjs/admin/query/audit-view.js +88 -0
  89. package/dist-cjs/admin/query/catalog.js +174 -0
  90. package/dist-cjs/admin/query/explain.js +149 -0
  91. package/dist-cjs/admin/query/index.js +74 -0
  92. package/dist-cjs/admin/query/simulate.js +98 -0
  93. package/dist-cjs/admin/safeguards-impl.js +322 -0
  94. package/dist-cjs/admin/safeguards.js +95 -0
  95. package/dist-cjs/admin/types.js +40 -0
  96. package/dist-cjs/audit/audit-recorder.js +269 -0
  97. package/dist-cjs/audit/canonicalize.js +176 -0
  98. package/dist-cjs/audit/errors.js +44 -0
  99. package/dist-cjs/audit/index.js +39 -0
  100. package/dist-cjs/audit/ports.js +27 -0
  101. package/dist-cjs/audit/sensitive.js +162 -0
  102. package/dist-cjs/audit/walk.js +123 -0
  103. package/dist-cjs/authentication/authenticator.js +210 -0
  104. package/dist-cjs/authentication/credential-resolver.js +21 -0
  105. package/dist-cjs/authentication/index.js +42 -0
  106. package/dist-cjs/authentication/password-hasher.js +21 -0
  107. package/dist-cjs/authentication/totp.js +155 -0
  108. package/dist-cjs/authorization/cross-tenant/grant-evaluator.js +167 -0
  109. package/dist-cjs/authorization/decision-authority.js +213 -0
  110. package/dist-cjs/authorization/default-gates.js +53 -0
  111. package/dist-cjs/authorization/delegation/operation-identity.js +226 -0
  112. package/dist-cjs/authorization/errors.js +110 -0
  113. package/dist-cjs/authorization/gates/object-type.js +192 -0
  114. package/dist-cjs/authorization/gates/tenant.js +89 -0
  115. package/dist-cjs/authorization/gates/wiring.js +59 -0
  116. package/dist-cjs/authorization/index.js +134 -0
  117. package/dist-cjs/authorization/ports.js +36 -0
  118. package/dist-cjs/authorization/reason-codes.js +117 -0
  119. package/dist-cjs/authorization/record/owner-baseline.js +74 -0
  120. package/dist-cjs/authorization/record/permit-tier.js +92 -0
  121. package/dist-cjs/authorization/record/rule-evaluator.js +128 -0
  122. package/dist-cjs/authorization/record/shares.js +110 -0
  123. package/dist-cjs/identity/broker.js +139 -0
  124. package/dist-cjs/identity/claim-mapper.js +51 -0
  125. package/dist-cjs/identity/index.js +39 -0
  126. package/dist-cjs/identity/internal-adapter.js +91 -0
  127. package/dist-cjs/index.js +63 -0
  128. package/dist-cjs/metadata/completeness.js +108 -0
  129. package/dist-cjs/metadata/dependencies.js +110 -0
  130. package/dist-cjs/metadata/index.js +76 -0
  131. package/dist-cjs/metadata/registry.js +207 -0
  132. package/dist-cjs/package.json +3 -0
  133. package/dist-cjs/risk/evaluator.js +63 -0
  134. package/dist-cjs/risk/index.js +35 -0
  135. package/dist-cjs/risk/risk-engine.js +290 -0
  136. package/dist-cjs/risk/signals.js +106 -0
  137. package/dist-cjs/risk/thresholds.js +63 -0
  138. package/dist-cjs/session/index.js +35 -0
  139. package/dist-cjs/session/lifetimes.js +70 -0
  140. package/dist-cjs/session/ports.js +23 -0
  141. package/dist-cjs/session/session-authority.js +398 -0
  142. package/package.json +13 -10
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ /**
3
+ * Gate 7 — DELEGATION overlay / **trusted operation identity** (§10 / ADR-0008).
4
+ *
5
+ * The case (§10, worked example): ONE server operation performs an internal
6
+ * side-effect on a resource the CALLER may not modify directly — e.g. "create
7
+ * user" also writes an onboarding record in a SEPARATE object type the caller has
8
+ * no standing grant on. The requirement is that the internal step runs under the
9
+ * OPERATION's OWN declared, scoped, least-privilege authority — NOT the caller's
10
+ * grants, and NOT a wildcard "skip all checks".
11
+ *
12
+ * This overlay is the LAST gate the pipeline runs (`decision-authority.ts` gate 7).
13
+ * It receives the BASELINE `Decision` that gates 0–6 computed under the CALLER's
14
+ * identity and decides the FINAL outcome:
15
+ *
16
+ * • **Pass-through (the common case, §10.6).** The request is NOT a delegated
17
+ * internal step (no delegation marker), OR the operation declares no authority
18
+ * for this step (`resolveDelegatedAuthority → undefined`). The overlay does NOT
19
+ * override — it returns `gateContinue()`, so the gates-0–6 `baseline` stands
20
+ * (whatever it was, allow or a specific deny). Delegation NEVER silently widens
21
+ * a non-delegated request.
22
+ *
23
+ * • **Delegated step (§10.2/§10.3).** The request IS a delegated internal step and
24
+ * the operation DECLARES a scoped authority for it. The caller's own baseline for
25
+ * this internal resource is TYPICALLY a permission deny (the caller lacks the
26
+ * grant — that is expected and correct). The overlay RE-EVALUATES the step under
27
+ * the OPERATION's declared authority:
28
+ * 1. `authority = OperationAuthorityPort.resolveDelegatedAuthority(op, step)`.
29
+ * `undefined` ⇒ NOT delegated ⇒ pass-through (baseline stands). Fail-closed.
30
+ * 2. **Scope ceiling (§10.3, AC-15).** The step's `resource.typeKey` MUST be a
31
+ * member of the authority's declared `objectTypeKeys` AND the `action.key`
32
+ * MUST be a member of the declared `allowedActions` — STRICT `=== true`
33
+ * membership, never a wildcard. Out of EITHER ⇒ the operation is trying to
34
+ * act beyond what it was delegated ⇒ `deny(missing_object_type_grant)`. This
35
+ * is AC-15 "the same operation cannot write to an object it was not
36
+ * delegated authority for".
37
+ * 3. **Tenant still applies (§10.4).** Delegation crosses PERMISSION, never
38
+ * TENANT. A `tenant_mismatch` baseline is NEVER overridden to allow — a
39
+ * delegated step may not open a tenant boundary a §10bis grant has not
40
+ * ALREADY opened for the request. The overlay only ever overrides a
41
+ * *permission* deny; a tenant deny is preserved verbatim.
42
+ * 4. In-scope + tenant OK ⇒ `allow()` (the step runs under the operation's own
43
+ * authority; the "on behalf of" audit trail is the adapter's concern — §10.5,
44
+ * not this pure gate's).
45
+ *
46
+ * ── SCOPE, NEVER SUPERUSER. A delegated step gets EXACTLY the operation's declared
47
+ * object-type(s) + action(s) — never more, never the caller's grants, never a
48
+ * wildcard. Every ambiguity fails CLOSED (out-of-scope ⇒ deny; a malformed
49
+ * authority ⇒ deny). This is the #1 over-grant risk in the whole engine, so the
50
+ * membership checks route through the load-bearing `strictTrue` guard.
51
+ *
52
+ * ── TRANSIENT-vs-DENY (ADR-0016). This overlay NEVER catches. `resolveDelegatedAuthority`
53
+ * is a pure declared-metadata lookup, but if a concrete adapter must reach a store
54
+ * and throws {@link AuthorizationUnavailableError} (or any other error), it
55
+ * PROPAGATES unchanged so `decide()` can re-throw it (503-retryable). We never
56
+ * swallow a throw into a pass-through/allow — that would fail OPEN.
57
+ *
58
+ * ── PURE + zero-dep (ADR-0003). No framework / HTTP / DB / node imports; the port +
59
+ * context are injected via the pipeline's `GateContext`. Deterministic; no leak.
60
+ */
61
+ Object.defineProperty(exports, "__esModule", { value: true });
62
+ exports.DELEGATION_MARKER_ATTRIBUTE = void 0;
63
+ exports.readDelegationMarker = readDelegationMarker;
64
+ exports.isTypeInScope = isTypeInScope;
65
+ exports.isActionInScope = isActionInScope;
66
+ exports.createDelegationOverlay = createDelegationOverlay;
67
+ const decision_authority_js_1 = require("../decision-authority.js");
68
+ const reason_codes_js_1 = require("../reason-codes.js");
69
+ /**
70
+ * The FROZEN `DecisionContext.attributes` bag key under which the enforcement
71
+ * adapter marks a decision as a DELEGATED internal step and names its operation +
72
+ * step. The prelude did NOT add a dedicated channel to `GateContext` (the frozen
73
+ * seam), so this overlay reads the marker from the open-ended `attributes` bag the
74
+ * seam already carries — no frozen type is changed.
75
+ *
76
+ * ⛔ ENFORCEMENT-ADAPTER CONTRACT (`@astram/guard`): to run an internal step under
77
+ * an operation's delegated authority, populate
78
+ * `context.attributes['shield.delegation'] = { operationKey, stepKey }` on the
79
+ * per-step decision. Absent (or malformed) ⇒ the request is treated as a NORMAL,
80
+ * non-delegated decision (pass-through) — evaluated entirely under the caller.
81
+ */
82
+ exports.DELEGATION_MARKER_ATTRIBUTE = 'shield.delegation';
83
+ /**
84
+ * Read + VALIDATE the delegation marker off the frozen `DecisionContext.attributes`
85
+ * bag. Returns the marker ONLY when the attribute is a well-formed object carrying
86
+ * BOTH a non-empty `operationKey` and a non-empty `stepKey` (both strings); anything
87
+ * else — absent, wrong type, empty strings, a hostile shape — yields `undefined`
88
+ * (treated as "not a delegated step", i.e. pass-through). Fail-closed: a garbage
89
+ * marker never manufactures a delegation.
90
+ */
91
+ function readDelegationMarker(ctx) {
92
+ const raw = ctx.context.attributes?.[exports.DELEGATION_MARKER_ATTRIBUTE];
93
+ if (typeof raw !== 'object' || raw === null) {
94
+ return undefined;
95
+ }
96
+ const { operationKey, stepKey } = raw;
97
+ if (typeof operationKey !== 'string' ||
98
+ operationKey.length === 0 ||
99
+ typeof stepKey !== 'string' ||
100
+ stepKey.length === 0) {
101
+ return undefined;
102
+ }
103
+ return { operationKey, stepKey };
104
+ }
105
+ /**
106
+ * §10.3 SCOPE CEILING — is the step's object type a member of the authority's
107
+ * DECLARED `objectTypeKeys`? STRICT membership (exact string equality; no wildcard,
108
+ * no prefix). A malformed `objectTypeKeys` (non-array / non-string members) is
109
+ * treated as covering NOTHING (fail-closed) — an operation with a garbage scope
110
+ * delegates over no object type.
111
+ */
112
+ function isTypeInScope(authority, typeKey) {
113
+ const declared = authority.objectTypeKeys;
114
+ if (!Array.isArray(declared)) {
115
+ return false;
116
+ }
117
+ return (0, reason_codes_js_1.strictTrue)(declared.some((t) => t === typeKey));
118
+ }
119
+ /**
120
+ * §10.3 ACTION CEILING — is the attempted action a member of the authority's
121
+ * DECLARED `allowedActions`? STRICT membership (exact string equality; no wildcard).
122
+ * A malformed `allowedActions` covers NO action (fail-closed) — a delegated step may
123
+ * perform ONLY the exact actions the operation named.
124
+ */
125
+ function isActionInScope(authority, actionKey) {
126
+ const declared = authority.allowedActions;
127
+ if (!Array.isArray(declared)) {
128
+ return false;
129
+ }
130
+ return (0, reason_codes_js_1.strictTrue)(declared.some((a) => a === actionKey));
131
+ }
132
+ /**
133
+ * A baseline deny that the delegation overlay is allowed to OVERRIDE is a
134
+ * *permission* deny only. §10.4: delegation crosses PERMISSION, never TENANT — so a
135
+ * `tenant_mismatch` baseline is NEVER overridable. `resource_not_registered` /
136
+ * `not_authenticated` are pre-gate-3 outcomes that never reach gate 7 in the real
137
+ * pipeline, but we guard them too (defense-in-depth): only a permission-tier deny
138
+ * (`missing_object_type_grant` / `no_record_permit` / `explicit_deny_policy` /
139
+ * `deny_by_default`) may be re-decided under the operation's authority.
140
+ *
141
+ * Note: `explicit_deny_policy` (a deny-wins record-rule deny) IS a permission-tier
142
+ * deny and MAY be overridden by a valid in-scope delegated authority — the operation
143
+ * acts under its OWN identity, for which the caller-scoped rule deny is irrelevant.
144
+ */
145
+ function isOverridablePermissionDeny(baseline) {
146
+ if (baseline.effect !== 'deny') {
147
+ return false;
148
+ }
149
+ switch (baseline.reason) {
150
+ case 'tenant_mismatch':
151
+ case 'resource_not_registered':
152
+ case 'not_authenticated':
153
+ // Never overridable by delegation (tenant boundary + pre-authz gates).
154
+ return false;
155
+ case 'missing_object_type_grant':
156
+ case 'no_record_permit':
157
+ case 'explicit_deny_policy':
158
+ case 'deny_by_default':
159
+ return true;
160
+ default:
161
+ // Unknown/hostile reason ⇒ fail-closed (do NOT override).
162
+ return false;
163
+ }
164
+ }
165
+ /**
166
+ * Build the gate-7 {@link DelegationOverlayFn} the pipeline injects. PURE — reaches
167
+ * the {@link OperationAuthorityPort} through `ctx.deps.operationAuthority`; holds no
168
+ * state.
169
+ *
170
+ * Contract (see the module doc for the full rationale):
171
+ * - No delegation marker OR `resolveDelegatedAuthority → undefined` ⇒
172
+ * `gateContinue()` (pass-through; the gates-0–6 baseline stands).
173
+ * - A delegated step whose declared authority covers the step's object type AND
174
+ * action, AND whose baseline deny is a PERMISSION deny (never `tenant_mismatch`)
175
+ * ⇒ `gateAllow()` (re-evaluated under the operation's own authority).
176
+ * - A delegated step OUT of the declared object-type or action scope ⇒
177
+ * `gateDeny(missing_object_type_grant)` (AC-15 over-grant refusal).
178
+ * - A delegated step whose baseline is a tenant (or pre-authz) deny ⇒
179
+ * `gateContinue()` — the overlay refuses to override it (§10.4 preserved).
180
+ * - Any throw from the port PROPAGATES unchanged (ADR-0016; never swallowed).
181
+ */
182
+ function createDelegationOverlay(_options = {}) {
183
+ return async function delegationOverlay(ctx, baseline) {
184
+ // (1) Is THIS request a delegated internal step? Absent/garbage marker ⇒ the
185
+ // request is a normal, caller-scoped decision — the baseline stands verbatim.
186
+ const marker = readDelegationMarker(ctx);
187
+ if (marker === undefined) {
188
+ return (0, decision_authority_js_1.gateContinue)();
189
+ }
190
+ // (2) Does the OPERATION declare a scoped authority for this step? A throw here
191
+ // (transient-unavailable adapter) PROPAGATES so `decide()` re-throws it — we do
192
+ // NOT catch. `undefined` ⇒ no declared authority ⇒ NOT delegated ⇒ pass-through
193
+ // (fail-closed to the caller's baseline, never to an allow).
194
+ const authority = ctx.deps.operationAuthority.resolveDelegatedAuthority(marker.operationKey, marker.stepKey);
195
+ if (authority === undefined) {
196
+ return (0, decision_authority_js_1.gateContinue)();
197
+ }
198
+ // (3) §10.4 TENANT PRESERVATION (before any override). Delegation crosses
199
+ // PERMISSION, never TENANT. If the baseline denied for the tenant boundary (or a
200
+ // pre-authz gate), the overlay MUST NOT override it — the delegated authority
201
+ // cannot open a tenant boundary a §10bis grant has not already opened. Preserve
202
+ // the baseline exactly.
203
+ if (baseline.effect === 'deny' && !isOverridablePermissionDeny(baseline)) {
204
+ return (0, decision_authority_js_1.gateContinue)();
205
+ }
206
+ // (4) §10.3 / AC-15 SCOPE CEILING. The step may act ONLY on the DECLARED object
207
+ // type(s) + action(s) — never wider, never a wildcard, never the caller's grants.
208
+ // Out of EITHER ⇒ the operation is attempting to write beyond its delegated
209
+ // authority ⇒ DENY (the AC-15 "cannot write to an object it was not delegated
210
+ // authority for" bound). `missing_object_type_grant` is the truest reason: the
211
+ // operation identity lacks a grant covering this step's object type/action.
212
+ if (!isTypeInScope(authority, ctx.resource.typeKey) ||
213
+ !isActionInScope(authority, ctx.action.key)) {
214
+ return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyMissingObjectTypeGrant)());
215
+ }
216
+ // (5) In-scope AND tenant OK. The step runs under the OPERATION's own declared,
217
+ // scoped, least-privilege authority — overriding the caller's permission-deny
218
+ // baseline. (The "on behalf of" audit — §10.5 — is the enforcement adapter's job,
219
+ // not this pure decision gate's.)
220
+ //
221
+ // Note: when the baseline was already an ALLOW (a pass-through step the operation
222
+ // ALSO declared authority for, and the caller happened to be authorized), an
223
+ // in-scope authority likewise yields allow — same terminal outcome, no widening.
224
+ return (0, decision_authority_js_1.gateAllow)();
225
+ };
226
+ }
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ /**
3
+ * Authorization engine ERRORS — the typed transient signal that resolves the
4
+ * ADR-0016 "transient-vs-deny" seam gap WITHOUT touching the frozen
5
+ * {@link DecisionReasonCode} enum (KICKOFF §"BINDING ARCHITECT DECISION").
6
+ *
7
+ * The frozen enum (8 members) has NO `authorization_unavailable` member, and per
8
+ * ADR-0016 the transient distinction lives in the ENFORCEMENT ADAPTER, not inside
9
+ * the pure `decide()` seam. So `decide()` never fabricates an out-of-enum reason:
10
+ *
11
+ * - it can RENDER a decision → returns a {@link Decision} (`allow`/`deny`);
12
+ * - a port is genuinely UNAVAILABLE (transient) → it THROWS this typed error;
13
+ * - any OTHER unexpected exception → fail-closed `deny` (`deny_by_default`).
14
+ *
15
+ * The enforcement adapter (`@astram/guard`) maps a thrown
16
+ * {@link AuthorizationUnavailableError} → **503 retryable**, while a returned
17
+ * `Decision{effect:'deny'}` → **403 terminal**. BOTH keep the request unserved
18
+ * (fail-closed); only the *signal* differs, exactly where the ADR places it.
19
+ *
20
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.AuthorizationUnavailableError = exports.AUTHORIZATION_UNAVAILABLE_BRAND = void 0;
24
+ exports.isAuthorizationUnavailable = isAuthorizationUnavailable;
25
+ /**
26
+ * ⛔ CROSS-BUILD BRAND (ADR-0016 hardening). `@astram/core` is DUAL-BUILT (ESM `dist/` +
27
+ * CJS `dist-cjs/`). A guard adapter compiled against one build can throw an
28
+ * `AuthorizationUnavailableError` whose class is a DIFFERENT realized constructor from the
29
+ * one the wiring loaded in the other build — so a bare `err instanceof
30
+ * AuthorizationUnavailableError` returns FALSE across the build boundary, and a genuine
31
+ * store OUTAGE would be mis-classified as `deny_by_default` (403 terminal) instead of the
32
+ * retryable 503 the ADR mandates.
33
+ *
34
+ * `Symbol.for(...)` is keyed on the GLOBAL symbol registry, shared across every module
35
+ * realm/build in the process — so a value carrying this brand is recognizable regardless of
36
+ * WHICH core build minted it. It is the robust, cross-realm transient signal;
37
+ * {@link isAuthorizationUnavailable} tests `instanceof` FIRST (fast, primary) then this
38
+ * brand (the dual-build fallback). A coincidental `name` alone is deliberately NOT trusted
39
+ * as the sole signal (see the guard).
40
+ */
41
+ exports.AUTHORIZATION_UNAVAILABLE_BRAND = Symbol.for('astram.core.AuthorizationUnavailable');
42
+ /**
43
+ * A TYPED, transient-unavailable signal thrown by `decide()` ONLY when an injected
44
+ * port genuinely CANNOT answer (ADR-0016) — e.g. the hot-facts read yields
45
+ * `unavailable`, or a rule/share/grant port throws a transient/outage error.
46
+ *
47
+ * ⛔ This is NOT a normal Deny. A port returning "no rule / no share / no grant /
48
+ * facts-absent-but-store-up" is a normal **data-absence** → it contributes to a
49
+ * returned `deny` Decision (`no_record_permit` / `deny_by_default`), NEVER this
50
+ * error. Only a genuine `unavailable`/transient-throw becomes this signal — the
51
+ * same `found|absent|unavailable` discipline Session uses.
52
+ *
53
+ * Fail-closed either way: a thrown `AuthorizationUnavailableError` leaves the
54
+ * request UNSERVED (the adapter maps it to 503-retryable); it must never be
55
+ * silently converted into an Allow, nor swallowed into a `deny_by_default` (that
56
+ * would erase the retryable signal the ADR mandates). The `decide()` pipeline
57
+ * therefore RE-THROWS this type unchanged and only converts OTHER exceptions to a
58
+ * fail-closed deny.
59
+ */
60
+ class AuthorizationUnavailableError extends Error {
61
+ /**
62
+ * The underlying transient cause (a port outage error, an `unavailable` marker,
63
+ * etc.), retained for admin troubleshooting/logging by the adapter. NEVER
64
+ * surfaced to end users and NEVER used to leak resource existence (§7.5).
65
+ */
66
+ cause;
67
+ /**
68
+ * Optional non-leaking admin-only detail (e.g. which port was unavailable).
69
+ * Same §7.5 discipline as {@link Decision.detail}: admin troubleshooting only,
70
+ * never returned to the caller, never reveals whether a resource exists.
71
+ */
72
+ detail;
73
+ /**
74
+ * The global-registry brand (see {@link AUTHORIZATION_UNAVAILABLE_BRAND}). Stamped `true`
75
+ * on every instance so {@link isAuthorizationUnavailable} recognizes the error across the
76
+ * ESM/CJS dual-build boundary, where `instanceof` alone can be false.
77
+ */
78
+ [exports.AUTHORIZATION_UNAVAILABLE_BRAND] = true;
79
+ constructor(detail, cause) {
80
+ super(detail ?? 'authorization_unavailable');
81
+ this.name = 'AuthorizationUnavailableError';
82
+ if (detail !== undefined)
83
+ this.detail = detail;
84
+ if (cause !== undefined)
85
+ this.cause = cause;
86
+ // Preserve the prototype chain when compiled down-level so `instanceof` works.
87
+ Object.setPrototypeOf(this, AuthorizationUnavailableError.prototype);
88
+ }
89
+ }
90
+ exports.AuthorizationUnavailableError = AuthorizationUnavailableError;
91
+ /**
92
+ * The robust, dual-build-safe transient test: is `err` an {@link AuthorizationUnavailableError}
93
+ * (ADR-0016 transient signal) regardless of WHICH core build (ESM `dist/` vs CJS `dist-cjs/`)
94
+ * minted it?
95
+ *
96
+ * Checks `instanceof` FIRST (primary, fast, exact within one build), then falls back to the
97
+ * GLOBAL-registry {@link AUTHORIZATION_UNAVAILABLE_BRAND} (cross-build/cross-realm safe). The
98
+ * brand is a `Symbol.for(...)` on the process-shared registry, so a differently-realized
99
+ * constructor still carries the SAME brand symbol — impossible to spoof by a coincidental
100
+ * `name` (we do NOT trust `name` as the sole signal; only the brand or a true `instanceof`).
101
+ * An ordinary `Error` has neither → returns false → the caller fail-closes it to
102
+ * `deny_by_default` (the ordinary-error path is unchanged).
103
+ */
104
+ function isAuthorizationUnavailable(err) {
105
+ if (err instanceof AuthorizationUnavailableError)
106
+ return true;
107
+ return (typeof err === 'object' &&
108
+ err !== null &&
109
+ err[exports.AUTHORIZATION_UNAVAILABLE_BRAND] === true);
110
+ }
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ /**
3
+ * Gate 5 — the **FEATURE / OBJECT-TYPE permission gate** (TEAM A, Hard Gates) —
4
+ * §7.3.3 / ADR-0011.
5
+ *
6
+ * Runs ONLY for GATED resources (public + authenticated_global already
7
+ * short-circuited to Allow upstream; unauthenticated + cross-tenant-without-grant
8
+ * already denied). It answers the coarse question: *does this principal hold a
9
+ * feature/object-type grant for the action's stable permission key?* — the
10
+ * ADR-0011 hot path.
11
+ *
12
+ * ── Permission identity: the required grant key is the action's STABLE
13
+ * permission key (ADR-0010) — `moduleKey:typeKey:actionKey`. The pipeline
14
+ * resolved the {@link RegisteredAction} at gate 1 but does NOT stash it on the
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
18
+ * for this type has no derivable grant → `deny(missing_object_type_grant)`.
19
+ *
20
+ * ── Coarse-grants source (ADR-0011, hot path, in order):
21
+ * 1. Read THIS request's session facts (`deps.sessionFacts`): compare the cached
22
+ * `permissionsVersion` against {@link PermissionFactsPort.currentPermissionsVersion}.
23
+ * - versions MATCH and `cachedFacts` present ⇒ use `cachedFacts` (NO reload) —
24
+ * a revoke takes effect within the version bound.
25
+ * - versions DIFFER (stale) OR `cachedFacts` null/unusable ⇒ RELOAD via
26
+ * {@link PermissionFactsPort.loadCoarseGrants}.
27
+ * 2. `cachedFacts` is the opaque ADR-0011 slot; this gate interprets it as
28
+ * {@link CoarseGrants} (`{ permissionsVersion, grantedPermissionKeys }`) — the
29
+ * exact shape `ports.ts` defines. (Assumption documented in DONE.md: the
30
+ * prelude left the slot typed `unknown`; we read it through a minimal typed
31
+ * view here and never mutate the frozen slot.)
32
+ *
33
+ * ── Cross-tenant case (§7.3.3): when the tenant DIFFERS (and the principal is not
34
+ * the root), gate 3 only let evaluation proceed BECAUSE a
35
+ * cross-tenant grant covers it — and that grant's scope + action-ceiling SERVES
36
+ * AS the object-type grant. Coarse facts are the WRONG-tenant facts, so this
37
+ * gate does NOT consult them; it RE-RESOLVES the grant via
38
+ * {@link CrossTenantGrantPort} (gate 3 is pure and stashed nothing) and, if the
39
+ * action is in-ceiling, `continue`s (record level → gate 6 runs) or `allow`s
40
+ * (feature/object-type level → terminates). A root crossing tenants is NOT
41
+ * grant-backed; it takes the normal coarse-grants path below.
42
+ *
43
+ * ── Decision:
44
+ * - grant held for this action (STRICT membership) →
45
+ * `record` level ⇒ `continue` (gate 6 record-permit runs next);
46
+ * feature/object_type level ⇒ `allow` (terminates here).
47
+ * - no applicable grant ⇒ `deny(missing_object_type_grant)`.
48
+ * - {@link PermissionFactsPort} / {@link CrossTenantGrantPort} throws
49
+ * {@link AuthorizationUnavailableError} (transient) ⇒ PROPAGATES (pipeline
50
+ * re-throws → 503). Any OTHER throw also propagates (pipeline fail-closes to
51
+ * `deny_by_default`). This gate NEVER swallows a throw into a `deny`.
52
+ *
53
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
54
+ */
55
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.createObjectTypeGate = createObjectTypeGate;
57
+ const decision_authority_js_1 = require("../decision-authority.js");
58
+ const reason_codes_js_1 = require("../reason-codes.js");
59
+ const grant_evaluator_js_1 = require("../cross-tenant/grant-evaluator.js");
60
+ const index_js_1 = require("../../metadata/index.js");
61
+ /**
62
+ * A minimal, defensive typed VIEW of the opaque `cachedFacts` slot (ADR-0011). We
63
+ * do NOT trust the slot to already be a well-formed {@link CoarseGrants}; we probe
64
+ * it structurally so a `null`/junk cache falls back to a reload rather than
65
+ * failing open. Returns the parsed facts, or `null` when the slot is unusable.
66
+ */
67
+ function asCoarseGrants(slot) {
68
+ if (slot === null || typeof slot !== 'object') {
69
+ return null;
70
+ }
71
+ const candidate = slot;
72
+ if (typeof candidate.permissionsVersion !== 'number') {
73
+ return null;
74
+ }
75
+ if (!Array.isArray(candidate.grantedPermissionKeys)) {
76
+ return null;
77
+ }
78
+ // Every entry must be a genuine string — a hostile non-string must not sneak in.
79
+ for (const key of candidate.grantedPermissionKeys) {
80
+ if (typeof key !== 'string') {
81
+ return null;
82
+ }
83
+ }
84
+ return {
85
+ permissionsVersion: candidate.permissionsVersion,
86
+ grantedPermissionKeys: candidate.grantedPermissionKeys,
87
+ };
88
+ }
89
+ /**
90
+ * STRICT membership: whether `grantedPermissionKeys` contains the required key.
91
+ * Routed through {@link strictTrue} so a truthy-non-boolean from `.includes` (there
92
+ * shouldn't be one, but defence-in-depth) is NOT a pass.
93
+ */
94
+ function grantsHoldKey(grants, permissionKey) {
95
+ return (0, reason_codes_js_1.strictTrue)(grants.grantedPermissionKeys.includes(permissionKey));
96
+ }
97
+ /**
98
+ * Build the feature/object-type gate (gate 5). No injected deps of its own — it
99
+ * reaches the registry, session facts, {@link PermissionFactsPort}, and
100
+ * {@link CrossTenantGrantPort} through {@link GateContext.deps}. Returns an
101
+ * {@link ObjectTypeGateFn} the integration owner injects as
102
+ * `DecisionAuthorityDeps.gates.objectTypeGate`.
103
+ */
104
+ function createObjectTypeGate() {
105
+ return async function objectTypeGate(ctx) {
106
+ const { principal, action, resource, deps } = ctx;
107
+ const isRecordLevel = resource.level === 'record';
108
+ // ── Cross-tenant grant path (§7.3.3): a non-root reaching a foreign
109
+ // tenant proceeded past gate 3 ONLY via a cross-tenant grant, whose scope +
110
+ // ceiling SERVES AS the object-type grant. Re-resolve it here (gate 3 is
111
+ // pure), NOT the wrong-tenant coarse facts. Root is not grant-backed;
112
+ // it falls through to the coarse-grants path.
113
+ const crossesTenant = resource.tenantId !== undefined &&
114
+ principal.tenantId !== resource.tenantId &&
115
+ !(0, reason_codes_js_1.strictTrue)(principal.isRoot);
116
+ if (crossesTenant) {
117
+ // Re-resolve the grant through the SINGLE-SOURCE cross-tenant helper (TEAM C)
118
+ // so gates 3/5/6 share ONE ceiling+scope+expiry implementation (RULING 1 /
119
+ // AC-13 defense-in-depth). The grant SERVES AS the object-type grant ONLY when
120
+ // its action ceiling INCLUDES this action AND its scope COVERS this resource
121
+ // AND it is UNEXPIRED — an expired or record-scope-mismatched grant is REJECTED
122
+ // here, not honored. A transient/any throw PROPAGATES (the helper never catches).
123
+ const { applicable } = await (0, grant_evaluator_js_1.isCrossTenantGrantApplicable)(deps.crossTenantGrant, {
124
+ principal,
125
+ action,
126
+ resource,
127
+ });
128
+ if (applicable) {
129
+ // In-scope cross-tenant grant: record level ⇒ record-permit still runs;
130
+ // feature/object-type level ⇒ the grant IS the object-type grant → allow.
131
+ return isRecordLevel ? (0, decision_authority_js_1.gateContinue)() : (0, decision_authority_js_1.gateAllow)();
132
+ }
133
+ // No covering grant on the foreign tenant ⇒ no object-type grant applies.
134
+ return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyMissingObjectTypeGrant)());
135
+ }
136
+ // ── Same-tenant (or root) path — coarse feature/object-type grants
137
+ // (ADR-0011). Derive the required stable permission key by re-resolving the
138
+ // registered action over the frozen registry surface.
139
+ const registered = deps.registry
140
+ .listActions()
141
+ .find((a) => a.action.typeKey === resource.typeKey && a.action.actionKey === action.key);
142
+ if (registered === undefined) {
143
+ // Unregistered action for this type ⇒ no permission key to grant against.
144
+ return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyMissingObjectTypeGrant)());
145
+ }
146
+ const requiredKey = registered.permissionKey;
147
+ // ── ROOT CAP (§0/§2, ISO A.8.2 / A.5.3): a root is
148
+ // control-plane ONLY. Deny every data-plane capability BY CONSTRUCTION —
149
+ // grant-independent (even a fully-granted root is denied). Control-plane
150
+ // capabilities are allowed WITHOUT a grant (root's authority is the flag +
151
+ // plane classification, not RBAC grants). Default plane is `data` → a
152
+ // forgotten classification denies root (fail-safe).
153
+ if ((0, reason_codes_js_1.strictTrue)(principal.isRoot)) {
154
+ if ((0, index_js_1.resolvePlane)(registered.action) === 'data') {
155
+ return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyRootDataPlane)());
156
+ }
157
+ return isRecordLevel ? (0, decision_authority_js_1.gateContinue)() : (0, decision_authority_js_1.gateAllow)();
158
+ }
159
+ // Hot path: prefer the request's cached facts when they are FRESH; reload on a
160
+ // stale version or an unusable cache.
161
+ const grants = await resolveCoarseGrants(ctx, requiredKey);
162
+ if (!grantsHoldKey(grants, requiredKey)) {
163
+ return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyMissingObjectTypeGrant)());
164
+ }
165
+ // Grant held: a record-level resource proceeds to the record permit tier;
166
+ // a feature/object-type-level resource terminates here as Allow.
167
+ return isRecordLevel ? (0, decision_authority_js_1.gateContinue)() : (0, decision_authority_js_1.gateAllow)();
168
+ };
169
+ }
170
+ /**
171
+ * Resolve the coarse grants to decide on (ADR-0011 version-freshness rule). Uses
172
+ * the request's `cachedFacts` when its version MATCHES the authority's current
173
+ * version; otherwise reloads via {@link PermissionFactsPort.loadCoarseGrants}. A
174
+ * transient throw from either port propagates (never swallowed).
175
+ *
176
+ * `_requiredKey` is unused in resolution (the freshness decision is version-based,
177
+ * not key-based) but kept in the signature for clarity of intent at the call site.
178
+ */
179
+ async function resolveCoarseGrants(ctx, _requiredKey) {
180
+ const { principal, deps } = ctx;
181
+ const cached = asCoarseGrants(deps.sessionFacts.cachedFacts);
182
+ if (cached !== null) {
183
+ const currentVersion = await deps.permissionFacts.currentPermissionsVersion(principal.id, principal.tenantId);
184
+ // Fresh iff the cached facts were projected at (or after) the current version.
185
+ // A LOWER cached version ⇒ STALE ⇒ reload (so a revoke lands within the bound).
186
+ if (cached.permissionsVersion >= currentVersion) {
187
+ return cached;
188
+ }
189
+ }
190
+ // Cache miss / unusable / stale ⇒ reload the authoritative grants.
191
+ return deps.permissionFacts.loadCoarseGrants(principal.id, principal.tenantId);
192
+ }
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ /**
3
+ * Gate 3 — the **TENANT gate** (TEAM A, Hard Gates) — §7.3.2 / ADR-0009.
4
+ *
5
+ * The tenant boundary is the platform's DEFAULT authorization boundary (§7.3): a
6
+ * principal may only reach a resource its own tenant owns, UNLESS it is the
7
+ * root (break-glass) or an active, consented cross-tenant grant
8
+ * (ADR-0009) lets evaluation PROCEED. This gate can ONLY block (`deny`) or let
9
+ * evaluation continue (`continue`) — it NEVER returns `allow`. An `allow` from
10
+ * the tenant gate would be a fail-open (the pipeline treats an unexpected `allow`
11
+ * here as fail-closed `deny_by_default`), so this gate never produces one; a
12
+ * cross-tenant grant is a hard action-CEILING that only permits proceeding, and
13
+ * the object-type/record gates downstream still run.
14
+ *
15
+ * ── The order (deny wins; every ambiguity resolves to the deny/continue path,
16
+ * never to a bypass):
17
+ *
18
+ * 1. SAME TENANT (`principal.tenantId === resource.tenantId`, OR the resource
19
+ * carries no instance tenant) ⇒ `continue`. A feature/object-type-level
20
+ * resource with no `tenantId` is same-tenant BY CONSTRUCTION — there is no
21
+ * foreign instance to cross into, so it is the principal's own tenant.
22
+ * 2. MISMATCH + root (STRICT `=== true`) ⇒ `continue` (break-glass,
23
+ * audited by a later layer — not this gate's concern).
24
+ * 3. MISMATCH + not root ⇒ consult {@link CrossTenantGrantPort}:
25
+ * - an ACTIVE grant whose action-ceiling INCLUDES this action (STRICT
26
+ * membership) ⇒ `continue` (proceed only; it confers no object-type/record
27
+ * permission — those gates still run);
28
+ * - `null` (a normal data-absence: no consent) ⇒ `deny(tenant_mismatch)`;
29
+ * - the port THROWS {@link AuthorizationUnavailableError} (transient) ⇒ it
30
+ * PROPAGATES (the pipeline re-throws → 503-retryable). ANY OTHER throw
31
+ * also propagates (the pipeline's top-level catch fail-closes it to
32
+ * `deny_by_default`). This gate NEVER swallows a throw into a `deny`.
33
+ *
34
+ * ── Cross-tenant re-resolution note (for gates 5/6): this gate is PURE over the
35
+ * ports and cannot mutate the shared read-only {@link GateContext}. It therefore
36
+ * does NOT stash "we proceeded under a grant" anywhere. When the tenant differs,
37
+ * gate 5 (and gate 6) MUST independently RE-RESOLVE the grant via the same
38
+ * {@link CrossTenantGrantPort} to learn the grant's scope/ceiling. This keeps
39
+ * every gate stateless and avoids a shared-mutable-state channel.
40
+ *
41
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
42
+ */
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.createTenantGate = createTenantGate;
45
+ const decision_authority_js_1 = require("../decision-authority.js");
46
+ const reason_codes_js_1 = require("../reason-codes.js");
47
+ const grant_evaluator_js_1 = require("../cross-tenant/grant-evaluator.js");
48
+ /**
49
+ * Build the tenant gate (gate 3). No injected deps of its own — it reaches the
50
+ * {@link CrossTenantGrantPort} through {@link GateContext.deps.crossTenantGrant}
51
+ * (the pipeline owns the wiring). Returns a {@link TenantGateFn} the integration
52
+ * owner injects as `DecisionAuthorityDeps.gates.tenantGate`.
53
+ */
54
+ function createTenantGate() {
55
+ return async function tenantGate(ctx) {
56
+ const { principal, action, resource, deps } = ctx;
57
+ // 1. Same tenant — including a feature/object-type resource with no instance
58
+ // tenant (same-tenant by construction: no foreign instance to cross into).
59
+ if (resource.tenantId === undefined || principal.tenantId === resource.tenantId) {
60
+ return (0, decision_authority_js_1.gateContinue)();
61
+ }
62
+ // 2. Mismatch + root (break-glass). STRICT === true — a truthy
63
+ // non-boolean root flag must NOT bypass the tenant boundary.
64
+ if ((0, reason_codes_js_1.strictTrue)(principal.isRoot)) {
65
+ return (0, decision_authority_js_1.gateContinue)();
66
+ }
67
+ // 3. Mismatch + not root — the ONLY sanctioned crossing is an active,
68
+ // consented cross-tenant grant (ADR-0009). Resolve applicability through the
69
+ // SINGLE-SOURCE cross-tenant helper (TEAM C) so gates 3/5/6 share ONE
70
+ // ceiling+scope+expiry implementation (RULING 1 / AC-13 defense-in-depth): a
71
+ // grant proceeds ONLY when its action ceiling INCLUDES this action AND its
72
+ // scope COVERS this resource AND it is UNEXPIRED. A racy/misbehaving adapter
73
+ // returning an expired or record-scope-mismatched grant is REJECTED here, not
74
+ // honored. Let a transient/any throw PROPAGATE (the helper never catches).
75
+ const { applicable } = await (0, grant_evaluator_js_1.isCrossTenantGrantApplicable)(deps.crossTenantGrant, {
76
+ principal,
77
+ action,
78
+ resource,
79
+ });
80
+ if (applicable) {
81
+ // The grant lets evaluation PROCEED — it is a hard action-ceiling, not an
82
+ // allow. Object-type/record gates still run (they re-resolve this grant).
83
+ return (0, decision_authority_js_1.gateContinue)();
84
+ }
85
+ // `null` (no consent) OR a grant that fails the ceiling / scope / expiry checks
86
+ // ⇒ the tenant boundary holds. FINAL — never relaxed downstream.
87
+ return (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyTenantMismatch)());
88
+ };
89
+ }