@astram/core 0.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 (259) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -0
  3. package/dist/admin/admin-service.d.ts +221 -0
  4. package/dist/admin/admin-service.d.ts.map +1 -0
  5. package/dist/admin/admin-service.js +155 -0
  6. package/dist/admin/admin-service.js.map +1 -0
  7. package/dist/admin/command/grants.d.ts +40 -0
  8. package/dist/admin/command/grants.d.ts.map +1 -0
  9. package/dist/admin/command/grants.js +196 -0
  10. package/dist/admin/command/grants.js.map +1 -0
  11. package/dist/admin/command/index.d.ts +23 -0
  12. package/dist/admin/command/index.d.ts.map +1 -0
  13. package/dist/admin/command/index.js +23 -0
  14. package/dist/admin/command/index.js.map +1 -0
  15. package/dist/admin/command/invitations.d.ts +72 -0
  16. package/dist/admin/command/invitations.d.ts.map +1 -0
  17. package/dist/admin/command/invitations.js +241 -0
  18. package/dist/admin/command/invitations.js.map +1 -0
  19. package/dist/admin/command/permissions.d.ts +33 -0
  20. package/dist/admin/command/permissions.d.ts.map +1 -0
  21. package/dist/admin/command/permissions.js +67 -0
  22. package/dist/admin/command/permissions.js.map +1 -0
  23. package/dist/admin/command/pipeline.d.ts +79 -0
  24. package/dist/admin/command/pipeline.d.ts.map +1 -0
  25. package/dist/admin/command/pipeline.js +106 -0
  26. package/dist/admin/command/pipeline.js.map +1 -0
  27. package/dist/admin/command/policies.d.ts +50 -0
  28. package/dist/admin/command/policies.d.ts.map +1 -0
  29. package/dist/admin/command/policies.js +219 -0
  30. package/dist/admin/command/policies.js.map +1 -0
  31. package/dist/admin/command/service-accounts.d.ts +58 -0
  32. package/dist/admin/command/service-accounts.d.ts.map +1 -0
  33. package/dist/admin/command/service-accounts.js +272 -0
  34. package/dist/admin/command/service-accounts.js.map +1 -0
  35. package/dist/admin/command/service.d.ts +65 -0
  36. package/dist/admin/command/service.d.ts.map +1 -0
  37. package/dist/admin/command/service.js +128 -0
  38. package/dist/admin/command/service.js.map +1 -0
  39. package/dist/admin/command/tiers.d.ts +40 -0
  40. package/dist/admin/command/tiers.d.ts.map +1 -0
  41. package/dist/admin/command/tiers.js +79 -0
  42. package/dist/admin/command/tiers.js.map +1 -0
  43. package/dist/admin/index.d.ts +36 -0
  44. package/dist/admin/index.d.ts.map +1 -0
  45. package/dist/admin/index.js +63 -0
  46. package/dist/admin/index.js.map +1 -0
  47. package/dist/admin/ports.d.ts +288 -0
  48. package/dist/admin/ports.d.ts.map +1 -0
  49. package/dist/admin/ports.js +39 -0
  50. package/dist/admin/ports.js.map +1 -0
  51. package/dist/admin/query/audit-view.d.ts +52 -0
  52. package/dist/admin/query/audit-view.d.ts.map +1 -0
  53. package/dist/admin/query/audit-view.js +84 -0
  54. package/dist/admin/query/audit-view.js.map +1 -0
  55. package/dist/admin/query/catalog.d.ts +70 -0
  56. package/dist/admin/query/catalog.d.ts.map +1 -0
  57. package/dist/admin/query/catalog.js +169 -0
  58. package/dist/admin/query/catalog.js.map +1 -0
  59. package/dist/admin/query/explain.d.ts +52 -0
  60. package/dist/admin/query/explain.d.ts.map +1 -0
  61. package/dist/admin/query/explain.js +145 -0
  62. package/dist/admin/query/explain.js.map +1 -0
  63. package/dist/admin/query/index.d.ts +45 -0
  64. package/dist/admin/query/index.d.ts.map +1 -0
  65. package/dist/admin/query/index.js +58 -0
  66. package/dist/admin/query/index.js.map +1 -0
  67. package/dist/admin/query/simulate.d.ts +42 -0
  68. package/dist/admin/query/simulate.d.ts.map +1 -0
  69. package/dist/admin/query/simulate.js +91 -0
  70. package/dist/admin/query/simulate.js.map +1 -0
  71. package/dist/admin/safeguards-impl.d.ts +67 -0
  72. package/dist/admin/safeguards-impl.d.ts.map +1 -0
  73. package/dist/admin/safeguards-impl.js +318 -0
  74. package/dist/admin/safeguards-impl.js.map +1 -0
  75. package/dist/admin/safeguards.d.ts +89 -0
  76. package/dist/admin/safeguards.d.ts.map +1 -0
  77. package/dist/admin/safeguards.js +91 -0
  78. package/dist/admin/safeguards.js.map +1 -0
  79. package/dist/admin/types.d.ts +485 -0
  80. package/dist/admin/types.d.ts.map +1 -0
  81. package/dist/admin/types.js +38 -0
  82. package/dist/admin/types.js.map +1 -0
  83. package/dist/audit/audit-recorder.d.ts +129 -0
  84. package/dist/audit/audit-recorder.d.ts.map +1 -0
  85. package/dist/audit/audit-recorder.js +265 -0
  86. package/dist/audit/audit-recorder.js.map +1 -0
  87. package/dist/audit/canonicalize.d.ts +38 -0
  88. package/dist/audit/canonicalize.d.ts.map +1 -0
  89. package/dist/audit/canonicalize.js +174 -0
  90. package/dist/audit/canonicalize.js.map +1 -0
  91. package/dist/audit/errors.d.ts +56 -0
  92. package/dist/audit/errors.d.ts.map +1 -0
  93. package/dist/audit/errors.js +41 -0
  94. package/dist/audit/errors.js.map +1 -0
  95. package/dist/audit/index.d.ts +45 -0
  96. package/dist/audit/index.d.ts.map +1 -0
  97. package/dist/audit/index.js +24 -0
  98. package/dist/audit/index.js.map +1 -0
  99. package/dist/audit/ports.d.ts +131 -0
  100. package/dist/audit/ports.d.ts.map +1 -0
  101. package/dist/audit/ports.js +27 -0
  102. package/dist/audit/ports.js.map +1 -0
  103. package/dist/audit/sensitive.d.ts +68 -0
  104. package/dist/audit/sensitive.d.ts.map +1 -0
  105. package/dist/audit/sensitive.js +159 -0
  106. package/dist/audit/sensitive.js.map +1 -0
  107. package/dist/audit/walk.d.ts +109 -0
  108. package/dist/audit/walk.d.ts.map +1 -0
  109. package/dist/audit/walk.js +117 -0
  110. package/dist/audit/walk.js.map +1 -0
  111. package/dist/authentication/authenticator.d.ts +74 -0
  112. package/dist/authentication/authenticator.d.ts.map +1 -0
  113. package/dist/authentication/authenticator.js +208 -0
  114. package/dist/authentication/authenticator.js.map +1 -0
  115. package/dist/authentication/credential-resolver.d.ts +76 -0
  116. package/dist/authentication/credential-resolver.d.ts.map +1 -0
  117. package/dist/authentication/credential-resolver.js +21 -0
  118. package/dist/authentication/credential-resolver.js.map +1 -0
  119. package/dist/authentication/index.d.ts +52 -0
  120. package/dist/authentication/index.d.ts.map +1 -0
  121. package/dist/authentication/index.js +27 -0
  122. package/dist/authentication/index.js.map +1 -0
  123. package/dist/authentication/password-hasher.d.ts +41 -0
  124. package/dist/authentication/password-hasher.d.ts.map +1 -0
  125. package/dist/authentication/password-hasher.js +21 -0
  126. package/dist/authentication/password-hasher.js.map +1 -0
  127. package/dist/authentication/totp.d.ts +101 -0
  128. package/dist/authentication/totp.d.ts.map +1 -0
  129. package/dist/authentication/totp.js +151 -0
  130. package/dist/authentication/totp.js.map +1 -0
  131. package/dist/authorization/cross-tenant/grant-evaluator.d.ts +90 -0
  132. package/dist/authorization/cross-tenant/grant-evaluator.d.ts.map +1 -0
  133. package/dist/authorization/cross-tenant/grant-evaluator.js +165 -0
  134. package/dist/authorization/cross-tenant/grant-evaluator.js.map +1 -0
  135. package/dist/authorization/decision-authority.d.ts +212 -0
  136. package/dist/authorization/decision-authority.d.ts.map +1 -0
  137. package/dist/authorization/decision-authority.js +200 -0
  138. package/dist/authorization/decision-authority.js.map +1 -0
  139. package/dist/authorization/default-gates.d.ts +41 -0
  140. package/dist/authorization/default-gates.d.ts.map +1 -0
  141. package/dist/authorization/default-gates.js +47 -0
  142. package/dist/authorization/default-gates.js.map +1 -0
  143. package/dist/authorization/delegation/operation-identity.d.ts +132 -0
  144. package/dist/authorization/delegation/operation-identity.d.ts.map +1 -0
  145. package/dist/authorization/delegation/operation-identity.js +220 -0
  146. package/dist/authorization/delegation/operation-identity.js.map +1 -0
  147. package/dist/authorization/errors.d.ts +54 -0
  148. package/dist/authorization/errors.d.ts.map +1 -0
  149. package/dist/authorization/errors.js +63 -0
  150. package/dist/authorization/errors.js.map +1 -0
  151. package/dist/authorization/gates/object-type.d.ts +63 -0
  152. package/dist/authorization/gates/object-type.d.ts.map +1 -0
  153. package/dist/authorization/gates/object-type.js +177 -0
  154. package/dist/authorization/gates/object-type.js.map +1 -0
  155. package/dist/authorization/gates/tenant.d.ts +50 -0
  156. package/dist/authorization/gates/tenant.d.ts.map +1 -0
  157. package/dist/authorization/gates/tenant.js +87 -0
  158. package/dist/authorization/gates/tenant.js.map +1 -0
  159. package/dist/authorization/gates/wiring.d.ts +57 -0
  160. package/dist/authorization/gates/wiring.d.ts.map +1 -0
  161. package/dist/authorization/gates/wiring.js +56 -0
  162. package/dist/authorization/gates/wiring.js.map +1 -0
  163. package/dist/authorization/index.d.ts +136 -0
  164. package/dist/authorization/index.d.ts.map +1 -0
  165. package/dist/authorization/index.js +82 -0
  166. package/dist/authorization/index.js.map +1 -0
  167. package/dist/authorization/ports.d.ts +271 -0
  168. package/dist/authorization/ports.d.ts.map +1 -0
  169. package/dist/authorization/ports.js +36 -0
  170. package/dist/authorization/ports.js.map +1 -0
  171. package/dist/authorization/reason-codes.d.ts +75 -0
  172. package/dist/authorization/reason-codes.d.ts.map +1 -0
  173. package/dist/authorization/reason-codes.js +98 -0
  174. package/dist/authorization/reason-codes.js.map +1 -0
  175. package/dist/authorization/record/permit-tier.d.ts +57 -0
  176. package/dist/authorization/record/permit-tier.d.ts.map +1 -0
  177. package/dist/authorization/record/permit-tier.js +79 -0
  178. package/dist/authorization/record/permit-tier.js.map +1 -0
  179. package/dist/authorization/record/rule-evaluator.d.ts +116 -0
  180. package/dist/authorization/record/rule-evaluator.d.ts.map +1 -0
  181. package/dist/authorization/record/rule-evaluator.js +125 -0
  182. package/dist/authorization/record/rule-evaluator.js.map +1 -0
  183. package/dist/authorization/record/shares.d.ts +70 -0
  184. package/dist/authorization/record/shares.d.ts.map +1 -0
  185. package/dist/authorization/record/shares.js +107 -0
  186. package/dist/authorization/record/shares.js.map +1 -0
  187. package/dist/identity/broker.d.ts +59 -0
  188. package/dist/identity/broker.d.ts.map +1 -0
  189. package/dist/identity/broker.js +135 -0
  190. package/dist/identity/broker.js.map +1 -0
  191. package/dist/identity/claim-mapper.d.ts +84 -0
  192. package/dist/identity/claim-mapper.d.ts.map +1 -0
  193. package/dist/identity/claim-mapper.js +48 -0
  194. package/dist/identity/claim-mapper.js.map +1 -0
  195. package/dist/identity/index.d.ts +60 -0
  196. package/dist/identity/index.d.ts.map +1 -0
  197. package/dist/identity/index.js +24 -0
  198. package/dist/identity/index.js.map +1 -0
  199. package/dist/identity/internal-adapter.d.ts +54 -0
  200. package/dist/identity/internal-adapter.d.ts.map +1 -0
  201. package/dist/identity/internal-adapter.js +88 -0
  202. package/dist/identity/internal-adapter.js.map +1 -0
  203. package/dist/index.d.ts +43 -0
  204. package/dist/index.d.ts.map +1 -0
  205. package/dist/index.js +48 -0
  206. package/dist/index.js.map +1 -0
  207. package/dist/metadata/completeness.d.ts +136 -0
  208. package/dist/metadata/completeness.d.ts.map +1 -0
  209. package/dist/metadata/completeness.js +106 -0
  210. package/dist/metadata/completeness.js.map +1 -0
  211. package/dist/metadata/dependencies.d.ts +114 -0
  212. package/dist/metadata/dependencies.d.ts.map +1 -0
  213. package/dist/metadata/dependencies.js +105 -0
  214. package/dist/metadata/dependencies.js.map +1 -0
  215. package/dist/metadata/index.d.ts +153 -0
  216. package/dist/metadata/index.d.ts.map +1 -0
  217. package/dist/metadata/index.js +51 -0
  218. package/dist/metadata/index.js.map +1 -0
  219. package/dist/metadata/registry.d.ts +23 -0
  220. package/dist/metadata/registry.d.ts.map +1 -0
  221. package/dist/metadata/registry.js +204 -0
  222. package/dist/metadata/registry.js.map +1 -0
  223. package/dist/risk/evaluator.d.ts +76 -0
  224. package/dist/risk/evaluator.d.ts.map +1 -0
  225. package/dist/risk/evaluator.js +59 -0
  226. package/dist/risk/evaluator.js.map +1 -0
  227. package/dist/risk/index.d.ts +40 -0
  228. package/dist/risk/index.d.ts.map +1 -0
  229. package/dist/risk/index.js +20 -0
  230. package/dist/risk/index.js.map +1 -0
  231. package/dist/risk/risk-engine.d.ts +76 -0
  232. package/dist/risk/risk-engine.d.ts.map +1 -0
  233. package/dist/risk/risk-engine.js +287 -0
  234. package/dist/risk/risk-engine.js.map +1 -0
  235. package/dist/risk/signals.d.ts +60 -0
  236. package/dist/risk/signals.d.ts.map +1 -0
  237. package/dist/risk/signals.js +104 -0
  238. package/dist/risk/signals.js.map +1 -0
  239. package/dist/risk/thresholds.d.ts +54 -0
  240. package/dist/risk/thresholds.d.ts.map +1 -0
  241. package/dist/risk/thresholds.js +60 -0
  242. package/dist/risk/thresholds.js.map +1 -0
  243. package/dist/session/index.d.ts +47 -0
  244. package/dist/session/index.d.ts.map +1 -0
  245. package/dist/session/index.js +20 -0
  246. package/dist/session/index.js.map +1 -0
  247. package/dist/session/lifetimes.d.ts +50 -0
  248. package/dist/session/lifetimes.d.ts.map +1 -0
  249. package/dist/session/lifetimes.js +67 -0
  250. package/dist/session/lifetimes.js.map +1 -0
  251. package/dist/session/ports.d.ts +266 -0
  252. package/dist/session/ports.d.ts.map +1 -0
  253. package/dist/session/ports.js +23 -0
  254. package/dist/session/ports.js.map +1 -0
  255. package/dist/session/session-authority.d.ts +97 -0
  256. package/dist/session/session-authority.d.ts.map +1 -0
  257. package/dist/session/session-authority.js +393 -0
  258. package/dist/session/session-authority.js.map +1 -0
  259. package/package.json +32 -0
@@ -0,0 +1,109 @@
1
+ /**
2
+ * **Shared structural-walk primitives** — the SINGLE SOURCE OF TRUTH for "which
3
+ * objects are descended" and "how a special leaf is tagged", used by BOTH the
4
+ * secret stripper (`./sensitive.ts`) and the canonical serializer
5
+ * (`./canonicalize.ts`).
6
+ *
7
+ * ── WHY THIS MODULE EXISTS (round-2 rulings A/B/C/D).
8
+ * The two walkers previously disagreed on their descend-set: the stripper
9
+ * descended only `Object.getPrototypeOf(v) === Object.prototype` objects, while
10
+ * the canonicalizer serialized-and-hashed ANY `typeof 'object'`. Wherever they
11
+ * disagreed, a secret on a class-instance / null-proto object was HASHED + STORED
12
+ * but NOT STRIPPED → a secret leaked (Defects A, B). Centralizing the descend-set
13
+ * predicate here — and having BOTH walkers import it — makes the two walkers
14
+ * descend the EXACT same objects by construction, so that bug class cannot recur.
15
+ *
16
+ * ── WHAT LIVES HERE.
17
+ * 1. {@link isDescendableObject} — the one predicate both walkers use to decide
18
+ * "recurse into this value's own keys?" (non-null, `typeof 'object'`, NOT an
19
+ * array, NOT a type-tagged special leaf like `Date`) — REGARDLESS of prototype.
20
+ * 2. {@link isSpecialLeaf} / {@link specialLeafTag} — the collision-free
21
+ * STRUCTURAL tag for a normalized special value (`Date`, `-0`, `NaN`,
22
+ * `±Infinity`). A structural object shape `{__shieldType,v}` — which a plain
23
+ * string can NEVER serialize to — replaces the old string-prefix tags
24
+ * (`"date:0"`), closing the plain-string collision (Defect D).
25
+ * 3. {@link SHIELD_MAX_DEPTH} + {@link throwOnCycle} helpers backing the shared
26
+ * visited-`WeakSet` / depth guard both walkers carry, so a cyclic /
27
+ * pathologically-deep attribute graph throws a TYPED
28
+ * `AuditValidationError('cyclic_attribute')` rather than an untyped
29
+ * `RangeError` mid-hash (Defect C).
30
+ *
31
+ * PURE — no I/O, no state, no clock. ADR-0003: framework-agnostic — no framework /
32
+ * HTTP / DB / node imports.
33
+ */
34
+ /**
35
+ * A structural type tag for a NORMALIZED special leaf value. Emitted as a distinct
36
+ * object SHAPE `{ __shieldType, v }`, never a string prefix — a plain string value
37
+ * can only ever serialize as a JSON string, so it can NEVER collide with this
38
+ * object form (closes Defect D: `new Date(0)` vs the plain string `"date:0"`).
39
+ *
40
+ * `kind` names the normalized type; `v` is the canonical scalar payload:
41
+ * - `date` → the epoch ms as a decimal string, or `'null'` for an invalid Date.
42
+ * Both walkers treat a special leaf as a LEAF (never descended) and tag it
43
+ * identically, so the descend-set stays in lock-step.
44
+ *
45
+ * ⛔ SCOPE: this structural tag exists to close the Date-vs-plain-string collision
46
+ * (round-2 Finding D). Numeric normalization (`NaN`/`±Infinity` → the bare `null`
47
+ * token, `-0` → `0`) is NOT a structural tag — those produce bare JSON tokens that a
48
+ * plain string can never equal (a caller string `"null"`/`"0"` JSON-encodes to the
49
+ * QUOTED `"null"`/`"0"`, distinct from the bare token), so they need no structural
50
+ * form and stay as the canonicalizer's inline number handling.
51
+ */
52
+ export interface ShieldTypeTag {
53
+ readonly __shieldType: 'date';
54
+ readonly v: string;
55
+ }
56
+ /**
57
+ * The maximum structural depth either walker will descend before treating the graph
58
+ * as pathological. Chosen well above any realistic audit attribute bag; a legitimate
59
+ * event's attributes are shallow. Hitting this cap almost always means a cycle the
60
+ * `WeakSet` didn't catch (e.g. a non-cyclic but exponentially deep graph) — either
61
+ * way it is REJECTED with a typed error, never allowed to overflow the stack.
62
+ */
63
+ export declare const SHIELD_MAX_DEPTH = 256;
64
+ /**
65
+ * Whether `value` is one of the type-tagged SPECIAL LEAVES both walkers normalize
66
+ * in place (never descend into). Today: a `Date`. A special leaf is NOT descendable
67
+ * (it is a leaf), so this is the exclusion consulted by {@link isDescendableObject}.
68
+ */
69
+ export declare function isSpecialLeaf(value: unknown): boolean;
70
+ /**
71
+ * The SINGLE descend-set predicate — the one place that answers "should a walker
72
+ * recurse into this value's own enumerable keys?". Both `stripValue` and
73
+ * `canonicalizeValue` call THIS, so they descend the EXACT same objects (closes
74
+ * Defects A + B — a null-proto or class-instance object is descended by BOTH,
75
+ * regardless of prototype).
76
+ *
77
+ * TRUE for: a non-null value that is `typeof 'object'`, is NOT an array (arrays are
78
+ * handled by their own element-walk in both walkers), and is NOT a type-tagged
79
+ * special leaf ({@link isSpecialLeaf}). Prototype is IRRELEVANT — a
80
+ * `Object.create(null)` bag and a `class Foo {}` instance both qualify.
81
+ */
82
+ export declare function isDescendableObject(value: unknown): value is object;
83
+ /**
84
+ * Compute the collision-free structural tag for a `Date` leaf, or `undefined` for
85
+ * any non-Date value.
86
+ *
87
+ * - `Date` → `{ __shieldType:'date', v:<epoch-ms|'null' for an invalid Date> }`.
88
+ *
89
+ * Returning a structural OBJECT (not a `"date:<ms>"` string prefix) is what makes a
90
+ * plain string value unable to collide with a tagged Date: the plain string
91
+ * `"date:0"` JSON-encodes to the string `"date:0"`, which can never equal the object
92
+ * form (closes round-2 Finding D). Numbers are NOT handled here — the canonicalizer
93
+ * normalizes `NaN`/`±Infinity`/`-0` inline to bare JSON tokens (see its scope note).
94
+ */
95
+ export declare function specialLeafTag(value: unknown): ShieldTypeTag | undefined;
96
+ /**
97
+ * A shared cycle/over-depth guard for the two structural walkers. Each walker,
98
+ * before descending an object/array, calls this with its live visited-`WeakSet` and
99
+ * current depth. On a detected cycle (the value is already on the current descent
100
+ * path) OR an over-depth graph, it throws a TYPED
101
+ * `AuditValidationError('cyclic_attribute')` — NEVER an untyped `RangeError`
102
+ * mid-hash (closes Defect C). Returns silently when it is safe to descend.
103
+ *
104
+ * The caller is responsible for `visited.add(value)` before recursing into its
105
+ * children and `visited.delete(value)` after — so a value legitimately reachable by
106
+ * two SIBLING paths (a shared, non-cyclic sub-object) is NOT mis-flagged as a cycle.
107
+ */
108
+ export declare function guardDescent(value: object, visited: WeakSet<object>, depth: number): void;
109
+ //# sourceMappingURL=walk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walk.d.ts","sourceRoot":"","sources":["../../src/audit/walk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAIH;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;CACpB;AAYD;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAErD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAOnE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,GAAG,SAAS,CAMxE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAOzF"}
@@ -0,0 +1,117 @@
1
+ /**
2
+ * **Shared structural-walk primitives** — the SINGLE SOURCE OF TRUTH for "which
3
+ * objects are descended" and "how a special leaf is tagged", used by BOTH the
4
+ * secret stripper (`./sensitive.ts`) and the canonical serializer
5
+ * (`./canonicalize.ts`).
6
+ *
7
+ * ── WHY THIS MODULE EXISTS (round-2 rulings A/B/C/D).
8
+ * The two walkers previously disagreed on their descend-set: the stripper
9
+ * descended only `Object.getPrototypeOf(v) === Object.prototype` objects, while
10
+ * the canonicalizer serialized-and-hashed ANY `typeof 'object'`. Wherever they
11
+ * disagreed, a secret on a class-instance / null-proto object was HASHED + STORED
12
+ * but NOT STRIPPED → a secret leaked (Defects A, B). Centralizing the descend-set
13
+ * predicate here — and having BOTH walkers import it — makes the two walkers
14
+ * descend the EXACT same objects by construction, so that bug class cannot recur.
15
+ *
16
+ * ── WHAT LIVES HERE.
17
+ * 1. {@link isDescendableObject} — the one predicate both walkers use to decide
18
+ * "recurse into this value's own keys?" (non-null, `typeof 'object'`, NOT an
19
+ * array, NOT a type-tagged special leaf like `Date`) — REGARDLESS of prototype.
20
+ * 2. {@link isSpecialLeaf} / {@link specialLeafTag} — the collision-free
21
+ * STRUCTURAL tag for a normalized special value (`Date`, `-0`, `NaN`,
22
+ * `±Infinity`). A structural object shape `{__shieldType,v}` — which a plain
23
+ * string can NEVER serialize to — replaces the old string-prefix tags
24
+ * (`"date:0"`), closing the plain-string collision (Defect D).
25
+ * 3. {@link SHIELD_MAX_DEPTH} + {@link throwOnCycle} helpers backing the shared
26
+ * visited-`WeakSet` / depth guard both walkers carry, so a cyclic /
27
+ * pathologically-deep attribute graph throws a TYPED
28
+ * `AuditValidationError('cyclic_attribute')` rather than an untyped
29
+ * `RangeError` mid-hash (Defect C).
30
+ *
31
+ * PURE — no I/O, no state, no clock. ADR-0003: framework-agnostic — no framework /
32
+ * HTTP / DB / node imports.
33
+ */
34
+ import { AuditValidationError } from './errors.js';
35
+ // NOTE: a plain caller attribute bag could, in principle, contain a literal
36
+ // `__shieldType` key. That is harmless — it is a plain STRING-keyed object,
37
+ // descended/serialized as an ordinary object (its value string is JSON-encoded),
38
+ // and the `date` tag is ONLY ever produced for a genuine `Date` leaf, never for a
39
+ // plain object, so a caller-supplied `{__shieldType:'date',v:'0'}` and a real
40
+ // `new Date(0)` still differ: the Date's `v` is a decimal-ms string tag emitted for
41
+ // a Date instance specifically, and the two are not required to be distinguishable
42
+ // (a caller crafting that exact object is choosing that value) — what matters is a
43
+ // plain STRING can never reach the tag's OBJECT form, which is the collision closed.
44
+ /**
45
+ * The maximum structural depth either walker will descend before treating the graph
46
+ * as pathological. Chosen well above any realistic audit attribute bag; a legitimate
47
+ * event's attributes are shallow. Hitting this cap almost always means a cycle the
48
+ * `WeakSet` didn't catch (e.g. a non-cyclic but exponentially deep graph) — either
49
+ * way it is REJECTED with a typed error, never allowed to overflow the stack.
50
+ */
51
+ export const SHIELD_MAX_DEPTH = 256;
52
+ /**
53
+ * Whether `value` is one of the type-tagged SPECIAL LEAVES both walkers normalize
54
+ * in place (never descend into). Today: a `Date`. A special leaf is NOT descendable
55
+ * (it is a leaf), so this is the exclusion consulted by {@link isDescendableObject}.
56
+ */
57
+ export function isSpecialLeaf(value) {
58
+ return value instanceof Date;
59
+ }
60
+ /**
61
+ * The SINGLE descend-set predicate — the one place that answers "should a walker
62
+ * recurse into this value's own enumerable keys?". Both `stripValue` and
63
+ * `canonicalizeValue` call THIS, so they descend the EXACT same objects (closes
64
+ * Defects A + B — a null-proto or class-instance object is descended by BOTH,
65
+ * regardless of prototype).
66
+ *
67
+ * TRUE for: a non-null value that is `typeof 'object'`, is NOT an array (arrays are
68
+ * handled by their own element-walk in both walkers), and is NOT a type-tagged
69
+ * special leaf ({@link isSpecialLeaf}). Prototype is IRRELEVANT — a
70
+ * `Object.create(null)` bag and a `class Foo {}` instance both qualify.
71
+ */
72
+ export function isDescendableObject(value) {
73
+ return (value !== null &&
74
+ typeof value === 'object' &&
75
+ !Array.isArray(value) &&
76
+ !isSpecialLeaf(value));
77
+ }
78
+ /**
79
+ * Compute the collision-free structural tag for a `Date` leaf, or `undefined` for
80
+ * any non-Date value.
81
+ *
82
+ * - `Date` → `{ __shieldType:'date', v:<epoch-ms|'null' for an invalid Date> }`.
83
+ *
84
+ * Returning a structural OBJECT (not a `"date:<ms>"` string prefix) is what makes a
85
+ * plain string value unable to collide with a tagged Date: the plain string
86
+ * `"date:0"` JSON-encodes to the string `"date:0"`, which can never equal the object
87
+ * form (closes round-2 Finding D). Numbers are NOT handled here — the canonicalizer
88
+ * normalizes `NaN`/`±Infinity`/`-0` inline to bare JSON tokens (see its scope note).
89
+ */
90
+ export function specialLeafTag(value) {
91
+ if (value instanceof Date) {
92
+ const ms = value.getTime();
93
+ return { __shieldType: 'date', v: Number.isNaN(ms) ? 'null' : String(ms) };
94
+ }
95
+ return undefined;
96
+ }
97
+ /**
98
+ * A shared cycle/over-depth guard for the two structural walkers. Each walker,
99
+ * before descending an object/array, calls this with its live visited-`WeakSet` and
100
+ * current depth. On a detected cycle (the value is already on the current descent
101
+ * path) OR an over-depth graph, it throws a TYPED
102
+ * `AuditValidationError('cyclic_attribute')` — NEVER an untyped `RangeError`
103
+ * mid-hash (closes Defect C). Returns silently when it is safe to descend.
104
+ *
105
+ * The caller is responsible for `visited.add(value)` before recursing into its
106
+ * children and `visited.delete(value)` after — so a value legitimately reachable by
107
+ * two SIBLING paths (a shared, non-cyclic sub-object) is NOT mis-flagged as a cycle.
108
+ */
109
+ export function guardDescent(value, visited, depth) {
110
+ if (depth > SHIELD_MAX_DEPTH || visited.has(value)) {
111
+ // A cycle (value already on the active descent path) or a pathologically deep
112
+ // graph — reject LOUD + TYPED. Carries NO value (a secret could ride in the
113
+ // attribute bag); the reason names the invariant, never the data.
114
+ throw new AuditValidationError('cyclic_attribute');
115
+ }
116
+ }
117
+ //# sourceMappingURL=walk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walk.js","sourceRoot":"","sources":["../../src/audit/walk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAyBnD,4EAA4E;AAC5E,4EAA4E;AAC5E,iFAAiF;AACjF,kFAAkF;AAClF,8EAA8E;AAC9E,oFAAoF;AACpF,mFAAmF;AACnF,mFAAmF;AACnF,qFAAqF;AAErF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAEpC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,KAAK,YAAY,IAAI,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAc;IAChD,OAAO,CACL,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACrB,CAAC,aAAa,CAAC,KAAK,CAAC,CACtB,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,IAAI,KAAK,YAAY,IAAI,EAAE,CAAC;QAC1B,MAAM,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;QAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC;IAC7E,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa,EAAE,OAAwB,EAAE,KAAa;IACjF,IAAI,KAAK,GAAG,gBAAgB,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QACnD,8EAA8E;QAC9E,4EAA4E;QAC5E,kEAAkE;QAClE,MAAM,IAAI,oBAAoB,CAAC,kBAAkB,CAAC,CAAC;IACrD,CAAC;AACH,CAAC"}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The Authentication **engine** — the body behind the FROZEN {@link Authenticator}
3
+ * seam (`./index.ts`). PROVES the caller is who they claim: verifies a password
4
+ * credential (via an injected {@link PasswordHasher}), evaluates required second
5
+ * factors, and on FULL success MINTS the {@link Principal} by delegating to the
6
+ * Identity broker's `normalize({ source: 'internal', … })` — it NEVER fabricates
7
+ * a Principal (reuses the broker's tenant-binding + superuser-safety).
8
+ *
9
+ * Mirrors the Identity engine exactly: a pure `createAuthenticator(...)` factory
10
+ * over INJECTED capabilities (hasher, resolver, factor verifiers, broker), a
11
+ * stateless impl, fail-closed everywhere.
12
+ *
13
+ * SCOPE — Auth PROVES, Session PERSISTS. This engine ENDS at
14
+ * `AuthenticationResult{ outcome:'authenticated', principal, satisfiedFactors }`.
15
+ * It mints NO tokens, writes NO session records, does NO rotation — that is the
16
+ * Session layer (step 6). It also does NOT issue/rotate service-account
17
+ * credentials, run any WebAuthn ceremony (only the factor CONTRACT slot exists),
18
+ * or emit a transient-vs-deny signal (that is enforcement, not auth).
19
+ *
20
+ * SECURITY invariants (all fail-closed):
21
+ * 1. ANTI-ENUMERATION — a "not found" hint and a "wrong password" both yield the
22
+ * SAME generic rejection; the reason NEVER distinguishes them.
23
+ * 2. ANTI-TIMING — an unknown hint still performs a dummy `hasher.verify`
24
+ * against a decoy hash, so unknown-user timing ≈ wrong-password timing.
25
+ * 3. NO PRINCIPAL WITHOUT SUCCESS — `principal` is populated ONLY on
26
+ * `outcome === 'authenticated'`; every other path omits it.
27
+ * 4. FAIL-CLOSED ERRORS — any resolver/hasher/verifier throw becomes a generic
28
+ * `rejected` result, never a raw throw that could leak a 500 / resource
29
+ * existence.
30
+ * 5. NO SECRET LEAKAGE — the plaintext, the stored hash, the TOTP secret are
31
+ * NEVER logged nor placed in a result/`reason`.
32
+ *
33
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
34
+ */
35
+ import type { IdentityBroker } from '../identity/index.js';
36
+ import type { Authenticator } from './index.js';
37
+ import type { CredentialResolver } from './credential-resolver.js';
38
+ import type { PasswordHasher } from './password-hasher.js';
39
+ import { type FactorVerifier } from './totp.js';
40
+ /** Options for {@link createAuthenticator}. */
41
+ export interface CreateAuthenticatorOptions {
42
+ /**
43
+ * The password hashing PORT (injected — the Argon2id concrete lives in
44
+ * `@astram/guard`, keeping Core zero-dep). Used to verify the password
45
+ * credential AND to burn the anti-timing dummy verify.
46
+ */
47
+ readonly hasher: PasswordHasher;
48
+ /**
49
+ * Resolves an identity hint → stored credential + claims, or `null` for an
50
+ * unknown hint (anti-enumeration). Injected — Core touches no store.
51
+ */
52
+ readonly resolver: CredentialResolver;
53
+ /**
54
+ * The Identity broker the engine mints principals through on full success
55
+ * (`normalize({ source: 'internal', claims })`). Reuses tenant-binding +
56
+ * superuser-safety — the engine never fabricates a Principal.
57
+ */
58
+ readonly identityBroker: IdentityBroker;
59
+ /**
60
+ * Optional second-factor verifiers (e.g. the reference TOTP verifier). When
61
+ * omitted, only password-only credentials can authenticate; a resolved
62
+ * credential that REQUIRES a factor with no registered verifier fail-closes to
63
+ * `mfa_required` (never authenticates). Duplicate factors fail-closed at
64
+ * registration.
65
+ */
66
+ readonly factorVerifiers?: readonly FactorVerifier[];
67
+ }
68
+ /**
69
+ * Wire the injected capabilities and return an object implementing the FROZEN
70
+ * {@link Authenticator}. The engine's public entry point (mirrors
71
+ * `createIdentityBroker`).
72
+ */
73
+ export declare function createAuthenticator(options: CreateAuthenticatorOptions): Authenticator;
74
+ //# sourceMappingURL=authenticator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticator.d.ts","sourceRoot":"","sources":["../../src/authentication/authenticator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,KAAK,EACV,cAAc,EAEf,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAGV,aAAa,EAEd,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,0BAA0B,CAAC;AACnF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAA0B,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAkMxE,+CAA+C;AAC/C,MAAM,WAAW,0BAA0B;IACzC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAChC;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,kBAAkB,CAAC;IACtC;;;;OAIG;IACH,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC;;;;;;OAMG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;CACtD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,0BAA0B,GAClC,aAAa,CAWf"}
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The Authentication **engine** — the body behind the FROZEN {@link Authenticator}
3
+ * seam (`./index.ts`). PROVES the caller is who they claim: verifies a password
4
+ * credential (via an injected {@link PasswordHasher}), evaluates required second
5
+ * factors, and on FULL success MINTS the {@link Principal} by delegating to the
6
+ * Identity broker's `normalize({ source: 'internal', … })` — it NEVER fabricates
7
+ * a Principal (reuses the broker's tenant-binding + superuser-safety).
8
+ *
9
+ * Mirrors the Identity engine exactly: a pure `createAuthenticator(...)` factory
10
+ * over INJECTED capabilities (hasher, resolver, factor verifiers, broker), a
11
+ * stateless impl, fail-closed everywhere.
12
+ *
13
+ * SCOPE — Auth PROVES, Session PERSISTS. This engine ENDS at
14
+ * `AuthenticationResult{ outcome:'authenticated', principal, satisfiedFactors }`.
15
+ * It mints NO tokens, writes NO session records, does NO rotation — that is the
16
+ * Session layer (step 6). It also does NOT issue/rotate service-account
17
+ * credentials, run any WebAuthn ceremony (only the factor CONTRACT slot exists),
18
+ * or emit a transient-vs-deny signal (that is enforcement, not auth).
19
+ *
20
+ * SECURITY invariants (all fail-closed):
21
+ * 1. ANTI-ENUMERATION — a "not found" hint and a "wrong password" both yield the
22
+ * SAME generic rejection; the reason NEVER distinguishes them.
23
+ * 2. ANTI-TIMING — an unknown hint still performs a dummy `hasher.verify`
24
+ * against a decoy hash, so unknown-user timing ≈ wrong-password timing.
25
+ * 3. NO PRINCIPAL WITHOUT SUCCESS — `principal` is populated ONLY on
26
+ * `outcome === 'authenticated'`; every other path omits it.
27
+ * 4. FAIL-CLOSED ERRORS — any resolver/hasher/verifier throw becomes a generic
28
+ * `rejected` result, never a raw throw that could leak a 500 / resource
29
+ * existence.
30
+ * 5. NO SECRET LEAKAGE — the plaintext, the stored hash, the TOTP secret are
31
+ * NEVER logged nor placed in a result/`reason`.
32
+ *
33
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
34
+ */
35
+ import { FactorVerifierRegistry } from './totp.js';
36
+ /** The Internal source the engine mints principals through (canonical claims). */
37
+ const INTERNAL_SOURCE = 'internal';
38
+ /**
39
+ * A single, GENERIC rejection reason for EVERY credential-failure path
40
+ * (unknown user, wrong password, unsatisfied/failed factor error). It never
41
+ * distinguishes existence or which check failed — anti-enumeration (§1). MFA and
42
+ * hard-error paths use their own equally-generic reasons below.
43
+ */
44
+ const REASON_INVALID_CREDENTIALS = 'invalid_credentials';
45
+ const REASON_MFA_REQUIRED = 'mfa_required';
46
+ const REASON_AUTH_UNAVAILABLE = 'authentication_unavailable';
47
+ /**
48
+ * A decoy Argon2id-shaped hash the engine verifies against when NO credential was
49
+ * resolved (unknown hint). Its ONLY purpose is to make the hasher do a full,
50
+ * representative unit of work so unknown-user timing ≈ wrong-password timing
51
+ * (§2). It is a fixed, non-secret constant that matches no real password. The
52
+ * concrete hasher parses it as a normal encoded hash and returns `false`.
53
+ */
54
+ const DECOY_PASSWORD_HASH = '$argon2id$v=19$m=19456,t=2,p=1$c2hpZWxkZGVjb3lzYWx0MDAwMA$0000000000000000000000000000000000000000000';
55
+ /** A frozen "rejected, generic reason, no principal" result. */
56
+ function rejected() {
57
+ return Object.freeze({
58
+ outcome: 'rejected',
59
+ satisfiedFactors: Object.freeze([]),
60
+ reason: REASON_INVALID_CREDENTIALS,
61
+ });
62
+ }
63
+ /** A frozen "authentication_unavailable" result (fail-closed on hard error). */
64
+ function unavailable() {
65
+ return Object.freeze({
66
+ outcome: 'rejected',
67
+ satisfiedFactors: Object.freeze([]),
68
+ reason: REASON_AUTH_UNAVAILABLE,
69
+ });
70
+ }
71
+ /** Extract the presented password (string) from a `password` credential. */
72
+ function presentedPassword(credentials) {
73
+ const cred = credentials.find((c) => c.factor === 'password');
74
+ const pw = cred?.payload?.password;
75
+ return typeof pw === 'string' ? pw : undefined;
76
+ }
77
+ /** All non-password credentials presented, indexed by factor (first wins). */
78
+ function presentedFactor(credentials, factor) {
79
+ return credentials.find((c) => c.factor === factor);
80
+ }
81
+ /**
82
+ * The concrete engine. Stateless per call; holds only its injected capabilities.
83
+ * Instances come from {@link createAuthenticator}.
84
+ */
85
+ class AuthenticatorImpl {
86
+ hasher;
87
+ resolver;
88
+ identityBroker;
89
+ factorVerifiers;
90
+ constructor(hasher, resolver, identityBroker, factorVerifiers) {
91
+ this.hasher = hasher;
92
+ this.resolver = resolver;
93
+ this.identityBroker = identityBroker;
94
+ this.factorVerifiers = factorVerifiers;
95
+ }
96
+ async authenticate(identityHint, credentials) {
97
+ try {
98
+ return await this.attempt(identityHint, credentials);
99
+ }
100
+ catch {
101
+ // §4 FAIL-CLOSED: ANY unexpected throw (resolver outage, hasher fault,
102
+ // verifier bug, broker reject) → a generic rejection, never a raw throw.
103
+ // We deliberately swallow the error object so nothing about it can leak.
104
+ return unavailable();
105
+ }
106
+ }
107
+ async attempt(identityHint, credentials) {
108
+ const password = presentedPassword(credentials);
109
+ // Resolve the hint. `null` = unknown principal (anti-enumeration): we do NOT
110
+ // early-return — we still perform an equivalent hash verify below so the
111
+ // unknown-user path costs the same as the wrong-password path (§2).
112
+ const resolved = await this.resolver.resolve(identityHint);
113
+ if (resolved === null) {
114
+ // §2 ANTI-TIMING: burn a representative verify against the decoy hash. The
115
+ // result is discarded — the outcome is ALWAYS a generic rejection.
116
+ await this.hasher.verify(DECOY_PASSWORD_HASH, password ?? '');
117
+ return rejected();
118
+ }
119
+ // A resolved principal but no presented password → still a generic rejection
120
+ // AFTER a dummy verify (keep timing uniform; never reveal "missing password").
121
+ if (password === undefined) {
122
+ await this.hasher.verify(resolved.passwordHash, '');
123
+ return rejected();
124
+ }
125
+ // §1 verify the password. Wrong → generic rejection (indistinguishable from
126
+ // the unknown-user path above).
127
+ //
128
+ // FAIL-CLOSED OVER THE PORT (defense-in-depth): the injected PasswordHasher is
129
+ // a capability the engine does NOT control. Gate on STRICT `=== true`, never
130
+ // truthiness — a misbehaving/hostile hasher returning a truthy non-boolean
131
+ // (`"false"`, `1`, `{}`, `[]`) must NOT mint a principal. Only a genuine
132
+ // boolean `true` passes; everything else rejects.
133
+ const ok = (await this.hasher.verify(resolved.passwordHash, password)) === true;
134
+ if (!ok) {
135
+ return rejected();
136
+ }
137
+ // Password satisfied. Evaluate required factors.
138
+ const satisfiedFactors = ['password'];
139
+ const required = resolved.requiredFactors ?? [];
140
+ for (const req of required) {
141
+ const verifier = this.factorVerifiers.resolve(req.factor);
142
+ const presented = presentedFactor(credentials, req.factor);
143
+ // No verifier wired for a required factor → fail-closed: the factor can
144
+ // never be satisfied, so the attempt cannot proceed. Surfaced as a step-up
145
+ // request (not a hard reject) so the caller can present the factor once
146
+ // wiring exists — but WITHOUT a principal.
147
+ if (verifier === undefined) {
148
+ return mfaRequired(satisfiedFactors, req.factor);
149
+ }
150
+ // Required factor not presented in THIS attempt → step-up (mfa_required),
151
+ // NO principal (§3). The caller re-submits with the factor.
152
+ if (presented === undefined) {
153
+ return mfaRequired(satisfiedFactors, req.factor);
154
+ }
155
+ const verdict = await verifier.verify(presented, req.secret);
156
+ // FAIL-CLOSED OVER THE PORT (defense-in-depth, same rule as the password
157
+ // gate): a factor counts as satisfied ONLY on a STRICT boolean `true`. A
158
+ // misbehaving/hostile FactorVerifier returning a truthy non-boolean
159
+ // `satisfied` (`"false"`, `1`, `{}`, `[]`) must NOT bypass MFA — treat it as
160
+ // NOT satisfied → generic rejection, no principal.
161
+ if (verdict.satisfied !== true) {
162
+ // A PRESENTED-but-WRONG (or non-strict-true) factor is a rejection (a bad
163
+ // code, not a missing one) — generic reason, no principal.
164
+ return rejected();
165
+ }
166
+ satisfiedFactors.push(req.factor);
167
+ }
168
+ // §3 FULL success → mint the Principal via the Identity broker (reuse its
169
+ // tenant-binding + superuser-safety; do NOT fabricate). A broker reject
170
+ // (malformed claims, missing tenant) propagates to the outer catch →
171
+ // fail-closed `authentication_unavailable` (never a partial/unsafe principal).
172
+ const principal = await this.identityBroker.normalize({
173
+ source: INTERNAL_SOURCE,
174
+ claims: resolved.claims,
175
+ });
176
+ return Object.freeze({
177
+ outcome: 'authenticated',
178
+ principal,
179
+ satisfiedFactors: Object.freeze([...satisfiedFactors]),
180
+ });
181
+ }
182
+ }
183
+ /**
184
+ * A frozen `mfa_required` result — NO principal (§3), generic reason. Names the
185
+ * outstanding factor only in the machine `reason` suffix so a caller can drive
186
+ * the step-up UX; it reveals nothing about the user beyond "another factor is
187
+ * needed" (which the caller already knows it must present).
188
+ */
189
+ function mfaRequired(satisfiedFactors, outstanding) {
190
+ return Object.freeze({
191
+ outcome: 'mfa_required',
192
+ satisfiedFactors: Object.freeze([...satisfiedFactors]),
193
+ reason: `${REASON_MFA_REQUIRED}:${outstanding}`,
194
+ });
195
+ }
196
+ /**
197
+ * Wire the injected capabilities and return an object implementing the FROZEN
198
+ * {@link Authenticator}. The engine's public entry point (mirrors
199
+ * `createIdentityBroker`).
200
+ */
201
+ export function createAuthenticator(options) {
202
+ const registry = new FactorVerifierRegistry();
203
+ for (const verifier of options.factorVerifiers ?? []) {
204
+ registry.register(verifier);
205
+ }
206
+ return new AuthenticatorImpl(options.hasher, options.resolver, options.identityBroker, registry);
207
+ }
208
+ //# sourceMappingURL=authenticator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticator.js","sourceRoot":"","sources":["../../src/authentication/authenticator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAcH,OAAO,EAAE,sBAAsB,EAAuB,MAAM,WAAW,CAAC;AAExE,kFAAkF;AAClF,MAAM,eAAe,GAAG,UAAU,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,0BAA0B,GAAG,qBAAqB,CAAC;AACzD,MAAM,mBAAmB,GAAG,cAAc,CAAC;AAC3C,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;GAMG;AACH,MAAM,mBAAmB,GACvB,uGAAuG,CAAC;AAE1G,gEAAgE;AAChE,SAAS,QAAQ;IACf,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,OAAO,EAAE,UAAU;QACnB,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QACnC,MAAM,EAAE,0BAA0B;KACnC,CAAC,CAAC;AACL,CAAC;AAED,gFAAgF;AAChF,SAAS,WAAW;IAClB,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,OAAO,EAAE,UAAU;QACnB,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QACnC,MAAM,EAAE,uBAAuB;KAChC,CAAC,CAAC;AACL,CAAC;AAED,4EAA4E;AAC5E,SAAS,iBAAiB,CAAC,WAAkC;IAC3D,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,C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MAAM,QAAQ,GAAG,IAAI,sBAAsB,EAAE,CAAC;IAC9C,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,eAAe,IAAI,EAAE,EAAE,CAAC;QACrD,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,IAAI,iBAAiB,CAC1B,OAAO,CAAC,MAAM,EACd,OAAO,CAAC,QAAQ,EAChB,OAAO,CAAC,cAAc,EACtB,QAAQ,CACT,CAAC;AACJ,CAAC"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The **CredentialResolver PORT** — resolves an `identityHint` (username / email)
3
+ * to the stored credential material + the claims needed to build a `Principal`.
4
+ *
5
+ * This is the seam between the pure Authentication engine and the deployment's
6
+ * credential store (a DB, a directory, a secrets service). The engine never
7
+ * touches storage; it asks the resolver for a `ResolvedCredential` and works
8
+ * purely with the returned record. ADR-0003: the resolver is INJECTED, so the
9
+ * Core takes on no DB/framework dependency.
10
+ *
11
+ * ANTI-ENUMERATION (security-critical): an unknown hint MUST resolve to `null`,
12
+ * NOT throw. The engine handles a `null` with the SAME generic rejection AND the
13
+ * same amount of work (a dummy hash verify) it does for a *wrong password*, so a
14
+ * caller cannot distinguish "no such user" from "bad password" by response
15
+ * content OR by timing. The resolver therefore never encodes existence in an
16
+ * error; `null` is the single, uniform "no credential" signal.
17
+ *
18
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
19
+ */
20
+ import type { AuthFactor } from './index.js';
21
+ /**
22
+ * A resolved credential record for one principal. Carries the password hash the
23
+ * engine verifies, the canonical claims the engine hands to
24
+ * `IdentityBroker.normalize({ source: 'internal', … })` to MINT the Principal
25
+ * (the engine never fabricates one), and the factors this principal must satisfy.
26
+ *
27
+ * SECURITY — `passwordHash` is a transient verify input; the engine never logs it
28
+ * and never places it (or any part of it) in an `AuthenticationResult`.
29
+ */
30
+ export interface ResolvedCredential {
31
+ /**
32
+ * The encoded password hash (algorithm-self-describing) to verify against the
33
+ * presented `password` credential via the injected `PasswordHasher`.
34
+ */
35
+ readonly passwordHash: string;
36
+ /**
37
+ * Canonical Internal-source claims (`id`, `tenantId`, `kind?`, `roleIds?`) the
38
+ * engine passes to `IdentityBroker.normalize({ source: 'internal', claims })`
39
+ * on FULL success. Reusing the broker inherits its tenant-binding +
40
+ * superuser-safety — the engine does NOT hand-build a Principal. Superuser
41
+ * status is decided by the broker's server-side allowlist, never by a claim
42
+ * placed here.
43
+ */
44
+ readonly claims: Readonly<Record<string, unknown>>;
45
+ /**
46
+ * Factors this principal is REQUIRED to satisfy in addition to the password
47
+ * (e.g. `['totp']`). Absent/empty ⇒ password alone authenticates. A required
48
+ * factor left unsatisfied yields `outcome: 'mfa_required'` (no principal).
49
+ * The factor's verification material (e.g. the TOTP shared secret) is carried
50
+ * here so the engine can drive the registered `FactorVerifier` without a second
51
+ * store lookup.
52
+ */
53
+ readonly requiredFactors?: readonly RequiredFactor[];
54
+ }
55
+ /**
56
+ * One required second factor + the server-side material needed to verify it.
57
+ * `secret` is opaque to the engine — it is handed to the `FactorVerifier`
58
+ * registered for `factor`, which knows how to interpret it (e.g. the TOTP
59
+ * verifier reads a base-string shared secret). NEVER logged.
60
+ */
61
+ export interface RequiredFactor {
62
+ readonly factor: AuthFactor;
63
+ /** Verifier-specific server-side material (e.g. TOTP shared secret). */
64
+ readonly secret: string;
65
+ }
66
+ /**
67
+ * Resolves an identity hint to its stored credential, or `null` when no such
68
+ * principal exists. `null` is the ONLY "not found" signal (anti-enumeration —
69
+ * see file header); the resolver MUST NOT throw for an unknown hint. A resolver
70
+ * that DOES throw (store outage, etc.) is treated by the engine as fail-closed
71
+ * (typed rejection, never a leaked 500).
72
+ */
73
+ export interface CredentialResolver {
74
+ resolve(identityHint: string): Promise<ResolvedCredential | null>;
75
+ }
76
+ //# sourceMappingURL=credential-resolver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-resolver.d.ts","sourceRoot":"","sources":["../../src/authentication/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;;;;;GAQG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B;;;;;;;OAOG;IACH,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACnD;;;;;;;OAOG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;CACtD;AAED;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,wEAAwE;IACxE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,kBAAkB;IACjC,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;CACnE"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The **CredentialResolver PORT** — resolves an `identityHint` (username / email)
3
+ * to the stored credential material + the claims needed to build a `Principal`.
4
+ *
5
+ * This is the seam between the pure Authentication engine and the deployment's
6
+ * credential store (a DB, a directory, a secrets service). The engine never
7
+ * touches storage; it asks the resolver for a `ResolvedCredential` and works
8
+ * purely with the returned record. ADR-0003: the resolver is INJECTED, so the
9
+ * Core takes on no DB/framework dependency.
10
+ *
11
+ * ANTI-ENUMERATION (security-critical): an unknown hint MUST resolve to `null`,
12
+ * NOT throw. The engine handles a `null` with the SAME generic rejection AND the
13
+ * same amount of work (a dummy hash verify) it does for a *wrong password*, so a
14
+ * caller cannot distinguish "no such user" from "bad password" by response
15
+ * content OR by timing. The resolver therefore never encodes existence in an
16
+ * error; `null` is the single, uniform "no credential" signal.
17
+ *
18
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
19
+ */
20
+ export {};
21
+ //# sourceMappingURL=credential-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-resolver.js","sourceRoot":"","sources":["../../src/authentication/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG"}