@astram/core 0.1.0 → 1.0.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 +23 -4
  41. package/dist/authorization/index.d.ts.map +1 -1
  42. package/dist/authorization/index.js +29 -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 +124 -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,398 @@
1
+ "use strict";
2
+ /**
3
+ * The Session **engine** — the body behind the FROZEN {@link SessionAuthority}
4
+ * seam (`./index.ts`). Establishes a session on login, ROTATES the refresh token
5
+ * on refresh (with THEFT DETECTION), and revokes on logout. Orchestrates the
6
+ * two-tier hybrid storage (ADR-0013): durable MariaDB records written ONLY at
7
+ * lifecycle events, hot Redis state (re)populated at those same events and served
8
+ * per-request WITHOUT ever touching the DB.
9
+ *
10
+ * Mirrors the Authentication engine (`../authentication/authenticator.ts`)
11
+ * EXACTLY: a pure `createSessionAuthority(...)` factory over INJECTED ports, a
12
+ * stateless impl, STRICT `=== true` gates over verdict-returning ports, and a
13
+ * top-level try/catch on every public method → a GENERIC fail-closed reject that
14
+ * NEVER leaks a token, a hash, or resource existence.
15
+ *
16
+ * ── THE SECURITY CORE — reuse detection → lineage kill (ADR-0013/0015):
17
+ * Every refresh rotates the token (mint a new pair, mark the old `rotated`, same
18
+ * lineage). A refresh token presented AFTER it was rotated out (or after the
19
+ * lineage was revoked) is a REPLAY — the sign of a stolen token. On that signal
20
+ * the engine calls `recordStore.revokeLineage(lineageId)`, killing EVERY refresh
21
+ * record AND the session in the chain (including the legitimate holder's live
22
+ * token), then rejects. Both the thief and the victim are logged out; the
23
+ * attacker cannot ride a stolen token forward, and the reuse is durably recorded.
24
+ *
25
+ * ── SILENT RECOVERY (ADR-0013): rotate re-populates Redis from the DURABLE record
26
+ * every time. A Redis loss (restart/eviction) is recovered at the user's next
27
+ * refresh with no forced re-login — the durable tier is the source of truth for
28
+ * rotation, and the hot tier is rebuilt from it.
29
+ *
30
+ * ── HOT PATH NEVER TOUCHES THE DB (ADR-0013): the per-request read path
31
+ * ({@link readHotSession}) calls ONLY the hot store; it makes ZERO durable-store
32
+ * calls, and fails CLOSED if the hot store cannot answer (never falls back to
33
+ * MariaDB, ADR-0013/0016).
34
+ *
35
+ * ── PERM-VERSION / FACTS SLOT (ADR-0011): establish seeds a hot record with
36
+ * `permissionsVersion: 0` and an OPAQUE `cachedFacts: null` slot; rotate carries
37
+ * the version forward. This layer only STORES/RE-POPULATES/INVALIDATES the slot —
38
+ * it does NOT project fact content, version-compare, or reload (that is
39
+ * Authorization, step 8).
40
+ *
41
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
42
+ */
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.SessionRejectedError = exports.SESSION_REJECTED_REASON = void 0;
45
+ exports.readHotSession = readHotSession;
46
+ exports.createSessionAuthority = createSessionAuthority;
47
+ const lifetimes_js_1 = require("./lifetimes.js");
48
+ /**
49
+ * A single GENERIC failure for every rejected session-lifecycle path (unknown
50
+ * token, replay, expiry, port outage). It NEVER distinguishes them and NEVER
51
+ * carries a token/hash — mirrors the Authentication engine's anti-enumeration
52
+ * reason discipline. Thrown as a typed error so a caller gets a uniform rejection
53
+ * rather than a raw 500 that could leak store internals.
54
+ */
55
+ exports.SESSION_REJECTED_REASON = 'session_rejected';
56
+ /** The one error type the engine rejects with — always the generic reason. */
57
+ class SessionRejectedError extends Error {
58
+ constructor() {
59
+ super(exports.SESSION_REJECTED_REASON);
60
+ this.name = 'SessionRejectedError';
61
+ }
62
+ }
63
+ exports.SessionRejectedError = SessionRejectedError;
64
+ /** The initial ADR-0011 permission version for a freshly-established session. */
65
+ const INITIAL_PERMISSIONS_VERSION = 0;
66
+ /** The initial cached-facts slot value — not yet projected (Authorization fills it). */
67
+ const INITIAL_CACHED_FACTS = null;
68
+ /** The Redis hot-session key for a session id (tenant-scoped, opaque, no PII). */
69
+ function hotKey(sessionId) {
70
+ return `shield:sess:${sessionId}`;
71
+ }
72
+ /**
73
+ * The concrete engine. Stateless per call; holds only its injected capabilities +
74
+ * the resolved lifetime config. Instances come from {@link createSessionAuthority}.
75
+ */
76
+ class SessionAuthorityImpl {
77
+ recordStore;
78
+ hotStore;
79
+ tokenGenerator;
80
+ refreshHasher;
81
+ clock;
82
+ lifetimes;
83
+ deviceTrust;
84
+ constructor(recordStore, hotStore, tokenGenerator, refreshHasher, clock, lifetimes, deviceTrust) {
85
+ this.recordStore = recordStore;
86
+ this.hotStore = hotStore;
87
+ this.tokenGenerator = tokenGenerator;
88
+ this.refreshHasher = refreshHasher;
89
+ this.clock = clock;
90
+ this.lifetimes = lifetimes;
91
+ this.deviceTrust = deviceTrust;
92
+ }
93
+ // -- establish (login) ----------------------------------------------------
94
+ async establish(principal) {
95
+ try {
96
+ return await this.doEstablish(principal);
97
+ }
98
+ catch {
99
+ // FAIL-CLOSED: any port outage / unexpected throw → a generic rejection,
100
+ // never a raw throw that could leak store internals or a token. The error
101
+ // object is deliberately swallowed so nothing about it can leak.
102
+ throw new SessionRejectedError();
103
+ }
104
+ }
105
+ async doEstablish(principal) {
106
+ // Validate the principal shape (never mint a session for a malformed one).
107
+ if (principal === null ||
108
+ typeof principal !== 'object' ||
109
+ typeof principal.id !== 'string' ||
110
+ principal.id.length === 0 ||
111
+ typeof principal.tenantId !== 'string' ||
112
+ principal.tenantId.length === 0) {
113
+ throw new SessionRejectedError();
114
+ }
115
+ const nowMs = this.clock.nowMs();
116
+ // Opaque unguessable ids via the same crypto port that mints tokens.
117
+ const sessionId = this.tokenGenerator.mint();
118
+ const lineageId = this.tokenGenerator.mint();
119
+ const refreshId = this.tokenGenerator.mint();
120
+ const accessToken = this.tokenGenerator.mint();
121
+ const refreshToken = this.tokenGenerator.mint();
122
+ // ⛔ Hash the refresh token BEFORE it ever reaches the durable store.
123
+ const tokenHash = this.refreshHasher.hash(refreshToken);
124
+ const absoluteExpiresAtMs = nowMs + this.lifetimes.refreshAbsoluteCapMs;
125
+ const idleExpiresAtMs = nowMs + this.lifetimes.refreshIdleMs;
126
+ // Durable tier first (ADR-0013 write ordering: DB record, then hot cache).
127
+ await this.recordStore.createSession({
128
+ sessionId,
129
+ principalId: principal.id,
130
+ tenantId: principal.tenantId,
131
+ issuedAtMs: nowMs,
132
+ absoluteExpiresAtMs,
133
+ });
134
+ await this.recordStore.insertRefreshRecord({
135
+ refreshId,
136
+ sessionId,
137
+ lineageId,
138
+ prevRefreshId: null,
139
+ tokenHash,
140
+ issuedAtMs: nowMs,
141
+ idleExpiresAtMs,
142
+ });
143
+ // Advisory device-trust hook (no-op slot). Never gates establishment; its
144
+ // result is not consumed by this layer beyond being invoked for future hooks.
145
+ await this.runDeviceTrust(principal, sessionId);
146
+ // Hot tier: seed the per-request record with the ADR-0011 version + facts slot.
147
+ await this.putHot(sessionId, principal, INITIAL_PERMISSIONS_VERSION, INITIAL_CACHED_FACTS);
148
+ const session = this.freezeSession({
149
+ sessionId,
150
+ principalId: principal.id,
151
+ tenantId: principal.tenantId,
152
+ status: 'active',
153
+ issuedAtMs: nowMs,
154
+ // Session-level expiry = the access-token bound (hot state TTL). Absolute
155
+ // cap lives on the durable record; refresh sliding window on the refresh record.
156
+ expiresAtMs: nowMs + this.lifetimes.accessTtlMs,
157
+ });
158
+ // The raw refresh token leaves the engine EXACTLY ONCE, here. Never persisted.
159
+ return Object.freeze({
160
+ session,
161
+ tokens: Object.freeze({ accessToken, refreshToken }),
162
+ });
163
+ }
164
+ // -- rotate (refresh) -----------------------------------------------------
165
+ async rotate(refreshToken) {
166
+ try {
167
+ return await this.doRotate(refreshToken);
168
+ }
169
+ catch {
170
+ // FAIL-CLOSED (same discipline as establish). NOTE: a reuse-detected replay
171
+ // performs its lineage-kill INSIDE doRotate and then throws — that throw is
172
+ // caught here and re-surfaced as the SAME generic rejection, so the reason
173
+ // never distinguishes "replay" from "unknown token".
174
+ throw new SessionRejectedError();
175
+ }
176
+ }
177
+ async doRotate(refreshToken) {
178
+ if (typeof refreshToken !== 'string' || refreshToken.length === 0) {
179
+ throw new SessionRejectedError();
180
+ }
181
+ // Look up by HASH only — the raw token is never stored, never logged.
182
+ const tokenHash = this.refreshHasher.hash(refreshToken);
183
+ const record = await this.recordStore.findRefreshByHash(tokenHash);
184
+ // ABSENT ⇒ unknown / forged token ⇒ fail-closed reject (no lineage to kill).
185
+ if (record === null || record === undefined || typeof record !== 'object') {
186
+ throw new SessionRejectedError();
187
+ }
188
+ // ⛔ REUSE DETECTION (the security core): a FOUND token whose record is NOT
189
+ // `active` (already `rotated`, or `revoked`, or `expired`) is a REPLAY of a
190
+ // spent token — the signature of theft. Kill the ENTIRE lineage (every refresh
191
+ // record + the session), then reject. Both thief and victim are cut off.
192
+ if (record.status !== 'active') {
193
+ await this.recordStore.revokeLineage(record.lineageId);
194
+ throw new SessionRejectedError();
195
+ }
196
+ const nowMs = this.clock.nowMs();
197
+ // Fetch the durable session — the AUTHORITATIVE identity + absolute-cap anchor,
198
+ // and the silent-recovery source of truth. (Refresh IS a lifecycle event, so a
199
+ // durable read is allowed — unlike the per-request hot path.) A missing session
200
+ // (revoked / gone) ⇒ fail closed.
201
+ const session = await this.recordStore.findSessionById(record.sessionId);
202
+ if (session === null || session === undefined || typeof session !== 'object') {
203
+ throw new SessionRejectedError();
204
+ }
205
+ // A durably-revoked/expired session refuses refreshes (ADR-0013): even if the
206
+ // refresh record still read `active`, the session gate wins.
207
+ if (session.status !== 'active') {
208
+ throw new SessionRejectedError();
209
+ }
210
+ // (1) IDLE window (ADR-0015): the sliding window resets each rotation. If the
211
+ // presented refresh record's idle expiry has passed, the session is idle-dead.
212
+ if (typeof record.idleExpiresAtMs !== 'number' || nowMs >= record.idleExpiresAtMs) {
213
+ await this.recordStore.markRevoked(record.refreshId);
214
+ throw new SessionRejectedError();
215
+ }
216
+ // (2) ABSOLUTE cap (ADR-0015): bounded from LOGIN regardless of activity —
217
+ // enforced from the durable SESSION record's absolute expiry (never reset by
218
+ // rotation). A breach revokes the whole session so continuous rotation cannot
219
+ // outlive the cap.
220
+ if (typeof session.absoluteExpiresAtMs !== 'number' || nowMs >= session.absoluteExpiresAtMs) {
221
+ await this.recordStore.revokeSession(record.sessionId);
222
+ throw new SessionRejectedError();
223
+ }
224
+ // -- Active + within both windows ⇒ ATOMICALLY CLAIM, THEN ROTATE. -------
225
+ //
226
+ // ⛔ CONCURRENCY-SAFE REUSE DETECTION (the fix for the race the whole
227
+ // kill-switch exists to stop). The read above (`record.status === 'active'`)
228
+ // is NOT a safe basis to mint a successor: two near-simultaneous rotates of ONE
229
+ // token BOTH read `active` before either writes, and would BOTH mint valid
230
+ // pairs — the exact theft-vs-victim race. So we do NOT trust the read; we CLAIM
231
+ // the record with an ATOMIC compare-and-set and act on the RESULT:
232
+ // - claim === true ⇒ THIS caller flipped active→rotated; it WON → proceed.
233
+ // - claim !== true ⇒ LOST (a racing caller already rotated it, or it was
234
+ // spent) ⇒ a REPLAY of a now-spent token ⇒ kill the lineage + reject.
235
+ // STRICT `=== true` (defense-in-depth): a hostile/misbehaving store returning a
236
+ // truthy non-boolean must NOT be treated as a win (never fail open).
237
+ const won = (await this.recordStore.markRotatedIfActive(record.refreshId)) === true;
238
+ if (!won) {
239
+ // Lost the CAS ⇒ this token was already claimed/spent by another caller ⇒
240
+ // treat as reuse of a spent token: kill the ENTIRE lineage, then reject.
241
+ // Both the winner's live successor and this caller are cut off.
242
+ await this.recordStore.revokeLineage(record.lineageId);
243
+ throw new SessionRejectedError();
244
+ }
245
+ // ── WINNER ONLY past this point. ────────────────────────────────────────
246
+ const newRefreshId = this.tokenGenerator.mint();
247
+ const newAccessToken = this.tokenGenerator.mint();
248
+ const newRefreshToken = this.tokenGenerator.mint();
249
+ const newTokenHash = this.refreshHasher.hash(newRefreshToken);
250
+ const newIdleExpiresAtMs = nowMs + this.lifetimes.refreshIdleMs;
251
+ // Insert the successor in the SAME lineage, pointing back at the spent one.
252
+ // (The old record is ALREADY 'rotated' from the CAS above — so any later replay
253
+ // of it, sequential or concurrent, trips reuse detection and kills the lineage.)
254
+ await this.recordStore.insertRefreshRecord({
255
+ refreshId: newRefreshId,
256
+ sessionId: record.sessionId,
257
+ lineageId: record.lineageId,
258
+ prevRefreshId: record.refreshId,
259
+ tokenHash: newTokenHash,
260
+ issuedAtMs: nowMs,
261
+ idleExpiresAtMs: newIdleExpiresAtMs,
262
+ });
263
+ // SILENT RECOVERY: re-populate the hot tier from the durable identity. This
264
+ // runs every rotation, so a wiped Redis is rebuilt here with no re-login.
265
+ const { principalId, tenantId } = session;
266
+ if (typeof principalId !== 'string' ||
267
+ principalId.length === 0 ||
268
+ typeof tenantId !== 'string' ||
269
+ tenantId.length === 0) {
270
+ // Durable record is missing the identity needed to rebuild the hot record —
271
+ // fail closed rather than cache a half-formed session.
272
+ throw new SessionRejectedError();
273
+ }
274
+ await this.putHotRaw(record.sessionId, principalId, tenantId);
275
+ const rotatedSession = this.freezeSession({
276
+ sessionId: record.sessionId,
277
+ principalId,
278
+ tenantId,
279
+ status: 'active',
280
+ // `issuedAtMs` reflects the ORIGINAL login (from the durable record), so the
281
+ // session's identity + absolute-cap anchor stay stable across rotations. The
282
+ // freshly-minted access token's validity is the `expiresAtMs` bound below.
283
+ issuedAtMs: session.issuedAtMs,
284
+ expiresAtMs: nowMs + this.lifetimes.accessTtlMs,
285
+ });
286
+ return Object.freeze({
287
+ session: rotatedSession,
288
+ tokens: Object.freeze({ accessToken: newAccessToken, refreshToken: newRefreshToken }),
289
+ });
290
+ }
291
+ // -- revoke (logout / admin) ---------------------------------------------
292
+ async revoke(sessionId) {
293
+ try {
294
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
295
+ // Nothing to revoke; fail closed silently (revoke returns void either way).
296
+ return;
297
+ }
298
+ // Durable revoke (refuses all future refreshes of the lineage) + hot delete
299
+ // (drops it from the per-request path within the version-check bound).
300
+ await this.recordStore.revokeSession(sessionId);
301
+ await this.hotStore.deleteHotSession(hotKey(sessionId));
302
+ }
303
+ catch {
304
+ // Revoke is best-effort-idempotent; swallow to keep the contract void +
305
+ // never leak. A durable revoke that failed can be retried by the caller.
306
+ return;
307
+ }
308
+ }
309
+ // -- helpers --------------------------------------------------------------
310
+ freezeSession(s) {
311
+ return Object.freeze({ ...s });
312
+ }
313
+ async putHot(sessionId, principal, permissionsVersion, cachedFacts) {
314
+ const state = Object.freeze({
315
+ sessionId,
316
+ principalId: principal.id,
317
+ tenantId: principal.tenantId,
318
+ permissionsVersion,
319
+ cachedFacts,
320
+ });
321
+ await this.hotStore.putHotSession(hotKey(sessionId), state, this.lifetimes.accessTtlMs);
322
+ }
323
+ async putHotRaw(sessionId, principalId, tenantId) {
324
+ const state = Object.freeze({
325
+ sessionId,
326
+ principalId,
327
+ tenantId,
328
+ // Silent-recovery re-populate seeds the version/facts slot fresh; if a real
329
+ // version needs to survive a Redis loss it lives in the durable tier and is
330
+ // Authorization's concern to re-project. This layer only reserves the slot.
331
+ permissionsVersion: INITIAL_PERMISSIONS_VERSION,
332
+ cachedFacts: INITIAL_CACHED_FACTS,
333
+ });
334
+ await this.hotStore.putHotSession(hotKey(sessionId), state, this.lifetimes.accessTtlMs);
335
+ }
336
+ async runDeviceTrust(principal, sessionId) {
337
+ const hook = this.deviceTrust;
338
+ if (hook === undefined || typeof hook.isTrusted !== 'function') {
339
+ return; // no-op slot
340
+ }
341
+ try {
342
+ // Advisory only — the result is NOT allowed to grant/deny a session here.
343
+ await hook.isTrusted({
344
+ principalId: principal.id,
345
+ tenantId: principal.tenantId,
346
+ sessionId,
347
+ });
348
+ }
349
+ catch {
350
+ // A misbehaving hook must never fail-open OR break establishment; ignore.
351
+ return;
352
+ }
353
+ }
354
+ }
355
+ /**
356
+ * The per-request HOT READ path (ADR-0013). Deliberately a FREE function, NOT a
357
+ * SessionAuthority method — it is not a lifecycle event. It reads the hot store
358
+ * ALONE and makes ZERO durable-store calls. Fails CLOSED (returns `null`) when the
359
+ * hot store cannot answer (`unavailable`) — NEVER falls back to MariaDB
360
+ * (ADR-0013/0016). `absent` (a genuine miss) also returns `null` but is a distinct
361
+ * outcome the caller/enforcement can classify (ADR-0016 transient-vs-deny is
362
+ * Authorization's job; this only surfaces the fail-closed result).
363
+ *
364
+ * Returns the strict-`true` gate result: the {@link HotSessionState} ONLY on a
365
+ * genuine `found`; `null` on both `absent` and `unavailable` (fail-closed).
366
+ */
367
+ async function readHotSession(hotStore, sessionId) {
368
+ try {
369
+ if (typeof sessionId !== 'string' || sessionId.length === 0)
370
+ return null;
371
+ const outcome = await hotStore.getHotSession(hotKey(sessionId));
372
+ // STRICT discriminant: only a well-formed `found` yields state. Anything else
373
+ // — absent, unavailable, or a malformed/hostile outcome — fails closed.
374
+ if (outcome !== null &&
375
+ typeof outcome === 'object' &&
376
+ outcome.kind === 'found') {
377
+ const state = outcome.state;
378
+ if (state !== null && typeof state === 'object') {
379
+ return state;
380
+ }
381
+ }
382
+ return null;
383
+ }
384
+ catch {
385
+ // Hot store threw ⇒ cannot answer ⇒ fail CLOSED (never serve from durable).
386
+ return null;
387
+ }
388
+ }
389
+ /**
390
+ * Wire the injected ports and return an object implementing the FROZEN
391
+ * {@link SessionAuthority}. The engine's public entry point (mirrors
392
+ * `createAuthenticator`). Validates the lifetime config eagerly at construction
393
+ * (throws LOUD on a nonsensical config — construction-time, not a hot path).
394
+ */
395
+ function createSessionAuthority(options) {
396
+ const lifetimes = (0, lifetimes_js_1.resolveLifetimes)(options.lifetimes);
397
+ return new SessionAuthorityImpl(options.recordStore, options.hotStore, options.tokenGenerator, options.refreshHasher, options.clock, lifetimes, options.deviceTrust);
398
+ }
package/package.json CHANGED
@@ -1,32 +1,35 @@
1
1
  {
2
2
  "name": "@astram/core",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "license": "MIT",
5
5
  "description": "Astram framework — sealed security core (Identity, Authentication, Session, Risk, Authorization, Audit). ZERO framework deps — the portable decision brain (ADR-0003). The frozen public contract consumers build against; installed, not edited (ADR-0023).",
6
6
  "type": "module",
7
- "main": "dist/index.js",
7
+ "main": "./dist-cjs/index.js",
8
+ "module": "./dist/index.js",
8
9
  "types": "dist/index.d.ts",
9
10
  "exports": {
10
11
  ".": {
11
12
  "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js"
13
+ "import": "./dist/index.js",
14
+ "require": "./dist-cjs/index.js"
13
15
  }
14
16
  },
15
17
  "files": [
16
- "dist"
18
+ "dist",
19
+ "dist-cjs"
17
20
  ],
18
21
  "sideEffects": false,
19
22
  "publishConfig": {
20
23
  "access": "public"
21
24
  },
22
- "scripts": {
23
- "build": "tsc -p tsconfig.json",
24
- "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
25
- "test": "vitest run"
26
- },
27
25
  "dependencies": {},
28
26
  "devDependencies": {
29
27
  "typescript": "^5.7.0",
30
28
  "vitest": "^2.1.8"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/write-cjs-marker.mjs",
32
+ "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
33
+ "test": "vitest run"
31
34
  }
32
- }
35
+ }