@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,162 @@
1
+ "use strict";
2
+ /**
3
+ * **Sensitive-attribute stripping** — the no-secret-leak guard (§2, AC-7).
4
+ *
5
+ * The audit engine records for INTEGRITY, and it MUST NEVER persist a secret
6
+ * value. A caller may accidentally include a token / password / hash in an
7
+ * event's `attributes`; this module removes any attribute whose KEY matches a
8
+ * denylisted secret-bearing term BEFORE the record is built or hashed, so a raw
9
+ * secret never reaches the store, the content hash, or a log.
10
+ *
11
+ * Matching is by KEY (case-insensitive substring): a key CONTAINING a denylist
12
+ * term is stripped (e.g. `access_token`, `userPassword`, `x-api-key` all match).
13
+ * Values are never inspected (a value scan is unreliable and could itself leak).
14
+ * Only the stripped key NAMES are surfaced (`strippedKeys`) — never the values.
15
+ *
16
+ * Stripping RECURSES through nested objects AND arrays at every depth: a
17
+ * denylisted key found under a benign parent — `{ meta: { password } }` or
18
+ * `{ changes: [{ secret }] }` — is stripped just as a top-level one is, so a raw
19
+ * secret never survives inside a diff-bag / `meta:{}` / request snapshot either.
20
+ * Recorded `strippedKeys` carry the dotted PATH to each removed key (names only,
21
+ * never values), so a nested strip is forensically visible.
22
+ *
23
+ * The denylist is DEFAULT-ON and overridable per recorder (a caller may pass a
24
+ * REPLACEMENT list) — but there is no way to disable stripping entirely; passing
25
+ * an empty list is the explicit opt-out and is the caller's documented risk.
26
+ *
27
+ * PURE — no I/O, no state. ADR-0003: framework-agnostic — no framework / HTTP /
28
+ * DB / node imports.
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.DEFAULT_SENSITIVE_DENYLIST = void 0;
32
+ exports.stripSensitive = stripSensitive;
33
+ const walk_js_1 = require("./walk.js");
34
+ /**
35
+ * The DEFAULT denylist of secret-bearing key fragments (lower-case; matched as a
36
+ * case-insensitive SUBSTRING of an attribute key). Covers tokens, passwords,
37
+ * password/refresh hashes, API keys, credentials, session/OTP/MFA secrets. A key
38
+ * CONTAINING any of these is stripped — e.g. `refresh_token`, `refreshToken`,
39
+ * `api_key`, `apiKey`, `session_token`, `mfa_secret`, `pwd`.
40
+ *
41
+ * ⛔ Extend, don't shrink: adding fragments only makes the guard stricter.
42
+ * Overriding with a SHORTER list is a deliberate (documented) risk the caller owns.
43
+ */
44
+ exports.DEFAULT_SENSITIVE_DENYLIST = Object.freeze([
45
+ 'token',
46
+ 'password',
47
+ 'passwd',
48
+ 'pwd',
49
+ 'secret',
50
+ 'refresh_token',
51
+ 'refreshtoken',
52
+ 'access_token',
53
+ 'authorization',
54
+ 'api_key',
55
+ 'api-key',
56
+ 'apikey',
57
+ 'private_key',
58
+ 'credential',
59
+ 'session_token',
60
+ 'otp',
61
+ 'mfa_secret',
62
+ 'hash',
63
+ ]);
64
+ /**
65
+ * Return whether `key` matches any denylist fragment (case-insensitive substring).
66
+ * A denylist fragment is compared already-lower-cased against the lower-cased key.
67
+ */
68
+ function isSensitiveKey(key, denylistLower) {
69
+ const k = key.toLowerCase();
70
+ return denylistLower.some((frag) => k.includes(frag));
71
+ }
72
+ /**
73
+ * Recursively strip denylisted keys from an arbitrary attribute VALUE. Objects are
74
+ * walked key-by-key (a denylisted key at ANY depth → its value is dropped and the
75
+ * dotted path recorded); arrays are walked element-by-element (order preserved,
76
+ * indices form part of the path). Primitives pass through unchanged. Deterministic:
77
+ * key iteration follows the object's own order and array order is retained, so the
78
+ * downstream key-sorted canonicalization stays reproducible.
79
+ *
80
+ * ⛔ DESCEND-SET PARITY: an OBJECT is descended iff {@link isDescendableObject} — the
81
+ * SAME shared predicate the canonicalizer (`./canonicalize.ts`) uses — so the
82
+ * stripper and the canonicalizer recurse into the EXACT same objects, REGARDLESS of
83
+ * prototype (a null-proto `Object.create(null)` bag or a class instance is descended
84
+ * by both). This closes the round-2 secret-leak regression: previously the stripper
85
+ * descended only `Object.prototype`-proto objects while the canonicalizer hashed
86
+ * ANY object, so a secret on a non-plain object was hashed+stored but NOT stripped.
87
+ * Own ENUMERABLE keys are read directly (`Object.keys`), which works for any
88
+ * prototype — so a denylisted key on a null-proto bag is matched too.
89
+ *
90
+ * A special leaf (Date) is NOT descendable ({@link isDescendableObject} excludes it)
91
+ * → passes through untouched here; the canonicalizer owns its value normalization.
92
+ *
93
+ * The shared {@link guardDescent} (visited-`WeakSet` + depth cap) rejects a cyclic /
94
+ * pathologically-deep graph with a TYPED `AuditValidationError('cyclic_attribute')`
95
+ * — never an untyped `RangeError` from stack overflow.
96
+ *
97
+ * `path` is the dotted prefix of the current value (`''` at the top level).
98
+ */
99
+ function stripValue(value, denylistLower, path, strippedKeys, visited, depth) {
100
+ if (Array.isArray(value)) {
101
+ (0, walk_js_1.guardDescent)(value, visited, depth);
102
+ visited.add(value);
103
+ try {
104
+ return value.map((element, index) => stripValue(element, denylistLower, path === '' ? String(index) : `${path}.${index}`, strippedKeys, visited, depth + 1));
105
+ }
106
+ finally {
107
+ visited.delete(value);
108
+ }
109
+ }
110
+ // Descend by the SHARED predicate (any non-null, non-array, non-special-leaf
111
+ // object — REGARDLESS of prototype). Own enumerable keys are read directly, so a
112
+ // denylisted key on a null-proto / class-instance object is stripped too.
113
+ if ((0, walk_js_1.isDescendableObject)(value)) {
114
+ (0, walk_js_1.guardDescent)(value, visited, depth);
115
+ visited.add(value);
116
+ try {
117
+ const obj = value;
118
+ const cleaned = {};
119
+ for (const key of Object.keys(obj)) {
120
+ const keyPath = path === '' ? key : `${path}.${key}`;
121
+ if (isSensitiveKey(key, denylistLower)) {
122
+ // Record only the PATH — never the value (that is the secret).
123
+ strippedKeys.push(keyPath);
124
+ continue;
125
+ }
126
+ cleaned[key] = stripValue(obj[key], denylistLower, keyPath, strippedKeys, visited, depth + 1);
127
+ }
128
+ return cleaned;
129
+ }
130
+ finally {
131
+ visited.delete(value);
132
+ }
133
+ }
134
+ return value;
135
+ }
136
+ /**
137
+ * Strip every attribute whose KEY is denylisted (AC-7). The engine calls this on
138
+ * an event's `attributes` before building/hashing the stored record, so NO raw
139
+ * secret value ever reaches the store, the `contentHash`, or a log.
140
+ *
141
+ * @param attributes The caller's raw attribute bag (or `undefined`).
142
+ * @param denylist Optional REPLACEMENT denylist; defaults to
143
+ * {@link DEFAULT_SENSITIVE_DENYLIST}. Matching is case-insensitive
144
+ * substring on the key. An empty list disables stripping (a
145
+ * documented, caller-owned risk).
146
+ * @returns The `cleaned` bag (secret keys removed) + `strippedKeys` names.
147
+ */
148
+ function stripSensitive(attributes, denylist = exports.DEFAULT_SENSITIVE_DENYLIST) {
149
+ if (attributes === undefined || attributes === null) {
150
+ return { cleaned: undefined, strippedKeys: [] };
151
+ }
152
+ const denylistLower = denylist.map((d) => d.toLowerCase());
153
+ const strippedKeys = [];
154
+ // Walk the top-level bag recursively: a denylisted key at ANY depth (nested
155
+ // object or array element) is stripped and its dotted path recorded. The bag is
156
+ // descended by the SHARED predicate REGARDLESS of prototype, so a top-level
157
+ // denylist key on a null-proto `Object.create(null)` bag is stripped too (round-2
158
+ // Finding A). A fresh visited-`WeakSet` (depth 0) backs the shared cycle guard.
159
+ const visited = new WeakSet();
160
+ const cleaned = stripValue(attributes, denylistLower, '', strippedKeys, visited, 0);
161
+ return { cleaned, strippedKeys };
162
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ /**
3
+ * **Shared structural-walk primitives** — the SINGLE SOURCE OF TRUTH for "which
4
+ * objects are descended" and "how a special leaf is tagged", used by BOTH the
5
+ * secret stripper (`./sensitive.ts`) and the canonical serializer
6
+ * (`./canonicalize.ts`).
7
+ *
8
+ * ── WHY THIS MODULE EXISTS (round-2 rulings A/B/C/D).
9
+ * The two walkers previously disagreed on their descend-set: the stripper
10
+ * descended only `Object.getPrototypeOf(v) === Object.prototype` objects, while
11
+ * the canonicalizer serialized-and-hashed ANY `typeof 'object'`. Wherever they
12
+ * disagreed, a secret on a class-instance / null-proto object was HASHED + STORED
13
+ * but NOT STRIPPED → a secret leaked (Defects A, B). Centralizing the descend-set
14
+ * predicate here — and having BOTH walkers import it — makes the two walkers
15
+ * descend the EXACT same objects by construction, so that bug class cannot recur.
16
+ *
17
+ * ── WHAT LIVES HERE.
18
+ * 1. {@link isDescendableObject} — the one predicate both walkers use to decide
19
+ * "recurse into this value's own keys?" (non-null, `typeof 'object'`, NOT an
20
+ * array, NOT a type-tagged special leaf like `Date`) — REGARDLESS of prototype.
21
+ * 2. {@link isSpecialLeaf} / {@link specialLeafTag} — the collision-free
22
+ * STRUCTURAL tag for a normalized special value (`Date`, `-0`, `NaN`,
23
+ * `±Infinity`). A structural object shape `{__shieldType,v}` — which a plain
24
+ * string can NEVER serialize to — replaces the old string-prefix tags
25
+ * (`"date:0"`), closing the plain-string collision (Defect D).
26
+ * 3. {@link SHIELD_MAX_DEPTH} + {@link throwOnCycle} helpers backing the shared
27
+ * visited-`WeakSet` / depth guard both walkers carry, so a cyclic /
28
+ * pathologically-deep attribute graph throws a TYPED
29
+ * `AuditValidationError('cyclic_attribute')` rather than an untyped
30
+ * `RangeError` mid-hash (Defect C).
31
+ *
32
+ * PURE — no I/O, no state, no clock. ADR-0003: framework-agnostic — no framework /
33
+ * HTTP / DB / node imports.
34
+ */
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SHIELD_MAX_DEPTH = void 0;
37
+ exports.isSpecialLeaf = isSpecialLeaf;
38
+ exports.isDescendableObject = isDescendableObject;
39
+ exports.specialLeafTag = specialLeafTag;
40
+ exports.guardDescent = guardDescent;
41
+ const errors_js_1 = require("./errors.js");
42
+ // NOTE: a plain caller attribute bag could, in principle, contain a literal
43
+ // `__shieldType` key. That is harmless — it is a plain STRING-keyed object,
44
+ // descended/serialized as an ordinary object (its value string is JSON-encoded),
45
+ // and the `date` tag is ONLY ever produced for a genuine `Date` leaf, never for a
46
+ // plain object, so a caller-supplied `{__shieldType:'date',v:'0'}` and a real
47
+ // `new Date(0)` still differ: the Date's `v` is a decimal-ms string tag emitted for
48
+ // a Date instance specifically, and the two are not required to be distinguishable
49
+ // (a caller crafting that exact object is choosing that value) — what matters is a
50
+ // plain STRING can never reach the tag's OBJECT form, which is the collision closed.
51
+ /**
52
+ * The maximum structural depth either walker will descend before treating the graph
53
+ * as pathological. Chosen well above any realistic audit attribute bag; a legitimate
54
+ * event's attributes are shallow. Hitting this cap almost always means a cycle the
55
+ * `WeakSet` didn't catch (e.g. a non-cyclic but exponentially deep graph) — either
56
+ * way it is REJECTED with a typed error, never allowed to overflow the stack.
57
+ */
58
+ exports.SHIELD_MAX_DEPTH = 256;
59
+ /**
60
+ * Whether `value` is one of the type-tagged SPECIAL LEAVES both walkers normalize
61
+ * in place (never descend into). Today: a `Date`. A special leaf is NOT descendable
62
+ * (it is a leaf), so this is the exclusion consulted by {@link isDescendableObject}.
63
+ */
64
+ function isSpecialLeaf(value) {
65
+ return value instanceof Date;
66
+ }
67
+ /**
68
+ * The SINGLE descend-set predicate — the one place that answers "should a walker
69
+ * recurse into this value's own enumerable keys?". Both `stripValue` and
70
+ * `canonicalizeValue` call THIS, so they descend the EXACT same objects (closes
71
+ * Defects A + B — a null-proto or class-instance object is descended by BOTH,
72
+ * regardless of prototype).
73
+ *
74
+ * TRUE for: a non-null value that is `typeof 'object'`, is NOT an array (arrays are
75
+ * handled by their own element-walk in both walkers), and is NOT a type-tagged
76
+ * special leaf ({@link isSpecialLeaf}). Prototype is IRRELEVANT — a
77
+ * `Object.create(null)` bag and a `class Foo {}` instance both qualify.
78
+ */
79
+ function isDescendableObject(value) {
80
+ return (value !== null &&
81
+ typeof value === 'object' &&
82
+ !Array.isArray(value) &&
83
+ !isSpecialLeaf(value));
84
+ }
85
+ /**
86
+ * Compute the collision-free structural tag for a `Date` leaf, or `undefined` for
87
+ * any non-Date value.
88
+ *
89
+ * - `Date` → `{ __shieldType:'date', v:<epoch-ms|'null' for an invalid Date> }`.
90
+ *
91
+ * Returning a structural OBJECT (not a `"date:<ms>"` string prefix) is what makes a
92
+ * plain string value unable to collide with a tagged Date: the plain string
93
+ * `"date:0"` JSON-encodes to the string `"date:0"`, which can never equal the object
94
+ * form (closes round-2 Finding D). Numbers are NOT handled here — the canonicalizer
95
+ * normalizes `NaN`/`±Infinity`/`-0` inline to bare JSON tokens (see its scope note).
96
+ */
97
+ function specialLeafTag(value) {
98
+ if (value instanceof Date) {
99
+ const ms = value.getTime();
100
+ return { __shieldType: 'date', v: Number.isNaN(ms) ? 'null' : String(ms) };
101
+ }
102
+ return undefined;
103
+ }
104
+ /**
105
+ * A shared cycle/over-depth guard for the two structural walkers. Each walker,
106
+ * before descending an object/array, calls this with its live visited-`WeakSet` and
107
+ * current depth. On a detected cycle (the value is already on the current descent
108
+ * path) OR an over-depth graph, it throws a TYPED
109
+ * `AuditValidationError('cyclic_attribute')` — NEVER an untyped `RangeError`
110
+ * mid-hash (closes Defect C). Returns silently when it is safe to descend.
111
+ *
112
+ * The caller is responsible for `visited.add(value)` before recursing into its
113
+ * children and `visited.delete(value)` after — so a value legitimately reachable by
114
+ * two SIBLING paths (a shared, non-cyclic sub-object) is NOT mis-flagged as a cycle.
115
+ */
116
+ function guardDescent(value, visited, depth) {
117
+ if (depth > exports.SHIELD_MAX_DEPTH || visited.has(value)) {
118
+ // A cycle (value already on the active descent path) or a pathologically deep
119
+ // graph — reject LOUD + TYPED. Carries NO value (a secret could ride in the
120
+ // attribute bag); the reason names the invariant, never the data.
121
+ throw new errors_js_1.AuditValidationError('cyclic_attribute');
122
+ }
123
+ }
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ /**
3
+ * The Authentication **engine** — the body behind the FROZEN {@link Authenticator}
4
+ * seam (`./index.ts`). PROVES the caller is who they claim: verifies a password
5
+ * credential (via an injected {@link PasswordHasher}), evaluates required second
6
+ * factors, and on FULL success MINTS the {@link Principal} by delegating to the
7
+ * Identity broker's `normalize({ source: 'internal', … })` — it NEVER fabricates
8
+ * a Principal (reuses the broker's tenant-binding + root-safety).
9
+ *
10
+ * Mirrors the Identity engine exactly: a pure `createAuthenticator(...)` factory
11
+ * over INJECTED capabilities (hasher, resolver, factor verifiers, broker), a
12
+ * stateless impl, fail-closed everywhere.
13
+ *
14
+ * SCOPE — Auth PROVES, Session PERSISTS. This engine ENDS at
15
+ * `AuthenticationResult{ outcome:'authenticated', principal, satisfiedFactors }`.
16
+ * It mints NO tokens, writes NO session records, does NO rotation — that is the
17
+ * Session layer (step 6). It also does NOT issue/rotate service-account
18
+ * credentials, run any WebAuthn ceremony (only the factor CONTRACT slot exists),
19
+ * or emit a transient-vs-deny signal (that is enforcement, not auth).
20
+ *
21
+ * SECURITY invariants (all fail-closed):
22
+ * 1. ANTI-ENUMERATION — a "not found" hint and a "wrong password" both yield the
23
+ * SAME generic rejection; the reason NEVER distinguishes them.
24
+ * 2. ANTI-TIMING — an unknown hint still performs a dummy `hasher.verify`
25
+ * against a decoy hash, so unknown-user timing ≈ wrong-password timing.
26
+ * 3. NO PRINCIPAL WITHOUT SUCCESS — `principal` is populated ONLY on
27
+ * `outcome === 'authenticated'`; every other path omits it.
28
+ * 4. FAIL-CLOSED ERRORS — any resolver/hasher/verifier throw becomes a generic
29
+ * `rejected` result, never a raw throw that could leak a 500 / resource
30
+ * existence.
31
+ * 5. NO SECRET LEAKAGE — the plaintext, the stored hash, the TOTP secret are
32
+ * NEVER logged nor placed in a result/`reason`.
33
+ *
34
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
35
+ */
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.createAuthenticator = createAuthenticator;
38
+ const totp_js_1 = require("./totp.js");
39
+ /** The Internal source the engine mints principals through (canonical claims). */
40
+ const INTERNAL_SOURCE = 'internal';
41
+ /**
42
+ * A single, GENERIC rejection reason for EVERY credential-failure path
43
+ * (unknown user, wrong password, unsatisfied/failed factor error). It never
44
+ * distinguishes existence or which check failed — anti-enumeration (§1). MFA and
45
+ * hard-error paths use their own equally-generic reasons below.
46
+ */
47
+ const REASON_INVALID_CREDENTIALS = 'invalid_credentials';
48
+ const REASON_MFA_REQUIRED = 'mfa_required';
49
+ const REASON_AUTH_UNAVAILABLE = 'authentication_unavailable';
50
+ /**
51
+ * A decoy Argon2id-shaped hash the engine verifies against when NO credential was
52
+ * resolved (unknown hint). Its ONLY purpose is to make the hasher do a full,
53
+ * representative unit of work so unknown-user timing ≈ wrong-password timing
54
+ * (§2). It is a fixed, non-secret constant that matches no real password. The
55
+ * concrete hasher parses it as a normal encoded hash and returns `false`.
56
+ */
57
+ const DECOY_PASSWORD_HASH = '$argon2id$v=19$m=19456,t=2,p=1$c2hpZWxkZGVjb3lzYWx0MDAwMA$0000000000000000000000000000000000000000000';
58
+ /** A frozen "rejected, generic reason, no principal" result. */
59
+ function rejected() {
60
+ return Object.freeze({
61
+ outcome: 'rejected',
62
+ satisfiedFactors: Object.freeze([]),
63
+ reason: REASON_INVALID_CREDENTIALS,
64
+ });
65
+ }
66
+ /** A frozen "authentication_unavailable" result (fail-closed on hard error). */
67
+ function unavailable() {
68
+ return Object.freeze({
69
+ outcome: 'rejected',
70
+ satisfiedFactors: Object.freeze([]),
71
+ reason: REASON_AUTH_UNAVAILABLE,
72
+ });
73
+ }
74
+ /** Extract the presented password (string) from a `password` credential. */
75
+ function presentedPassword(credentials) {
76
+ const cred = credentials.find((c) => c.factor === 'password');
77
+ const pw = cred?.payload?.password;
78
+ return typeof pw === 'string' ? pw : undefined;
79
+ }
80
+ /** All non-password credentials presented, indexed by factor (first wins). */
81
+ function presentedFactor(credentials, factor) {
82
+ return credentials.find((c) => c.factor === factor);
83
+ }
84
+ /**
85
+ * The concrete engine. Stateless per call; holds only its injected capabilities.
86
+ * Instances come from {@link createAuthenticator}.
87
+ */
88
+ class AuthenticatorImpl {
89
+ hasher;
90
+ resolver;
91
+ identityBroker;
92
+ factorVerifiers;
93
+ constructor(hasher, resolver, identityBroker, factorVerifiers) {
94
+ this.hasher = hasher;
95
+ this.resolver = resolver;
96
+ this.identityBroker = identityBroker;
97
+ this.factorVerifiers = factorVerifiers;
98
+ }
99
+ async authenticate(identityHint, credentials) {
100
+ try {
101
+ return await this.attempt(identityHint, credentials);
102
+ }
103
+ catch {
104
+ // §4 FAIL-CLOSED: ANY unexpected throw (resolver outage, hasher fault,
105
+ // verifier bug, broker reject) → a generic rejection, never a raw throw.
106
+ // We deliberately swallow the error object so nothing about it can leak.
107
+ return unavailable();
108
+ }
109
+ }
110
+ async attempt(identityHint, credentials) {
111
+ const password = presentedPassword(credentials);
112
+ // Resolve the hint. `null` = unknown principal (anti-enumeration): we do NOT
113
+ // early-return — we still perform an equivalent hash verify below so the
114
+ // unknown-user path costs the same as the wrong-password path (§2).
115
+ const resolved = await this.resolver.resolve(identityHint);
116
+ if (resolved === null) {
117
+ // §2 ANTI-TIMING: burn a representative verify against the decoy hash. The
118
+ // result is discarded — the outcome is ALWAYS a generic rejection.
119
+ await this.hasher.verify(DECOY_PASSWORD_HASH, password ?? '');
120
+ return rejected();
121
+ }
122
+ // A resolved principal but no presented password → still a generic rejection
123
+ // AFTER a dummy verify (keep timing uniform; never reveal "missing password").
124
+ if (password === undefined) {
125
+ await this.hasher.verify(resolved.passwordHash, '');
126
+ return rejected();
127
+ }
128
+ // §1 verify the password. Wrong → generic rejection (indistinguishable from
129
+ // the unknown-user path above).
130
+ //
131
+ // FAIL-CLOSED OVER THE PORT (defense-in-depth): the injected PasswordHasher is
132
+ // a capability the engine does NOT control. Gate on STRICT `=== true`, never
133
+ // truthiness — a misbehaving/hostile hasher returning a truthy non-boolean
134
+ // (`"false"`, `1`, `{}`, `[]`) must NOT mint a principal. Only a genuine
135
+ // boolean `true` passes; everything else rejects.
136
+ const ok = (await this.hasher.verify(resolved.passwordHash, password)) === true;
137
+ if (!ok) {
138
+ return rejected();
139
+ }
140
+ // Password satisfied. Evaluate required factors.
141
+ const satisfiedFactors = ['password'];
142
+ const required = resolved.requiredFactors ?? [];
143
+ for (const req of required) {
144
+ const verifier = this.factorVerifiers.resolve(req.factor);
145
+ const presented = presentedFactor(credentials, req.factor);
146
+ // No verifier wired for a required factor → fail-closed: the factor can
147
+ // never be satisfied, so the attempt cannot proceed. Surfaced as a step-up
148
+ // request (not a hard reject) so the caller can present the factor once
149
+ // wiring exists — but WITHOUT a principal.
150
+ if (verifier === undefined) {
151
+ return mfaRequired(satisfiedFactors, req.factor);
152
+ }
153
+ // Required factor not presented in THIS attempt → step-up (mfa_required),
154
+ // NO principal (§3). The caller re-submits with the factor.
155
+ if (presented === undefined) {
156
+ return mfaRequired(satisfiedFactors, req.factor);
157
+ }
158
+ const verdict = await verifier.verify(presented, req.secret);
159
+ // FAIL-CLOSED OVER THE PORT (defense-in-depth, same rule as the password
160
+ // gate): a factor counts as satisfied ONLY on a STRICT boolean `true`. A
161
+ // misbehaving/hostile FactorVerifier returning a truthy non-boolean
162
+ // `satisfied` (`"false"`, `1`, `{}`, `[]`) must NOT bypass MFA — treat it as
163
+ // NOT satisfied → generic rejection, no principal.
164
+ if (verdict.satisfied !== true) {
165
+ // A PRESENTED-but-WRONG (or non-strict-true) factor is a rejection (a bad
166
+ // code, not a missing one) — generic reason, no principal.
167
+ return rejected();
168
+ }
169
+ satisfiedFactors.push(req.factor);
170
+ }
171
+ // §3 FULL success → mint the Principal via the Identity broker (reuse its
172
+ // tenant-binding + root-safety; do NOT fabricate). A broker reject
173
+ // (malformed claims, missing tenant) propagates to the outer catch →
174
+ // fail-closed `authentication_unavailable` (never a partial/unsafe principal).
175
+ const principal = await this.identityBroker.normalize({
176
+ source: INTERNAL_SOURCE,
177
+ claims: resolved.claims,
178
+ });
179
+ return Object.freeze({
180
+ outcome: 'authenticated',
181
+ principal,
182
+ satisfiedFactors: Object.freeze([...satisfiedFactors]),
183
+ });
184
+ }
185
+ }
186
+ /**
187
+ * A frozen `mfa_required` result — NO principal (§3), generic reason. Names the
188
+ * outstanding factor only in the machine `reason` suffix so a caller can drive
189
+ * the step-up UX; it reveals nothing about the user beyond "another factor is
190
+ * needed" (which the caller already knows it must present).
191
+ */
192
+ function mfaRequired(satisfiedFactors, outstanding) {
193
+ return Object.freeze({
194
+ outcome: 'mfa_required',
195
+ satisfiedFactors: Object.freeze([...satisfiedFactors]),
196
+ reason: `${REASON_MFA_REQUIRED}:${outstanding}`,
197
+ });
198
+ }
199
+ /**
200
+ * Wire the injected capabilities and return an object implementing the FROZEN
201
+ * {@link Authenticator}. The engine's public entry point (mirrors
202
+ * `createIdentityBroker`).
203
+ */
204
+ function createAuthenticator(options) {
205
+ const registry = new totp_js_1.FactorVerifierRegistry();
206
+ for (const verifier of options.factorVerifiers ?? []) {
207
+ registry.register(verifier);
208
+ }
209
+ return new AuthenticatorImpl(options.hasher, options.resolver, options.identityBroker, registry);
210
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * The **CredentialResolver PORT** — resolves an `identityHint` (username / email)
4
+ * to the stored credential material + the claims needed to build a `Principal`.
5
+ *
6
+ * This is the seam between the pure Authentication engine and the deployment's
7
+ * credential store (a DB, a directory, a secrets service). The engine never
8
+ * touches storage; it asks the resolver for a `ResolvedCredential` and works
9
+ * purely with the returned record. ADR-0003: the resolver is INJECTED, so the
10
+ * Core takes on no DB/framework dependency.
11
+ *
12
+ * ANTI-ENUMERATION (security-critical): an unknown hint MUST resolve to `null`,
13
+ * NOT throw. The engine handles a `null` with the SAME generic rejection AND the
14
+ * same amount of work (a dummy hash verify) it does for a *wrong password*, so a
15
+ * caller cannot distinguish "no such user" from "bad password" by response
16
+ * content OR by timing. The resolver therefore never encodes existence in an
17
+ * error; `null` is the single, uniform "no credential" signal.
18
+ *
19
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * Engine seam: **Authentication** — proves the identity.
4
+ *
5
+ * Establishes that the caller is who the {@link Principal} claims to be (Argon2id,
6
+ * MFA, WebAuthn — 010_Architecture §2). This seam names the contract only; the
7
+ * factor implementations are a later layer.
8
+ *
9
+ * The FROZEN public types below (ADR-0023, semver) are the seam — DO NOT change
10
+ * them. The ENGINE that implements this seam (the password-hasher + credential-
11
+ * resolver + factor-verifier PORTs, the reference TOTP verifier, and the
12
+ * `createAuthenticator` factory) lives in the sibling files re-exported at the
13
+ * bottom of this barrel (flows out through `src/index.ts`).
14
+ *
15
+ * ADR-0003: framework-agnostic.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
29
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ // --- Engine implementation behind the FROZEN seam above (this layer) ----------
33
+ // The PasswordHasher PORT (concrete Argon2id ships in @astram/guard — Core stays
34
+ // zero-dep):
35
+ __exportStar(require("./password-hasher.js"), exports);
36
+ // The CredentialResolver PORT (hint → stored credential + claims; null = unknown,
37
+ // anti-enumeration):
38
+ __exportStar(require("./credential-resolver.js"), exports);
39
+ // The factor-verifier CONTRACT + registry + reference TOTP verifier (HMAC injected):
40
+ __exportStar(require("./totp.js"), exports);
41
+ // The Authentication engine + the `createAuthenticator` factory:
42
+ __exportStar(require("./authenticator.js"), exports);
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * The **PasswordHasher PORT** — the framework-agnostic contract the
4
+ * Authentication engine uses to verify a password credential, WITHOUT the engine
5
+ * ever knowing which algorithm backs it.
6
+ *
7
+ * ADR-0003 (zero-dep Core): the concrete hasher is a real dependency (Argon2id
8
+ * needs the `argon2` npm package + native bindings), so it CANNOT live here. The
9
+ * Core defines only this interface; `@astram/guard` ships
10
+ * `Argon2idPasswordHasher implements PasswordHasher` and INJECTS it into
11
+ * `createAuthenticator`. This keeps `@astram/core` at ZERO runtime dependencies
12
+ * (the load-bearing invariant) while the algorithm stays swappable.
13
+ *
14
+ * SECURITY — the engine NEVER logs, renders, or returns the hash or the
15
+ * plaintext. Both are transient inputs to `verify`; neither is ever surfaced in
16
+ * an `AuthenticationResult`, a `reason`, or a log line. A `PasswordHasher`
17
+ * implementation MUST likewise not log its arguments.
18
+ *
19
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });