@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,290 @@
1
+ "use strict";
2
+ /**
3
+ * The **Risk engine** — the body behind the FROZEN {@link RiskEngine} seam
4
+ * (`./index.ts`). SCORES a request from its signals into a `RiskScore` VALUE, and
5
+ * exposes a SEPARATE advisory `recommendStepUp` derivation (ADR-0017). Mirrors the
6
+ * Authentication / Session engines EXACTLY: a pure `createRiskEngine(...)` factory
7
+ * over injected capabilities (evaluators + thresholds), a stateless impl, STRICT
8
+ * gates, a top-level try/catch → a FAIL-SAFE result, no logging.
9
+ *
10
+ * ⛔ THE ASSESS-vs-ENFORCE LINE (this layer's whole point):
11
+ * Risk ASSESSES + RECOMMENDS; it NEVER ENFORCES. `assess()` returns a `RiskScore`
12
+ * VALUE — it NEVER blocks, mints, denies, or throws-in-a-way-that-acts-as-a-hard-
13
+ * deny. `recommendStepUp` is a PURE derivation OVER a `RiskScore`, NOT a field on
14
+ * the frozen type and NOT an enforcement action — advice a later layer reads.
15
+ *
16
+ * ⛔ THE FAIL-SAFE DIRECTION (uncertainty ⇒ HIGHER risk, NEVER "allow"):
17
+ * An unknown signal (no evaluator), a malformed value bag, or an evaluator that
18
+ * THROWS is treated as ELEVATING — it raises the score, never lowers or drops it.
19
+ * BUT fail-safe here = advise HARDER (higher value / recommend step-up), NOT
20
+ * throw-to-deny. `assess()` ALWAYS RESOLVES to a `RiskScore` — the outer catch
21
+ * yields a fail-safe HIGH-ish score, never an exception.
22
+ *
23
+ * ⛔ DETERMINISM: same `(principal, signals)` ⇒ same `RiskScore`, every call. NO
24
+ * wall-clock, NO RNG, NO order-dependence — aggregation is a commutative combine.
25
+ *
26
+ * ⛔ MONOTONICITY: adding a risky signal never DECREASES `value`; a superset of
27
+ * signals never scores lower than its subset. The combine is non-decreasing.
28
+ *
29
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
30
+ */
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.createRiskEngine = createRiskEngine;
33
+ exports.recommendStepUp = recommendStepUp;
34
+ const evaluator_js_1 = require("./evaluator.js");
35
+ const signals_js_1 = require("./signals.js");
36
+ const thresholds_js_1 = require("./thresholds.js");
37
+ /**
38
+ * The contribution assigned when a signal CANNOT be evaluated (no registered
39
+ * evaluator, or an evaluator threw). Equal to the reference fail-safe floor — an
40
+ * un-evaluable signal ELEVATES, never lowers or drops. This is the fail-safe
41
+ * DIRECTION expressed at the engine level.
42
+ */
43
+ const UNEVALUABLE_CONTRIBUTION = signals_js_1.FAIL_SAFE_CONTRIBUTION;
44
+ /**
45
+ * The score `assess()` resolves to when the WHOLE assessment throws unexpectedly
46
+ * (the top-level catch). A fail-safe HIGH score with no explainable kinds — Risk
47
+ * still RESOLVES (never throws-to-deny), but advises maximally hard.
48
+ */
49
+ const FAIL_SAFE_SCORE = Object.freeze({
50
+ level: 'high',
51
+ value: 1,
52
+ contributingSignals: Object.freeze([]),
53
+ });
54
+ /**
55
+ * Aggregate contributions into a single `0..1` value, DETERMINISTICALLY and
56
+ * ORDER-INDEPENDENTLY. Uses a BOUNDED probabilistic-OR combine:
57
+ *
58
+ * value = 1 − Π(1 − cᵢ)
59
+ *
60
+ * Properties this gives us for free (all required by the layer):
61
+ * - RANGE: always in `[0,1]` (each factor `(1−cᵢ) ∈ [0,1]`, product ∈ `[0,1]`).
62
+ * - COMMUTATIVE: multiplication is order-independent in exact arithmetic. ⚠️ IEEE-754
63
+ * multiplication is commutative but NOT associative, so a naive left-fold differs
64
+ * by ~1 ULP with input order — and `RiskScore.value` is audit-loggable, so it must
65
+ * be BYTE-identical for a given multiset. We therefore CANONICALIZE the fold:
66
+ * SORT the (clamped) contributions ascending so the multiplication order is fixed
67
+ * for a given multiset, THEN round the result to 1e-9 to kill any residual FP drift.
68
+ * Result: same multiset (any input order) ⇒ identical `value`, to the bit.
69
+ * - MONOTONIC: every factor `(1−cᵢ) ≤ 1`, so adding ANY signal multiplies the
70
+ * product by `≤ 1` ⇒ the product never grows ⇒ `value` never DECREASES. A
71
+ * zero-risk signal (`c=0`) multiplies by exactly 1 ⇒ no change (never lowers).
72
+ * (Sorting doesn't touch this — the multiset of factors is unchanged; the 1e-9
73
+ * round is coarse enough never to invert the order of two genuinely-distinct scores.)
74
+ * - No single signal can drop the score below the running floor.
75
+ */
76
+ function combine(contributions) {
77
+ // Clamp each contribution to [0,1] (defense-in-depth; the caller already clamps),
78
+ // then SORT ascending so the fold order is deterministic for a given multiset —
79
+ // making `value` order-independent to the BIT (IEEE-754 is commutative but not
80
+ // associative, so a fixed order is required, not just commutativity).
81
+ const sorted = contributions
82
+ .map((c) => (c < 0 ? 0 : c > 1 ? 1 : c))
83
+ .sort((a, b) => a - b);
84
+ let complement = 1;
85
+ for (const c of sorted) {
86
+ complement *= 1 - c;
87
+ }
88
+ let value = 1 - complement;
89
+ // Clamp against floating-point drift so the contract's [0,1] is exact.
90
+ value = value < 0 ? 0 : value > 1 ? 1 : value;
91
+ // Round to 1e-9 to eliminate residual FP drift ⇒ a byte-reproducible, audit-stable
92
+ // value for the same multiset. Coarse enough never to flip a band/threshold.
93
+ return Math.round(value * 1e9) / 1e9;
94
+ }
95
+ /**
96
+ * Map an aggregated `value` onto a coarse `RiskLevel` via the band cutoffs.
97
+ *
98
+ * ⛔ FAIL-SAFE BOUNDARY: a value exactly AT a cutoff maps to the HIGHER-risk band
99
+ * (`>=`), never rounding down into a calmer band. `high` at `>= highCutoff`;
100
+ * `medium` at `>= mediumCutoff`; else `low`.
101
+ */
102
+ function bandFor(value, thresholds) {
103
+ if (value >= thresholds.highCutoff)
104
+ return 'high';
105
+ if (value >= thresholds.mediumCutoff)
106
+ return 'medium';
107
+ return 'low';
108
+ }
109
+ /**
110
+ * Route one signal to its evaluator and score it. Selection is DETERMINISTIC:
111
+ * - an explicit `value.__evaluator` string names the evaluator to use;
112
+ * - otherwise the signal's `kind` is used as the default evaluator name lookup
113
+ * (the reference evaluators register under a name AND cover a kind — the engine
114
+ * falls back to a per-kind default registered by that convention).
115
+ *
116
+ * FAIL-SAFE: no evaluator found, a kind/evaluator mismatch, a non-number
117
+ * contribution, OR the evaluator THROWS (including a `.evaluate` that is not a
118
+ * function, or a throwing property getter on `signal.kind`/`.value`/`.__evaluator`)
119
+ * ⇒ the {@link UNEVALUABLE_CONTRIBUTION} elevation attributed to the signal's
120
+ * declared kind. Never throws, never drops.
121
+ *
122
+ * ⚠️ ATTRIBUTION OF UN-KINDED JUNK (by design): a signal whose `kind` is missing,
123
+ * non-string, or throws when read is attributed to `'context'` for the
124
+ * `contributingSignals` list. This is an ARBITRARY-but-stable bucket — the point is
125
+ * that the elevation is still explainable somewhere; there is no "unknown" kind in
126
+ * the frozen `RiskSignalKind` union to attribute it to.
127
+ */
128
+ function scoreSignal(signal, registry, defaultByKind) {
129
+ // Determine the signal's declared kind for attribution (fail-safe even if junk).
130
+ // Wrapped: reading `.kind` may itself THROW (a hostile getter) — that must NOT
131
+ // escape scoreSignal; it degrades to the 'context' bucket + a fail-safe elevate.
132
+ const declaredKind = safeDeclaredKind(signal);
133
+ try {
134
+ const bag = signal?.value;
135
+ const selector = typeof bag?.__evaluator === 'string' && bag.__evaluator.length > 0
136
+ ? bag.__evaluator
137
+ : undefined;
138
+ // Resolve: explicit selector wins; else the per-kind default evaluator.
139
+ const evaluator = (selector !== undefined ? registry.resolve(selector) : undefined) ??
140
+ defaultByKind.get(declaredKind);
141
+ // UNKNOWN signal — no evaluator for this kind/name ⇒ ELEVATE (never ignore).
142
+ // A resolved-but-malformed evaluator whose `.evaluate` is not callable is
143
+ // likewise treated as "cannot evaluate" ⇒ elevate (the call below would throw
144
+ // and be caught anyway; this makes the intent explicit and the path direct).
145
+ if (evaluator === undefined || typeof evaluator.evaluate !== 'function') {
146
+ return { contribution: UNEVALUABLE_CONTRIBUTION, kind: declaredKind };
147
+ }
148
+ const verdict = evaluator.evaluate(signal);
149
+ // STRICT: a well-formed verdict must carry a numeric contribution. A hostile /
150
+ // misbehaving evaluator returning a truthy non-number ⇒ fail-safe elevate
151
+ // (clampContribution maps a non-number to the fail-safe floor), NOT fail-open.
152
+ const contribution = (0, evaluator_js_1.clampContribution)(verdict?.contribution, UNEVALUABLE_CONTRIBUTION);
153
+ const kind = typeof verdict?.kind === 'string'
154
+ ? verdict.kind
155
+ : declaredKind;
156
+ return { contribution, kind };
157
+ }
158
+ catch {
159
+ // An evaluator THREW ⇒ uncertainty ⇒ ELEVATE (never lower / drop / rethrow).
160
+ return { contribution: UNEVALUABLE_CONTRIBUTION, kind: declaredKind };
161
+ }
162
+ }
163
+ /**
164
+ * Read a signal's declared `kind` for attribution WITHOUT ever throwing. A hostile
165
+ * signal can expose `kind` as a getter that throws — reading it must not escape.
166
+ * A missing / non-string / throwing kind degrades to the `'context'` bucket (see
167
+ * {@link scoreSignal}'s attribution note).
168
+ */
169
+ function safeDeclaredKind(signal) {
170
+ try {
171
+ if (signal !== null &&
172
+ typeof signal === 'object' &&
173
+ typeof signal.kind === 'string') {
174
+ return signal.kind;
175
+ }
176
+ }
177
+ catch {
178
+ // A throwing `kind` getter → fall through to the stable bucket.
179
+ }
180
+ return 'context';
181
+ }
182
+ /**
183
+ * The concrete engine. Stateless per call; holds only its injected capabilities.
184
+ * Instances come from {@link createRiskEngine}.
185
+ */
186
+ class RiskEngineImpl {
187
+ registry;
188
+ defaultByKind;
189
+ thresholds;
190
+ constructor(registry, defaultByKind, thresholds) {
191
+ this.registry = registry;
192
+ this.defaultByKind = defaultByKind;
193
+ this.thresholds = thresholds;
194
+ }
195
+ assess(_principal, signals) {
196
+ // NOTE: `_principal` is part of the FROZEN seam signature. Step-7 signals are
197
+ // computable from the RiskSignal facts alone; the principal is reserved for
198
+ // future principal-aware signals (e.g. role-weighted risk) — unused today.
199
+ try {
200
+ return Promise.resolve(this.doAssess(signals));
201
+ }
202
+ catch {
203
+ // FAIL-SAFE (not fail-open, not throw-to-deny): ANY unexpected throw ⇒ RESOLVE
204
+ // to a fail-safe HIGH score. Risk never throws in a way that acts as a deny.
205
+ return Promise.resolve(FAIL_SAFE_SCORE);
206
+ }
207
+ }
208
+ doAssess(signals) {
209
+ // No signals (or a non-array) ⇒ a genuine LOW score (0). Absence of signal is
210
+ // not uncertainty — there is simply nothing elevating. (An UNKNOWN signal, by
211
+ // contrast, IS uncertainty and elevates — see scoreSignal.)
212
+ const list = Array.isArray(signals) ? signals : [];
213
+ const contributions = [];
214
+ // Collect the DISTINCT kinds that pushed the score up, for explainability. A
215
+ // Set keeps this order-independent; we materialize it deterministically below.
216
+ const contributingKinds = new Set();
217
+ for (const signal of list) {
218
+ const { contribution, kind } = scoreSignal(signal, this.registry, this.defaultByKind);
219
+ contributions.push(contribution);
220
+ if (contribution > 0) {
221
+ contributingKinds.add(kind);
222
+ }
223
+ }
224
+ const value = combine(contributions);
225
+ const level = bandFor(value, this.thresholds);
226
+ // Deterministic ordering of the explainability list (canonical kind order),
227
+ // so the same inputs always yield an identical RiskScore.
228
+ const contributingSignals = CANONICAL_KIND_ORDER.filter((k) => contributingKinds.has(k));
229
+ return Object.freeze({
230
+ level,
231
+ value,
232
+ contributingSignals: Object.freeze(contributingSignals),
233
+ });
234
+ }
235
+ }
236
+ /** Canonical kind order for the deterministic `contributingSignals` list. */
237
+ const CANONICAL_KIND_ORDER = Object.freeze([
238
+ 'device',
239
+ 'behaviour',
240
+ 'context',
241
+ 'network',
242
+ ]);
243
+ /**
244
+ * Wire the injected capabilities and return an object implementing the FROZEN
245
+ * {@link RiskEngine}. The engine's public entry point (mirrors `createAuthenticator`
246
+ * / `createSessionAuthority`). Validates the threshold config eagerly at
247
+ * construction (throws LOUD on a nonsensical config — construction-time).
248
+ */
249
+ function createRiskEngine(options = {}) {
250
+ const thresholds = (0, thresholds_js_1.resolveThresholds)(options.thresholds);
251
+ const registry = new evaluator_js_1.RiskSignalEvaluatorRegistry();
252
+ const defaultByKind = new Map();
253
+ const evaluators = options.evaluators ?? signals_js_1.DEFAULT_RISK_EVALUATORS;
254
+ for (const evaluator of evaluators) {
255
+ registry.register(evaluator); // duplicate NAME → throws LOUD (fail-closed)
256
+ // First evaluator registered for a kind becomes that kind's default router
257
+ // target (a later one keeps its NAME-based selectability but not the default).
258
+ if (!defaultByKind.has(evaluator.kind)) {
259
+ defaultByKind.set(evaluator.kind, evaluator);
260
+ }
261
+ }
262
+ return new RiskEngineImpl(registry, defaultByKind, thresholds);
263
+ }
264
+ /**
265
+ * The ADR-0017 **step-up recommendation** — a SEPARATE, PURE derivation OVER a
266
+ * {@link RiskScore}. Returns `true` when the score's `level === 'high'` OR its
267
+ * `value >= stepUpThreshold`.
268
+ *
269
+ * ⛔ THIS IS ADVISORY, NOT ENFORCEMENT. It is NOT a field on the frozen `RiskScore`
270
+ * (which has no recommendation/stepUp field — semver, ADR-0023) and it takes NO
271
+ * action. A later layer (Auth performs `mfa_required`; the SDK does UX) READS this
272
+ * advice and decides. Risk never blocks/mints/denies.
273
+ *
274
+ * FAIL-SAFE: a malformed / missing score (null, non-object, non-number value) ⇒
275
+ * recommend step-up (`true`) — uncertainty advises HARDER, never silently `false`.
276
+ */
277
+ function recommendStepUp(score, config) {
278
+ const stepUpThreshold = typeof config?.stepUpThreshold === 'number' && Number.isFinite(config.stepUpThreshold)
279
+ ? config.stepUpThreshold
280
+ : thresholds_js_1.DEFAULT_RISK_THRESHOLDS.stepUpThreshold;
281
+ // Malformed score ⇒ fail-safe: recommend step-up.
282
+ if (score === null || typeof score !== 'object')
283
+ return true;
284
+ if (score.level === 'high')
285
+ return true;
286
+ const value = score.value;
287
+ if (typeof value !== 'number' || !Number.isFinite(value))
288
+ return true;
289
+ return value >= stepUpThreshold;
290
+ }
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ /**
3
+ * **Reference risk-signal evaluators** (Rule of Three — ADR-0023 §7). A minimal
4
+ * pair of PURE, ZERO-IO evaluators that exercise the {@link RiskSignalEvaluator}
5
+ * contract without standing up any speculative port:
6
+ *
7
+ * 1. `UNKNOWN_DEVICE_EVALUATOR` — a `'device'` signal whose value indicates the
8
+ * device is not in a KNOWN-LIST carried in the signal itself (no history / no
9
+ * IO). Unknown/new device ⇒ ELEVATES risk (ADR-0017 new/unknown-device trigger).
10
+ * 2. `SENSITIVE_ACTION_EVALUATOR` — a `'context'` signal the caller stamps
11
+ * (`value.sensitiveAction === true`) marking the request as a sensitive action
12
+ * ⇒ ELEVATES risk (ADR-0017 sensitive-action trigger).
13
+ *
14
+ * These two suffice to prove the contract + the aggregation + the fail-safe
15
+ * direction. The DEFERRED signals (impossible-travel / geo / behavioural / UEBA)
16
+ * need IO or history and are NOT built here — adding a speculative GeoLookup /
17
+ * threat-feed port for a signal that doesn't exist yet would violate Rule of Three
18
+ * AND the zero-dep invariant.
19
+ *
20
+ * ⛔ FAIL-SAFE: each evaluator ELEVATES on an ambiguous / malformed value bag
21
+ * (never returns a low score for "couldn't tell"), and NEVER throws. STRICT checks
22
+ * (`=== true`, explicit membership) — no truthiness fail-open.
23
+ *
24
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.DEFAULT_RISK_EVALUATORS = exports.SENSITIVE_ACTION_EVALUATOR = exports.UNKNOWN_DEVICE_EVALUATOR = exports.SENSITIVE_ACTION_EVALUATOR_NAME = exports.UNKNOWN_DEVICE_EVALUATOR_NAME = exports.FAIL_SAFE_CONTRIBUTION = void 0;
28
+ /**
29
+ * The contribution an ambiguous/malformed signal yields — a HIGH elevation, so
30
+ * "couldn't evaluate" always raises risk rather than lowering it. Chosen ≥ the
31
+ * default `highCutoff` (0.67) so an unreadable signal alone pushes toward the high
32
+ * band. NOT 1.0 — a genuinely-confirmed risk can still exceed it.
33
+ */
34
+ exports.FAIL_SAFE_CONTRIBUTION = 0.8;
35
+ /** The clear-risk contribution a positively-confirmed reference signal emits. */
36
+ const CONFIRMED_RISK_CONTRIBUTION = 0.7;
37
+ /** No-risk contribution — the signal is present and clearly benign. */
38
+ const NO_RISK_CONTRIBUTION = 0;
39
+ /** Names — the evaluator identities in the registry (also the per-kind default routing). */
40
+ exports.UNKNOWN_DEVICE_EVALUATOR_NAME = 'unknown_device';
41
+ exports.SENSITIVE_ACTION_EVALUATOR_NAME = 'sensitive_action';
42
+ /** Is `v` a readonly array of strings (a known-device list)? */
43
+ function isStringArray(v) {
44
+ return Array.isArray(v) && v.every((x) => typeof x === 'string');
45
+ }
46
+ /**
47
+ * `'device'`-kind evaluator. The signal carries `value.deviceId` (the current
48
+ * device's stable id) and `value.knownDeviceIds` (a list the CALLER supplies — no
49
+ * history lookup, no IO). If `deviceId` is present in `knownDeviceIds` ⇒ known ⇒ no
50
+ * risk. Otherwise ⇒ NEW/UNKNOWN device ⇒ elevate.
51
+ *
52
+ * FAIL-SAFE: a missing / non-string `deviceId`, or a missing / malformed
53
+ * `knownDeviceIds`, is treated as "cannot confirm the device is known" ⇒ ELEVATE
54
+ * (never assume known). STRICT membership check. Never throws.
55
+ */
56
+ exports.UNKNOWN_DEVICE_EVALUATOR = Object.freeze({
57
+ name: exports.UNKNOWN_DEVICE_EVALUATOR_NAME,
58
+ kind: 'device',
59
+ evaluate(signal) {
60
+ const bag = signal?.value;
61
+ const deviceId = bag?.deviceId;
62
+ const known = bag?.knownDeviceIds;
63
+ // Malformed / ambiguous bag → cannot confirm known → elevate (fail-safe).
64
+ if (typeof deviceId !== 'string' || deviceId.length === 0 || !isStringArray(known)) {
65
+ return Object.freeze({ contribution: exports.FAIL_SAFE_CONTRIBUTION, kind: 'device' });
66
+ }
67
+ // STRICT membership: only an exact match in the caller's known-list is "known".
68
+ const isKnown = known.includes(deviceId);
69
+ return Object.freeze({
70
+ contribution: isKnown ? NO_RISK_CONTRIBUTION : CONFIRMED_RISK_CONTRIBUTION,
71
+ kind: 'device',
72
+ });
73
+ },
74
+ });
75
+ /**
76
+ * `'context'`-kind evaluator. The caller stamps `value.sensitiveAction === true`
77
+ * when the request targets a sensitive action (ADR-0017). STRICT `=== true` ⇒
78
+ * elevate. An explicit `=== false` ⇒ no risk.
79
+ *
80
+ * FAIL-SAFE: a missing / non-boolean / truthy-non-boolean `sensitiveAction` is
81
+ * AMBIGUOUS — we do NOT treat "truthy" as confirmed (no fail-open) NOR "absent" as
82
+ * benign silently. Absent/non-boolean ⇒ we cannot tell ⇒ ELEVATE. Only an explicit
83
+ * boolean `false` is benign. Never throws.
84
+ */
85
+ exports.SENSITIVE_ACTION_EVALUATOR = Object.freeze({
86
+ name: exports.SENSITIVE_ACTION_EVALUATOR_NAME,
87
+ kind: 'context',
88
+ evaluate(signal) {
89
+ const flag = signal?.value
90
+ ?.sensitiveAction;
91
+ if (flag === true) {
92
+ return Object.freeze({ contribution: CONFIRMED_RISK_CONTRIBUTION, kind: 'context' });
93
+ }
94
+ if (flag === false) {
95
+ return Object.freeze({ contribution: NO_RISK_CONTRIBUTION, kind: 'context' });
96
+ }
97
+ // Absent / non-boolean / truthy-non-boolean → ambiguous → elevate (fail-safe,
98
+ // NOT fail-open: a truthy "yes-ish" is not accepted as a confirmed benign).
99
+ return Object.freeze({ contribution: exports.FAIL_SAFE_CONTRIBUTION, kind: 'context' });
100
+ },
101
+ });
102
+ /** The default reference evaluators the engine registers when none are supplied. */
103
+ exports.DEFAULT_RISK_EVALUATORS = Object.freeze([
104
+ exports.UNKNOWN_DEVICE_EVALUATOR,
105
+ exports.SENSITIVE_ACTION_EVALUATOR,
106
+ ]);
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /**
3
+ * **Risk threshold configuration** (ADR-0017 step-up trigger). The band cutoffs
4
+ * that map a normalized `RiskScore.value ∈ [0,1]` onto a coarse `RiskLevel`, plus
5
+ * the separate `stepUpThreshold` the advisory `recommendStepUp` derivation reads.
6
+ *
7
+ * All three values are runtime-configurable per deployment; the DEFAULTS below are
8
+ * conservative middle-of-the-road cutoffs. They are validated + frozen at
9
+ * CONSTRUCTION (`resolveThresholds`) — a nonsensical config throws LOUD at boot,
10
+ * never silently at `assess()` time (mirrors `resolveLifetimes`).
11
+ *
12
+ * ⛔ FAIL-SAFE BAND MAPPING (this layer's #1 rule leaning into the config): a value
13
+ * exactly AT a cutoff maps to the HIGHER-risk (safer-for-security) band. `medium`
14
+ * starts at `>= mediumCutoff`; `high` starts at `>= highCutoff`. A boundary never
15
+ * rounds DOWN into a calmer band. The mapping itself lives in `risk-engine.ts`;
16
+ * this file owns only the numbers + their bounds validation.
17
+ *
18
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.DEFAULT_RISK_THRESHOLDS = void 0;
22
+ exports.resolveThresholds = resolveThresholds;
23
+ /**
24
+ * Conservative deployment defaults: medium at 0.34, high at 0.67, step-up
25
+ * recommended at 0.67 (i.e. aligned with the high band). A deployment tightens or
26
+ * loosens these per its risk appetite.
27
+ */
28
+ exports.DEFAULT_RISK_THRESHOLDS = Object.freeze({
29
+ mediumCutoff: 0.34,
30
+ highCutoff: 0.67,
31
+ stepUpThreshold: 0.67,
32
+ });
33
+ /** A finite number within the closed unit interval `[0,1]`. */
34
+ function isUnitFraction(v) {
35
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
36
+ }
37
+ /**
38
+ * Validate + freeze a threshold config, applying {@link DEFAULT_RISK_THRESHOLDS}
39
+ * for any omitted field. Enforces:
40
+ *
41
+ * 0 ≤ mediumCutoff ≤ highCutoff ≤ 1 and 0 ≤ stepUpThreshold ≤ 1
42
+ *
43
+ * Throws LOUD on a nonsensical config — this is construction-time, not a hot path;
44
+ * a misconfiguration must fail the boot, never silently ship a broken banding.
45
+ */
46
+ function resolveThresholds(partial) {
47
+ const mediumCutoff = partial?.mediumCutoff ?? exports.DEFAULT_RISK_THRESHOLDS.mediumCutoff;
48
+ const highCutoff = partial?.highCutoff ?? exports.DEFAULT_RISK_THRESHOLDS.highCutoff;
49
+ const stepUpThreshold = partial?.stepUpThreshold ?? exports.DEFAULT_RISK_THRESHOLDS.stepUpThreshold;
50
+ if (!isUnitFraction(mediumCutoff)) {
51
+ throw new Error('RiskThresholdConfig: mediumCutoff must be a finite number in [0,1]');
52
+ }
53
+ if (!isUnitFraction(highCutoff)) {
54
+ throw new Error('RiskThresholdConfig: highCutoff must be a finite number in [0,1]');
55
+ }
56
+ if (!isUnitFraction(stepUpThreshold)) {
57
+ throw new Error('RiskThresholdConfig: stepUpThreshold must be a finite number in [0,1]');
58
+ }
59
+ if (mediumCutoff > highCutoff) {
60
+ throw new Error('RiskThresholdConfig: mediumCutoff must be ≤ highCutoff (bands must ascend)');
61
+ }
62
+ return Object.freeze({ mediumCutoff, highCutoff, stepUpThreshold });
63
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ /**
3
+ * Engine seam: **Session** — establishes/rotates/revokes the session.
4
+ *
5
+ * Two-tier storage (ADR-0013): durable session + refresh-token records live in
6
+ * MariaDB (lifecycle events only); the hot per-request session state + cached
7
+ * authorization facts live in Redis. This seam names the lifecycle contract only;
8
+ * the storage tiers, rotation, and fail-closed lookup are a later layer.
9
+ *
10
+ * TYPES / INTERFACES ONLY. ADR-0003: framework-agnostic.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
24
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ // --- Engine implementation behind the FROZEN seam above (this layer) ----------
28
+ // The storage/crypto/clock PORTs (concrete MariaDB/Redis/node:crypto adapters
29
+ // ship in @astram/guard — Core stays zero-dep):
30
+ __exportStar(require("./ports.js"), exports);
31
+ // The lifetime config + ADR-0015 defaults + bounds validation:
32
+ __exportStar(require("./lifetimes.js"), exports);
33
+ // The Session engine (establish/rotate-with-reuse-detection/revoke) + the
34
+ // per-request hot-read path + the `createSessionAuthority` factory:
35
+ __exportStar(require("./session-authority.js"), exports);
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * **Session & token lifetime configuration** (ADR-0015). All three values are
4
+ * runtime-configurable per deployment; the DEFAULTS below match the ADR:
5
+ *
6
+ * - access token: **15 minutes**
7
+ * - refresh token: sliding **14-day idle** window
8
+ * - refresh token: **60-day absolute cap** (max session age regardless of activity)
9
+ *
10
+ * The idle window and the absolute cap are DISTINCT and independently enforced
11
+ * (ADR-0015): a session dies at the earlier of (last-refresh + idle) and
12
+ * (login + absolute-cap). Rotation-on-use + reuse-detection are the engine's job
13
+ * (`./session-authority.ts`); this file owns only the numeric config + its bounds
14
+ * validation.
15
+ *
16
+ * ⛔ SCOPE: this ships the DEPLOYMENT-DEFAULT config. Per-tenant override
17
+ * RESOLUTION (tenant policy → deployment default precedence, ADR-0015) is a later
18
+ * concern; a caller may construct a different {@link SessionLifetimeConfig} per
19
+ * tenant and hand it to a per-tenant authority, but this layer does not resolve
20
+ * tenant policy.
21
+ *
22
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.DEFAULT_SESSION_LIFETIMES = void 0;
26
+ exports.resolveLifetimes = resolveLifetimes;
27
+ /** Milliseconds in one minute / day (local, node-free constants). */
28
+ const MINUTE_MS = 60_000;
29
+ const DAY_MS = 24 * 60 * MINUTE_MS;
30
+ /** The ADR-0015 documented defaults (15 min / 14 d idle / 60 d cap). */
31
+ exports.DEFAULT_SESSION_LIFETIMES = Object.freeze({
32
+ accessTtlMs: 15 * MINUTE_MS,
33
+ refreshIdleMs: 14 * DAY_MS,
34
+ refreshAbsoluteCapMs: 60 * DAY_MS,
35
+ });
36
+ /** A finite, strictly-positive integer millisecond duration. */
37
+ function isPositiveDuration(v) {
38
+ return typeof v === 'number' && Number.isFinite(v) && v > 0;
39
+ }
40
+ /**
41
+ * Validate + freeze a lifetime config, applying ADR-0015 defaults for any omitted
42
+ * field. Enforces the sane-bounds invariant from ADR-0015 ("access TTL not longer
43
+ * than the refresh idle window") extended to the full chain:
44
+ *
45
+ * 0 < accessTtlMs ≤ refreshIdleMs ≤ refreshAbsoluteCapMs
46
+ *
47
+ * Throws LOUD on a nonsensical config (this is construction-time, not a hot path —
48
+ * a misconfiguration must fail the boot, never silently ship a broken policy).
49
+ */
50
+ function resolveLifetimes(partial) {
51
+ const accessTtlMs = partial?.accessTtlMs ?? exports.DEFAULT_SESSION_LIFETIMES.accessTtlMs;
52
+ const refreshIdleMs = partial?.refreshIdleMs ?? exports.DEFAULT_SESSION_LIFETIMES.refreshIdleMs;
53
+ const refreshAbsoluteCapMs = partial?.refreshAbsoluteCapMs ?? exports.DEFAULT_SESSION_LIFETIMES.refreshAbsoluteCapMs;
54
+ if (!isPositiveDuration(accessTtlMs)) {
55
+ throw new Error('SessionLifetimeConfig: accessTtlMs must be a positive, finite number of ms');
56
+ }
57
+ if (!isPositiveDuration(refreshIdleMs)) {
58
+ throw new Error('SessionLifetimeConfig: refreshIdleMs must be a positive, finite number of ms');
59
+ }
60
+ if (!isPositiveDuration(refreshAbsoluteCapMs)) {
61
+ throw new Error('SessionLifetimeConfig: refreshAbsoluteCapMs must be a positive, finite number of ms');
62
+ }
63
+ if (accessTtlMs > refreshIdleMs) {
64
+ throw new Error('SessionLifetimeConfig: accessTtlMs must be ≤ refreshIdleMs (ADR-0015 sane-bounds)');
65
+ }
66
+ if (refreshIdleMs > refreshAbsoluteCapMs) {
67
+ throw new Error('SessionLifetimeConfig: refreshIdleMs must be ≤ refreshAbsoluteCapMs (ADR-0015 sane-bounds)');
68
+ }
69
+ return Object.freeze({ accessTtlMs, refreshIdleMs, refreshAbsoluteCapMs });
70
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * The Session engine **PORTS** — the framework-agnostic contracts the
4
+ * SessionAuthority engine (`./session-authority.ts`) uses to reach the two
5
+ * storage tiers (ADR-0013), mint/hash tokens, and read the clock, WITHOUT the
6
+ * engine ever knowing which DB / cache / crypto backs them.
7
+ *
8
+ * ADR-0003 (zero-dep Core): every concrete adapter (MariaDB, Redis, node:crypto)
9
+ * is a real runtime dependency and CANNOT live here. The Core defines only these
10
+ * interfaces; `@astram/guard` ships the concretes and INJECTS them into
11
+ * `createSessionAuthority(...)`. This keeps `@astram/core` at ZERO runtime
12
+ * dependencies (the load-bearing invariant) while the substrate stays swappable.
13
+ *
14
+ * ⛔ SECURITY — the engine NEVER logs a token and NEVER stores a RAW refresh
15
+ * token. A refresh token is stored ONLY as its keyed hash (via
16
+ * {@link RefreshTokenHasher}); the durable {@link SessionRecordStore} therefore
17
+ * only ever receives a HASH. No port method returns a raw token except the one
18
+ * mint operation ({@link TokenGenerator.mint}); the raw refresh token leaves the
19
+ * engine EXACTLY ONCE, in the establishment result, never persisted.
20
+ *
21
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });