@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,155 @@
1
+ "use strict";
2
+ /**
3
+ * The **factor-verifier CONTRACT** + a **reference TOTP verifier** (RFC 6238).
4
+ *
5
+ * `FactorVerifier` is the extension seam for second factors: one verifier per
6
+ * `AuthFactor`, registered in a `FactorVerifierRegistry`, driven by the
7
+ * Authentication engine when a `RequiredFactor` is outstanding. This is
8
+ * deliberately MINIMAL (ADR-0023 §7 Rule of Three): the contract + ONE concrete
9
+ * verifier (TOTP) that exercises the `mfa_required` mechanism. The WebAuthn /
10
+ * recovery-code factors are named in `AuthFactor` but only their CONTRACT slot
11
+ * exists here — no ceremony this layer.
12
+ *
13
+ * ZERO-DEP + NODE-TYPE-FREE (ADR-0003): TOTP needs HMAC-SHA1, but `@astram/core`
14
+ * has neither a runtime dependency NOR `@types/node` (its tsconfig sets
15
+ * `types: []`). So HMAC is itself an INJECTED port (`HmacSha1`): the pure RFC-6238
16
+ * arithmetic (time-step counter, dynamic truncation, modulo) lives here; the one
17
+ * crypto primitive is supplied by the caller (a `node:crypto` one-liner in the
18
+ * app / tests). Core stays dependency-free and never imports a node builtin.
19
+ *
20
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.FactorVerifierRegistry = void 0;
24
+ exports.createTotpFactorVerifier = createTotpFactorVerifier;
25
+ /**
26
+ * A tiny registry of {@link FactorVerifier}s, keyed by `factor`. The engine
27
+ * resolves the verifier for each outstanding `RequiredFactor`; a MISS means no
28
+ * verifier is wired for a required factor → the engine fail-closes (that factor
29
+ * can never be satisfied, so the attempt cannot authenticate). Fail-closed on
30
+ * empty/duplicate registration, mirroring `IdentityClaimMapperRegistry`.
31
+ */
32
+ class FactorVerifierRegistry {
33
+ verifiers = new Map();
34
+ /** Register a verifier for its `factor`. Duplicate → throws LOUD. */
35
+ register(verifier) {
36
+ if (this.verifiers.has(verifier.factor)) {
37
+ throw new Error(`FactorVerifierRegistry.register: factor "${verifier.factor}" is already registered (duplicate verifier)`);
38
+ }
39
+ this.verifiers.set(verifier.factor, verifier);
40
+ }
41
+ /** Look up the verifier for a factor, or `undefined` if none is registered. */
42
+ resolve(factor) {
43
+ return this.verifiers.get(factor);
44
+ }
45
+ }
46
+ exports.FactorVerifierRegistry = FactorVerifierRegistry;
47
+ const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
48
+ /**
49
+ * Decode an RFC 4648 base32 string (the standard TOTP secret encoding) into
50
+ * bytes. Case-insensitive; ignores padding (`=`) and whitespace. Returns `null`
51
+ * for any non-alphabet character so the verifier fail-closes on a malformed
52
+ * secret rather than authenticating against garbage.
53
+ */
54
+ function base32Decode(input) {
55
+ const clean = input.replace(/=+$/u, '').replace(/\s+/gu, '').toUpperCase();
56
+ if (clean.length === 0)
57
+ return null;
58
+ let bits = 0;
59
+ let value = 0;
60
+ const out = [];
61
+ for (const ch of clean) {
62
+ const idx = BASE32_ALPHABET.indexOf(ch);
63
+ if (idx === -1)
64
+ return null;
65
+ value = (value << 5) | idx;
66
+ bits += 5;
67
+ if (bits >= 8) {
68
+ bits -= 8;
69
+ out.push((value >>> bits) & 0xff);
70
+ }
71
+ }
72
+ return Uint8Array.from(out);
73
+ }
74
+ /** Encode a 64-bit counter (big-endian) into an 8-byte buffer (RFC 4226). */
75
+ function counterToBytes(counter) {
76
+ const buf = new Uint8Array(8);
77
+ // JS bitwise is 32-bit; split into high/low 32-bit halves to fill all 8 bytes.
78
+ let high = Math.floor(counter / 0x1_0000_0000);
79
+ let low = counter >>> 0;
80
+ for (let i = 7; i >= 4; i--) {
81
+ buf[i] = low & 0xff;
82
+ low = Math.floor(low / 256);
83
+ }
84
+ for (let i = 3; i >= 0; i--) {
85
+ buf[i] = high & 0xff;
86
+ high = Math.floor(high / 256);
87
+ }
88
+ return buf;
89
+ }
90
+ /**
91
+ * Compute the RFC 6238 TOTP code for a given time-step counter. Pure arithmetic
92
+ * over the injected HMAC-SHA1: dynamic truncation (RFC 4226 §5.3) → modulo
93
+ * 10^digits, zero-padded.
94
+ */
95
+ function computeCode(hmacSha1, key, counter, digits) {
96
+ const digest = hmacSha1(key, counterToBytes(counter));
97
+ // Dynamic truncation: low 4 bits of the last byte select the offset.
98
+ const offset = (digest[digest.length - 1] ?? 0) & 0x0f;
99
+ const binary = (((digest[offset] ?? 0) & 0x7f) << 24) |
100
+ (((digest[offset + 1] ?? 0) & 0xff) << 16) |
101
+ (((digest[offset + 2] ?? 0) & 0xff) << 8) |
102
+ ((digest[offset + 3] ?? 0) & 0xff);
103
+ const code = binary % 10 ** digits;
104
+ return code.toString().padStart(digits, '0');
105
+ }
106
+ /**
107
+ * Constant-time string comparison (both operands are short numeric codes). Avoids
108
+ * an early-return timing signal on the presented code. Not a substitute for the
109
+ * password's algorithmic constant-time verify, but keeps the factor tidy.
110
+ */
111
+ function timingSafeEqual(a, b) {
112
+ if (a.length !== b.length)
113
+ return false;
114
+ let diff = 0;
115
+ for (let i = 0; i < a.length; i++) {
116
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
117
+ }
118
+ return diff === 0;
119
+ }
120
+ /**
121
+ * Build the reference **TOTP** {@link FactorVerifier} (RFC 6238). The presented
122
+ * `credential.payload.code` (a string of digits) is checked against codes derived
123
+ * from the base32 `secret` across the accepted skew window. PURE apart from the
124
+ * injected HMAC + clock. Fail-closed: a malformed secret or a non-string /
125
+ * wrong-length code → `satisfied: false` (never throws, never logs the code).
126
+ */
127
+ function createTotpFactorVerifier(options) {
128
+ const { hmacSha1 } = options;
129
+ const digits = options.digits ?? 6;
130
+ const stepSeconds = options.stepSeconds ?? 30;
131
+ const window = Math.max(0, options.window ?? 1);
132
+ const now = options.now ?? Date.now;
133
+ return {
134
+ factor: 'totp',
135
+ verify(credential, secret) {
136
+ const presented = credential.payload?.code;
137
+ if (typeof presented !== 'string' || presented.length === 0) {
138
+ return Promise.resolve({ satisfied: false, reason: 'factor_rejected' });
139
+ }
140
+ const key = base32Decode(secret);
141
+ if (key === null || key.length === 0) {
142
+ // Malformed server-side secret — fail-closed, never authenticate.
143
+ return Promise.resolve({ satisfied: false, reason: 'factor_rejected' });
144
+ }
145
+ const counter = Math.floor(now() / 1000 / stepSeconds);
146
+ for (let offset = -window; offset <= window; offset++) {
147
+ const candidate = computeCode(hmacSha1, key, counter + offset, digits);
148
+ if (timingSafeEqual(candidate, presented)) {
149
+ return Promise.resolve({ satisfied: true });
150
+ }
151
+ }
152
+ return Promise.resolve({ satisfied: false, reason: 'factor_rejected' });
153
+ },
154
+ };
155
+ }
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * Cross-tenant consented GRANT evaluator (ADR-0009 / §10bis) — the single, reusable
4
+ * "does an active cross-tenant grant permit THIS action on THIS resource?" helper
5
+ * consulted by gate 3 (tenant, TEAM A), gate 5 (object-type, TEAM A), AND gate 6's
6
+ * share-half (per-record permit, TEAM C — this file's owner).
7
+ *
8
+ * A cross-tenant grant is the ONLY sanctioned way (short of root) a
9
+ * principal reaches a resource owned by a DIFFERENT tenant. It is NEVER a root
10
+ * bypass: it is a HARD action-ceiling (ADR-0009). This helper enforces AC 13 — the
11
+ * two hard bounds a grant may never exceed:
12
+ *
13
+ * 1. **Action ceiling** — the attempted action key MUST be a member of the grant's
14
+ * `allowedActions` set (STRICT membership). A `view`+`edit` grant DENIES `delete`.
15
+ * 2. **Scope coverage** — the grant must cover THIS resource: same object type, and
16
+ * for a `record`-scoped grant the exact record id. A grant scoped to one record
17
+ * (or one object type) DENIES every other record / object type.
18
+ *
19
+ * ── FAIL-CLOSED on ANY ambiguity. Any condition that is not affirmatively satisfied
20
+ * yields `applicable: false` — never a permit. An UNKNOWN scope shape is treated as
21
+ * "does not apply" (a hostile/garbage `scope` can never open access). Expiry is
22
+ * re-checked defensively even though the port is contracted to return only ACTIVE
23
+ * grants (defense-in-depth, per the {@link CrossTenantGrantPort.findActiveGrant}
24
+ * contract — "the engine additionally re-checks the returned grant's allowedActions
25
+ * + expiresAtMs").
26
+ *
27
+ * ── TRANSIENT-vs-DENY (ADR-0016). This helper NEVER catches. A `null` grant from the
28
+ * port is a normal data-absence → `applicable: false`. A transient
29
+ * {@link AuthorizationUnavailableError} (or any other throw) from the port
30
+ * PROPAGATES unchanged so `decide()` can re-throw it (503-retryable). We never
31
+ * swallow a transient into a "not applicable" — that would silently downgrade an
32
+ * outage to a Deny.
33
+ *
34
+ * ── PURE + zero-dep. No I/O of its own beyond the injected port; no framework / DB /
35
+ * node imports (ADR-0003). The `now` clock is injectable for deterministic tests;
36
+ * it defaults to `Date.now`, matching the port contract ("the clock is the
37
+ * engine's").
38
+ */
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.isCrossTenantGrantApplicable = isCrossTenantGrantApplicable;
41
+ const reason_codes_js_1 = require("../reason-codes.js");
42
+ const NOT_APPLICABLE = Object.freeze({
43
+ applicable: false,
44
+ grant: null,
45
+ });
46
+ /**
47
+ * Resolve whether an ACTIVE, consented cross-tenant grant permits `subject.action`
48
+ * on `subject.resource` for `subject.principal` — the single-source AC-13 ceiling +
49
+ * scope evaluator shared across gates 3/5/6.
50
+ *
51
+ * Sequence (all conditions must hold, else `applicable:false`):
52
+ * 1. Ask {@link CrossTenantGrantPort.findActiveGrant} for a grant covering the
53
+ * resource's owning tenant + object type + action (+ record id for record-scoped).
54
+ * `null` ⇒ no consent ⇒ not applicable.
55
+ * 2. **Action ceiling** — `action.key` ∈ `grant.allowedActions` (strict membership).
56
+ * 3. **Scope coverage** — `object_type`-scoped covers every record of that type;
57
+ * `record`-scoped covers ONLY its `recordId`. Object type must match. Unknown
58
+ * scope shape ⇒ not applicable.
59
+ * 4. **Expiry (defensive)** — `grant.expiresAtMs > now`, even though the port
60
+ * should only return active grants.
61
+ *
62
+ * @throws propagates any {@link AuthorizationUnavailableError} (or other error) the
63
+ * port throws — a transient must NOT be swallowed into "not applicable".
64
+ */
65
+ async function isCrossTenantGrantApplicable(port, subject, options = {}) {
66
+ const { principal, action, resource } = subject;
67
+ const owningTenantId = resource.tenantId;
68
+ // A grant is only meaningful for a resource with a known owning tenant. Absent one,
69
+ // there is nothing to consent across — fail closed.
70
+ if (owningTenantId === undefined || owningTenantId.length === 0) {
71
+ return NOT_APPLICABLE;
72
+ }
73
+ // Ask the port. A transient throw PROPAGATES (never caught here) so the pipeline
74
+ // re-throws it (ADR-0016); a `null` is a normal data-absence (no active consent).
75
+ // `recordId` is only included when present (exactOptionalPropertyTypes: no explicit
76
+ // `undefined` on an optional field).
77
+ const query = {
78
+ grantee: principal.id,
79
+ roleIds: principal.roleIds,
80
+ owningTenantId,
81
+ typeKey: resource.typeKey,
82
+ action: action.key,
83
+ ...(resource.recordId !== undefined ? { recordId: resource.recordId } : {}),
84
+ };
85
+ const grant = await port.findActiveGrant(query);
86
+ if (grant === null) {
87
+ return NOT_APPLICABLE;
88
+ }
89
+ // From here the port RETURNED a grant, but we do NOT trust it blindly — the ceiling
90
+ // + scope + expiry are re-verified (defense-in-depth per the port contract). Any
91
+ // failing check ⇒ the grant exists but does not apply (return it for the consumer,
92
+ // `applicable:false`).
93
+ if (!clearsActionCeiling(grant, action.key)) {
94
+ return { applicable: false, grant };
95
+ }
96
+ if (!coversResource(grant, resource)) {
97
+ return { applicable: false, grant };
98
+ }
99
+ if (!isUnexpired(grant, options.now ?? Date.now)) {
100
+ return { applicable: false, grant };
101
+ }
102
+ return { applicable: true, grant };
103
+ }
104
+ /**
105
+ * AC-13 ACTION CEILING — the attempted action key must be a member of the grant's
106
+ * `allowedActions`. STRICT membership (exact string equality, no wildcard, no prefix):
107
+ * a `['view','edit']` grant must DENY `delete`. Defends against a malformed
108
+ * `allowedActions` (non-array / non-string members) by treating it as empty (no
109
+ * action permitted) — fail-closed.
110
+ */
111
+ function clearsActionCeiling(grant, actionKey) {
112
+ const allowed = grant.allowedActions;
113
+ if (!Array.isArray(allowed)) {
114
+ return false;
115
+ }
116
+ // Strict membership: only an exact-string match permits. `strictTrue` guards the
117
+ // final boolean so a hostile array (e.g. containing objects) can never fail open.
118
+ return (0, reason_codes_js_1.strictTrue)(allowed.some((a) => a === actionKey));
119
+ }
120
+ /**
121
+ * AC-13 SCOPE COVERAGE — does the grant's scope cover THIS resource?
122
+ * - object type MUST match the grant's `typeKey` (a grant on type A never covers B);
123
+ * - `object_type` scope covers every record of that type (record id irrelevant);
124
+ * - `record` scope covers ONLY its declared `recordId`, and requires the resource to
125
+ * carry a matching `recordId`;
126
+ * - any OTHER (unknown) scope shape ⇒ NOT covered (fail-closed on ambiguity).
127
+ */
128
+ function coversResource(grant, resource) {
129
+ // Object type must match regardless of scope.
130
+ if (grant.typeKey !== resource.typeKey) {
131
+ return false;
132
+ }
133
+ switch (grant.scope) {
134
+ case 'object_type':
135
+ // Whole-type grant — covers every record of this object type.
136
+ return true;
137
+ case 'record': {
138
+ // Record-scoped grant — covers ONLY its exact record. Both the grant and the
139
+ // resource must name the SAME non-empty record id.
140
+ const grantRecordId = grant.recordId;
141
+ const resourceRecordId = resource.recordId;
142
+ if (grantRecordId === undefined ||
143
+ grantRecordId.length === 0 ||
144
+ resourceRecordId === undefined ||
145
+ resourceRecordId.length === 0) {
146
+ return false;
147
+ }
148
+ return grantRecordId === resourceRecordId;
149
+ }
150
+ default:
151
+ // Unknown / hostile scope shape — never covers anything (fail-closed).
152
+ return false;
153
+ }
154
+ }
155
+ /**
156
+ * Defensive expiry re-check (ADR-0009). The port is contracted to return only ACTIVE
157
+ * grants, but the engine re-checks `expiresAtMs` as defense-in-depth: a grant with
158
+ * `expiresAtMs <= now` is INACTIVE and does not apply. A non-finite/absent expiry is
159
+ * treated as expired (fail-closed) — an active grant MUST carry a real future expiry.
160
+ */
161
+ function isUnexpired(grant, now) {
162
+ const expiresAtMs = grant.expiresAtMs;
163
+ if (typeof expiresAtMs !== 'number' || !Number.isFinite(expiresAtMs)) {
164
+ return false;
165
+ }
166
+ return expiresAtMs > now();
167
+ }
@@ -0,0 +1,213 @@
1
+ "use strict";
2
+ /**
3
+ * The Authorization **engine** — the body behind the FROZEN {@link DecisionAuthority}
4
+ * seam (`./index.ts`). `decide(principal, action, resource, context) → Decision`,
5
+ * THE single decision authority (§7.1). Every enforcement point calls this one
6
+ * path; there is NO divergent per-feature/resource-level/principal-type logic.
7
+ *
8
+ * Mirrors the Session engine (`../session/session-authority.ts`) EXACTLY: a pure
9
+ * `createDecisionAuthority(...)` factory over INJECTED deps (ports + registry +
10
+ * per-request session facts + the four team-supplied gate functions), a stateless
11
+ * impl, STRICT `=== true` gates over verdict-returning ports, and a top-level
12
+ * try/catch → fail-closed.
13
+ *
14
+ * ── THE ONE DECISION PATH — gate order (KICKOFF §"The one decision path", verbatim
15
+ * §7.3 hard gates → permit tier; deny wins). `decide()` runs EXACTLY this
16
+ * sequence; EVERY Allow traverses it and escapes via a short-circuit; the
17
+ * terminal is a fail-closed Deny. There is no second route to Allow.
18
+ *
19
+ * 0. Resource registration → `resource_not_registered` if unregistered.
20
+ * 1. Tier + Public → tier `public` ⇒ Allow, consulting NO port.
21
+ * 2. Authentication gate → non-public + unauth ⇒ `not_authenticated`.
22
+ * 3. Tenant gate → mismatch + no grant + not root ⇒
23
+ * `tenant_mismatch` (TEAM A/C, via a gate-fn).
24
+ * 4. Authenticated-Global → tier `authenticated_global` ⇒ Allow, AFTER 3.
25
+ * 5. Feature/Object-type gate → gated + no grant ⇒ `missing_object_type_grant`
26
+ * (TEAM A, via a gate-fn); feature/object level
27
+ * terminates here (Allow if held).
28
+ * 6. Record permit tier → record level only; deny-wins; rule ∪ share ∪
29
+ * grant (TEAM B/C, via a gate-fn).
30
+ * 7. Delegation overlay → trusted operation identity (TEAM D, via a
31
+ * gate-fn); re-evaluates 3–6 under the operation
32
+ * scope; tenant STILL applies; never wildcard.
33
+ * 8. Fail-closed default → any unresolved path / unexpected exception ⇒
34
+ * `deny_by_default`. Typed transient ⇒ RE-THROW.
35
+ *
36
+ * ── ADR-0016 CLASSIFICATION (KICKOFF §"BINDING ARCHITECT DECISION"): the top-level
37
+ * catch RE-THROWS a {@link AuthorizationUnavailableError} unchanged (a genuine
38
+ * transient must propagate to the enforcement adapter → 503-retryable, request
39
+ * unserved). ANY OTHER thrown error → fail-closed `deny_by_default` (never
40
+ * throw-to-open, never an unavailable masquerade).
41
+ *
42
+ * ── PRELUDE SCOPE: this file implements the PIPELINE STRUCTURE + the pure/trivial
43
+ * short-circuits (gates 0, 1, 2, 4, 8) + the ADR-0016 classification. Gates 3,
44
+ * 5, 6, 7 are SEAM functions (`TenantGateFn`, `ObjectTypeGateFn`,
45
+ * `RecordPermitFn`, `DelegationOverlayFn`) that Teams A/B/C/D implement and the
46
+ * integration owner injects. The prelude ships trivial DENY-BY-DEFAULT defaults
47
+ * (see `./default-gates.js`) so the file compiles + tests pass NOW; teams
48
+ * replace the defaults with real evaluators.
49
+ *
50
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
51
+ */
52
+ Object.defineProperty(exports, "__esModule", { value: true });
53
+ exports.gateContinue = gateContinue;
54
+ exports.gateAllow = gateAllow;
55
+ exports.gateDeny = gateDeny;
56
+ exports.createDecisionAuthority = createDecisionAuthority;
57
+ const errors_js_1 = require("./errors.js");
58
+ const reason_codes_js_1 = require("./reason-codes.js");
59
+ /** Constructor: this gate is satisfied / not applicable — proceed. */
60
+ function gateContinue() {
61
+ return { kind: 'continue' };
62
+ }
63
+ /** Constructor: this gate short-circuits to ALLOW. */
64
+ function gateAllow() {
65
+ return { kind: 'allow' };
66
+ }
67
+ /** Constructor: this gate short-circuits to DENY with a reason-mapped Decision. */
68
+ function gateDeny(decision) {
69
+ return { kind: 'deny', decision };
70
+ }
71
+ // ---------------------------------------------------------------------------
72
+ // The engine.
73
+ // ---------------------------------------------------------------------------
74
+ /** Stateless per call; holds only the injected deps. From {@link createDecisionAuthority}. */
75
+ class DecisionAuthorityImpl {
76
+ deps;
77
+ constructor(deps) {
78
+ this.deps = deps;
79
+ }
80
+ async decide(principal, action, resource, context) {
81
+ try {
82
+ return await this.runPipeline(principal, action, resource, context);
83
+ }
84
+ catch (err) {
85
+ // ── ADR-0016 CLASSIFICATION — the single point where transient ≠ deny. ──
86
+ // A genuine transient must PROPAGATE (adapter → 503-retryable, request
87
+ // unserved). Everything else is an UNEXPECTED failure → fail-closed deny
88
+ // (never throw-to-open, never fabricate an unavailable).
89
+ //
90
+ // ⛔ DUAL-BUILD SAFE: use `isAuthorizationUnavailable` (instanceof OR the
91
+ // global-registry brand), NOT a bare `instanceof`. Core is built twice (ESM + CJS);
92
+ // a guard adapter compiled against the OTHER build throws a differently-realized
93
+ // AuthorizationUnavailableError for which a bare `instanceof` is FALSE — that would
94
+ // mask a genuine store outage as `deny_by_default` (403) instead of the retryable 503
95
+ // the ADR mandates. The brand crosses the build boundary; an ordinary Error still has
96
+ // neither → fail-closed deny (that path unchanged).
97
+ if ((0, errors_js_1.isAuthorizationUnavailable)(err)) {
98
+ throw err;
99
+ }
100
+ return (0, reason_codes_js_1.denyByDefault)();
101
+ }
102
+ }
103
+ /** The ONE decision path (gates 0→8). Every Allow escapes via a short-circuit. */
104
+ async runPipeline(principal, action, resource, context) {
105
+ const { registry, gates } = this.deps;
106
+ // ── Gate 0 — Resource registration (§5.4/5.5). Unregistered ⇒ Deny. ───────
107
+ const objectType = registry.resolveObjectType(resource.typeKey);
108
+ if (objectType === undefined) {
109
+ return (0, reason_codes_js_1.denyResourceNotRegistered)();
110
+ }
111
+ // ── Gate 1 — Tier resolution + Public short-circuit (§6/§7.3.1). ─────────
112
+ // A `public` action is reachable with NO authz and consults NO port. Resolve
113
+ // the action's baseline tier from the registry via the canonical `resolveTier`
114
+ // 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);
121
+ // Prefer the registry's ALREADY-RESOLVED `tier` (single-source; the registry
122
+ // derived it via the canonical `resolveTier` at registration) over re-calling
123
+ // `resolveTier(registered.action)` here — behavior identical. An action not
124
+ // registered for this type resolves to the fail-closed `gated` default.
125
+ const tier = registered === undefined ? 'gated' : registered.tier;
126
+ if (tier === 'public') {
127
+ return (0, reason_codes_js_1.allow)();
128
+ }
129
+ // ── Gate 2 — Authentication gate (§7.3.1). Non-public + unauth ⇒ Deny. ───
130
+ if (context.isAuthenticated !== true) {
131
+ return (0, reason_codes_js_1.denyNotAuthenticated)();
132
+ }
133
+ // Assemble the shared gate context once (ports + registry + per-request facts).
134
+ const gctx = {
135
+ principal,
136
+ action,
137
+ resource,
138
+ context,
139
+ tier,
140
+ deps: {
141
+ registry: this.deps.registry,
142
+ permissionFacts: this.deps.permissionFacts,
143
+ recordRule: this.deps.recordRule,
144
+ recordShare: this.deps.recordShare,
145
+ crossTenantGrant: this.deps.crossTenantGrant,
146
+ operationAuthority: this.deps.operationAuthority,
147
+ sessionFacts: this.deps.sessionFacts,
148
+ },
149
+ };
150
+ // ── Gate 3 — Tenant gate (TEAM A/C). deny(tenant_mismatch) | continue. ───
151
+ const tenant = await gates.tenantGate(gctx);
152
+ if (tenant.kind === 'deny')
153
+ return tenant.decision;
154
+ if (tenant.kind === 'allow') {
155
+ // The tenant gate must not short-circuit to Allow (it only lets eval proceed);
156
+ // treat an unexpected `allow` as fail-closed rather than trusting it.
157
+ return (0, reason_codes_js_1.denyByDefault)();
158
+ }
159
+ // ── Gate 4 — Authenticated-Global short-circuit (§6.2), AFTER gate 3. ────
160
+ // Tenant scoping is NEVER relaxed, so this comes strictly after the tenant gate.
161
+ if (tier === 'authenticated_global') {
162
+ return (0, reason_codes_js_1.allow)();
163
+ }
164
+ // ── Gate 5 — Feature / Object-type gate (TEAM A). ────────────────────────
165
+ // allow ⇒ feature/object-type level held (terminates); continue ⇒ record level.
166
+ // deny ⇒ becomes the BASELINE (not an early return) so gate 7 (delegation) gets
167
+ // its chance to override it for a delegated step (§10.1/AC-15, RULING 3). A
168
+ // non-delegated request is unaffected: gate 7 passes through and this deny stands
169
+ // verbatim; a `tenant_mismatch` (from a covering-grant proceed path) is likewise
170
+ // never overridden (isOverridablePermissionDeny → false).
171
+ const objectGate = await gates.objectTypeGate(gctx);
172
+ let baseline;
173
+ if (objectGate.kind === 'deny') {
174
+ baseline = objectGate.decision;
175
+ }
176
+ else if (objectGate.kind === 'allow') {
177
+ baseline = (0, reason_codes_js_1.allow)();
178
+ }
179
+ else {
180
+ // ── Gate 6 — Record permit tier (TEAM B/C), record level only. ─────────
181
+ const permit = await gates.recordPermit(gctx);
182
+ if (permit.kind === 'deny') {
183
+ baseline = permit.decision;
184
+ }
185
+ else if (permit.kind === 'allow') {
186
+ baseline = (0, reason_codes_js_1.allow)();
187
+ }
188
+ else {
189
+ // A record gate that neither allows nor denies is an unresolved path.
190
+ baseline = (0, reason_codes_js_1.denyByDefault)();
191
+ }
192
+ }
193
+ // ── Gate 7 — Delegation overlay (TEAM D). Pass-through ⇒ baseline stands. ─
194
+ const overlay = await gates.delegationOverlay(gctx, baseline);
195
+ if (overlay.kind === 'deny')
196
+ return overlay.decision;
197
+ if (overlay.kind === 'allow')
198
+ return (0, reason_codes_js_1.allow)();
199
+ // ── Gate 8 — Fail-closed terminal. The baseline (Allow if a gate granted it,
200
+ // else a specific deny / deny_by_default). Every Allow reached here came
201
+ // from a gate short-circuit above; there is no other route to Allow.
202
+ return baseline;
203
+ }
204
+ }
205
+ /**
206
+ * Wire the injected deps and return an object implementing the FROZEN
207
+ * {@link DecisionAuthority}. The engine's public entry point (mirrors
208
+ * `createSessionAuthority`). PURE — no I/O at construction; the gates + ports do
209
+ * their work lazily inside `decide()`.
210
+ */
211
+ function createDecisionAuthority(deps) {
212
+ return new DecisionAuthorityImpl(deps);
213
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ /**
3
+ * PRELUDE DEFAULT GATES — trivial, fail-closed placeholders for the four seam gate
4
+ * functions (gates 3/5/6/7) so `createDecisionAuthority(...)` compiles and the
5
+ * prelude's own guarantees are testable NOW, BEFORE Teams A/B/C/D ship the real
6
+ * evaluators.
7
+ *
8
+ * ⛔ These are DELIBERATELY the most conservative possible bodies — deny-by-default
9
+ * everywhere (the tenant gate `continue`s ONLY so the pipeline can be exercised
10
+ * end-to-end; every other gate denies). They implement NO real authorization logic.
11
+ * The integration owner REPLACES each with the corresponding team's evaluator when
12
+ * wiring the real `DecisionAuthorityDeps.gates`.
13
+ *
14
+ * - `defaultTenantGate` → `continue` (same-tenant assumption for the skeleton
15
+ * ONLY; TEAM A/C replace it with the real tenant + cross-tenant-grant gate).
16
+ * - `defaultObjectTypeGate` → `deny(deny_by_default)` (TEAM A replaces).
17
+ * - `defaultRecordPermit` → `deny(deny_by_default)` (TEAM B/C replace).
18
+ * - `defaultDelegationOverlay` → `continue` (pass-through: baseline stands;
19
+ * TEAM D replaces with the real delegation overlay).
20
+ *
21
+ * A default-wired authority therefore DENIES every gated/authenticated request
22
+ * (fail-closed) except the pure short-circuits the pipeline owns (public tier,
23
+ * authenticated_global) — exactly what a not-yet-filled authority must do.
24
+ *
25
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
26
+ */
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.DEFAULT_DENY_BY_DEFAULT_GATES = exports.defaultDelegationOverlay = exports.defaultRecordPermit = exports.defaultObjectTypeGate = exports.defaultTenantGate = void 0;
29
+ const decision_authority_js_1 = require("./decision-authority.js");
30
+ const reason_codes_js_1 = require("./reason-codes.js");
31
+ /** Prelude default: let evaluation PROCEED past the tenant gate (skeleton only). */
32
+ const defaultTenantGate = async () => (0, decision_authority_js_1.gateContinue)();
33
+ exports.defaultTenantGate = defaultTenantGate;
34
+ /** Prelude default: DENY at the feature/object-type gate (fail-closed until TEAM A). */
35
+ const defaultObjectTypeGate = async () => (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyByDefault)());
36
+ exports.defaultObjectTypeGate = defaultObjectTypeGate;
37
+ /** Prelude default: DENY at the record permit tier (fail-closed until TEAM B/C). */
38
+ const defaultRecordPermit = async () => (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyByDefault)());
39
+ exports.defaultRecordPermit = defaultRecordPermit;
40
+ /** Prelude default: pass-through delegation overlay (baseline stands until TEAM D). */
41
+ const defaultDelegationOverlay = async () => (0, decision_authority_js_1.gateContinue)();
42
+ exports.defaultDelegationOverlay = defaultDelegationOverlay;
43
+ /**
44
+ * The complete deny-by-default gate set — inject this as `DecisionAuthorityDeps.gates`
45
+ * to get a compiling, fail-closed authority the prelude tests exercise. Teams replace
46
+ * each member with the real evaluator at integration.
47
+ */
48
+ exports.DEFAULT_DENY_BY_DEFAULT_GATES = Object.freeze({
49
+ tenantGate: exports.defaultTenantGate,
50
+ objectTypeGate: exports.defaultObjectTypeGate,
51
+ recordPermit: exports.defaultRecordPermit,
52
+ delegationOverlay: exports.defaultDelegationOverlay,
53
+ });