@blamejs/core 0.7.18 → 0.7.20

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 (169) hide show
  1. package/CHANGELOG.md +427 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +350 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +399 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/fetch-metadata.js +129 -0
  86. package/lib/middleware/health.js +392 -392
  87. package/lib/middleware/index.js +85 -79
  88. package/lib/middleware/rate-limit.js +358 -358
  89. package/lib/middleware/request-id.js +61 -61
  90. package/lib/middleware/request-log.js +168 -168
  91. package/lib/middleware/require-auth.js +104 -104
  92. package/lib/middleware/security-headers.js +121 -116
  93. package/lib/middleware/sse.js +166 -166
  94. package/lib/migrations.js +383 -383
  95. package/lib/mtls-ca.js +518 -518
  96. package/lib/mtls-engine-default.js +481 -481
  97. package/lib/network-dns.js +632 -632
  98. package/lib/network-heartbeat.js +290 -290
  99. package/lib/network-nts.js +574 -574
  100. package/lib/network-proxy.js +265 -265
  101. package/lib/network-tls.js +328 -328
  102. package/lib/network.js +233 -233
  103. package/lib/notify.js +612 -612
  104. package/lib/ntp-check.js +229 -229
  105. package/lib/numeric-bounds.js +111 -111
  106. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  107. package/lib/object-store/azure-blob.js +488 -488
  108. package/lib/object-store/gcs-bucket-ops.js +351 -351
  109. package/lib/object-store/gcs.js +519 -519
  110. package/lib/object-store/http-put.js +153 -153
  111. package/lib/object-store/index.js +197 -197
  112. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  113. package/lib/object-store/sigv4.js +903 -903
  114. package/lib/observability.js +151 -151
  115. package/lib/otel-export.js +269 -269
  116. package/lib/pagination.js +464 -464
  117. package/lib/parsers/index.js +80 -80
  118. package/lib/parsers/safe-env.js +642 -642
  119. package/lib/parsers/safe-ini.js +292 -292
  120. package/lib/parsers/safe-toml.js +784 -784
  121. package/lib/parsers/safe-xml.js +390 -390
  122. package/lib/parsers/safe-yaml.js +1015 -1015
  123. package/lib/permissions.js +708 -708
  124. package/lib/pqc-agent.js +87 -87
  125. package/lib/pqc-gate.js +279 -279
  126. package/lib/protobuf-encoder.js +190 -190
  127. package/lib/protocol-dispatcher.js +161 -161
  128. package/lib/pubsub-redis.js +167 -167
  129. package/lib/pubsub.js +429 -429
  130. package/lib/queue-local.js +476 -476
  131. package/lib/queue-redis.js +745 -745
  132. package/lib/queue-sqs.js +319 -319
  133. package/lib/queue.js +695 -695
  134. package/lib/redis-client.js +519 -519
  135. package/lib/request-helpers.js +340 -340
  136. package/lib/restore-bundle.js +237 -237
  137. package/lib/restore-rollback.js +259 -259
  138. package/lib/restore.js +409 -409
  139. package/lib/retry.js +376 -376
  140. package/lib/router.js +748 -748
  141. package/lib/safe-async.js +735 -735
  142. package/lib/safe-buffer.js +237 -237
  143. package/lib/safe-json.js +541 -541
  144. package/lib/safe-schema.js +1266 -1266
  145. package/lib/safe-url.js +159 -159
  146. package/lib/scheduler.js +706 -706
  147. package/lib/security-assert.js +373 -373
  148. package/lib/seeders.js +618 -618
  149. package/lib/session.js +535 -478
  150. package/lib/slug.js +269 -269
  151. package/lib/ssrf-guard.js +401 -401
  152. package/lib/static.js +7 -5
  153. package/lib/storage.js +471 -471
  154. package/lib/subject.js +281 -281
  155. package/lib/template.js +791 -791
  156. package/lib/testing.js +798 -798
  157. package/lib/time.js +310 -310
  158. package/lib/totp.js +302 -302
  159. package/lib/tracing.js +494 -494
  160. package/lib/uuid.js +132 -132
  161. package/lib/validate-opts.js +340 -340
  162. package/lib/vault/index.js +308 -308
  163. package/lib/vault/rotate.js +784 -784
  164. package/lib/vault/wrap.js +296 -296
  165. package/lib/vendor/noble-ciphers.cjs +9 -9
  166. package/lib/webhook.js +595 -595
  167. package/lib/websocket.js +1048 -1048
  168. package/package.json +77 -77
  169. package/sbom.cyclonedx.json +7 -7
@@ -1,594 +1,628 @@
1
- "use strict";
2
- /**
3
- * Argon2id password hashing — public framework primitive.
4
- *
5
- * Different concern from lib/vault-wrap.js, which also uses Argon2id but
6
- * for KEK derivation (the output is a KEY used to AEAD-wrap the vault
7
- * file). This module is for application-layer password storage: the
8
- * output is a verifiable digest in PHC format, never decrypted, used
9
- * for "is this the password the user originally set?".
10
- *
11
- * Public API:
12
- *
13
- * await auth.password.hash(plain, opts?) → string (PHC format)
14
- * await auth.password.verify(hash, plain) → boolean
15
- * auth.password.needsRehash(hash, opts?) → boolean
16
- *
17
- * The PHC string captures the algorithm + parameters + salt + digest:
18
- *
19
- * $argon2id$v=19$m=65536,t=3,p=4$<base64-salt>$<base64-hash>
20
- *
21
- * That string is what callers store in the database. verify() parses
22
- * it to recover the parameters, recomputes the digest with the
23
- * supplied plaintext, and timing-safe compares.
24
- *
25
- * Defaults (memoryCost=64 MiB, timeCost=3, parallelism=4) target
26
- * ~250–500ms on commodity 2026 hardware — painful for offline brute
27
- * force, tolerable inside a login latency budget. Operators with
28
- * tighter budgets (or beefier hardware) tune via opts; needsRehash
29
- * surfaces when stored hashes lag behind the current defaults so the
30
- * caller can transparently rehash on next successful login.
31
- *
32
- * Validation posture:
33
- * - plain must be a non-empty string. Empty/whitespace passwords
34
- * are operator bugs (UI should reject) — failing here surfaces
35
- * them before they hit the DB.
36
- * - plain length is capped at 4096 bytes (UTF-8). Same cap as the
37
- * vault-wrap passphrase. A 5 GiB string fed to Argon2 would peg
38
- * the box for minutes; the cap is sanity, not security.
39
- * - hash must be a non-empty string starting with `$argon2id$`.
40
- * Other Argon2 variants (`$argon2i$` / `$argon2d$`) are out of
41
- * spec for this framework — verify() returns false rather than
42
- * attempting to validate them. Callers using needsRehash on a
43
- * non-id hash get true (forces rehash on next login).
44
- *
45
- * Errors are AuthError(code, message) with permanent=true. A failed
46
- * verify is NOT an error — it returns false. Errors are reserved for
47
- * "the call shape was wrong" (empty plain, oversize plain).
48
- */
49
- var argon2 = require("../vendor/argon2");
50
- var C = require("../constants");
51
- var httpClient = require("../http-client");
52
- var hibpSha1 = require("../framework-sha1-hibp");
53
- var safeUrl = require("../safe-url");
54
- var timingSafeEqual = require("../crypto").timingSafeEqual;
55
- var { AuthError } = require("../framework-error");
56
-
57
- // Tuning targets ~250–500ms on commodity 2026 hardware. memoryCost
58
- // is in KiB per Argon2's parameter convention. 64 MiB expressed as
59
- // KiB through C.BYTES.kib so the framework's byte math has a single
60
- // source of truth.
61
- var DEFAULT_PARAMS = Object.freeze({
62
- memoryCost: C.BYTES.kib(64), // 64 MiB
63
- timeCost: 3,
64
- parallelism: 4,
65
- });
66
-
67
- // Plaintext upper bound. NIST 800-63B requires >= 64 chars; 4 KiB is
68
- // the framework's defense against amplification attacks (a hostile
69
- // caller submitting a multi-megabyte "password" would otherwise burn
70
- // Argon2 cycles for no security gain).
71
- var MAX_PLAINTEXT_BYTES = C.BYTES.kib(4);
72
-
73
- // ---- Policy primitive ----------------------------------------------
74
- //
75
- // Argon2id covers the OFFLINE attack model: even with the DB stolen,
76
- // each guess costs ~250ms of CPU + 64 MiB of RAM. It does NOT cover:
77
- // - Online weak-credential attacks (operator phishes / reuses)
78
- // - Periodic rotation requirements (PCI 8.3, NYDFS, some HIPAA)
79
- // - History reuse (PCI 8.3 last-4 floor)
80
- // - Operator-tunable composition rules (HIPAA / industry-specific
81
- // where AAL2-equivalent posture is mandated)
82
- //
83
- // b.auth.password.policy(opts) returns:
84
- // - check(plaintext, context?) → presentation-time gate
85
- // - shouldRotate(passwordSetAt) → per-account rotation check
86
- // - reuseProhibited(plaintext, history)→ history-reuse check
87
- //
88
- // Standards mapped:
89
- // - NIST 800-63B §5.1.1.2: 8-char min floor, 64-char min max,
90
- // breach check, NO MANDATORY composition. (Default posture.)
91
- // - PCI-DSS 8.3.6 / 8.3.7: 12-char min, 90-day rotation, history
92
- // of 4. (Operator opts in via { profile: "pci-8.3" }.)
93
- // - HIPAA 164.308(a)(5)(ii)(D): "procedures for creating, changing,
94
- // and safeguarding passwords" — addressed via composition opts.
95
- // - GDPR Art. 32: storage shape (sealed via Argon2id); no
96
- // additional policy requirement here.
97
- // - NYDFS 23 NYCRR 500.12 / NIST AAL2: rotation + breach + length.
98
- //
99
- // The defaults follow NIST 800-63B (no mandatory composition,
100
- // length-and-breach over rules). Every other regime layers on
101
- // opt-in opts; the framework refuses to surprise an operator who
102
- // followed the defaults.
103
- //
104
- // var policy = b.auth.password.policy({
105
- // minLength: 12,
106
- // breachCheck: "haveibeenpwned",
107
- // mustRotateAfterMs: C.TIME.days(90), // PCI 8.3.9
108
- // historyMinDistance: 4, // PCI 8.3.7
109
- // complexity: {
110
- // minCategories: 0, // NIST: don't enforce. opt in for HIPAA-flavoured.
111
- // categories: ["lower", "upper", "digit", "special"],
112
- // minRunRepeat: 3, // reject "aaaa…"
113
- // minSequenceLength: 3, // reject "abcd"/"1234"
114
- // },
115
- // dictionary: ["companyName", "productName"],
116
- // });
117
- //
118
- // await policy.check(plain, { email, username, deny: [...], passwordSetAt });
119
- // policy.shouldRotate(passwordSetAt);
120
- // await policy.reuseProhibited(plain, [oldHash1, oldHash2, oldHash3]);
121
- //
122
- // breachCheck:"haveibeenpwned" uses the HIBP k-anonymity API; the
123
- // SHA-1 hash is computed in-process via lib/framework-sha1-hibp.js
124
- // (NOT exported on b.crypto — see comment in lib/crypto.js). Only
125
- // the first 5 hex chars cross the wire. Rate-limit and failure-mode
126
- // are operator's call: an HIBP outage returns
127
- // { ok: true, breachCheckSkipped: true } by default; failClosed:true
128
- // rejects.
129
- var DEFAULT_POLICY = Object.freeze({
130
- minLength: 0x08, // NIST floor — hex literal form
131
- maxLength: MAX_PLAINTEXT_BYTES,
132
- forbidCommon: [],
133
- // The bundled top-10000 list ships in lib/vendor/common-passwords-top-10000.txt
134
- // (SecLists, CC-BY-3.0). Set false to skip — operators with a richer
135
- // breach-list (HIBP downloads, NCSC 100k) layered via forbidCommon
136
- // typically leave this on; it's additive.
137
- useBundledCommon: true,
138
- denyContextSubstrings: true,
139
- breachCheck: null, // null | "haveibeenpwned"
140
- breachThreshold: 1,
141
- failClosed: false,
142
- hibpEndpoint: "https://api.pwnedpasswords.com",
143
- hibpTimeoutMs: C.TIME.seconds(1.5),
144
- // Rotation policy (PCI 8.3.9 / NYDFS / industry-specific). null = no rotation.
145
- mustRotateAfterMs: null,
146
- // History reuse (PCI 8.3.7 floor: last-4). 0 = disabled.
147
- // Operator passes the actual stored hash list to reuseProhibited().
148
- historyMinDistance: 0,
149
- // Composition rules (NIST 800-63B explicitly says NOT to enforce
150
- // these; HIPAA / older standards still ask for them. Default is OFF
151
- // so the NIST-aligned posture is the default; operators opt in.)
152
- complexity: null,
153
- // Dictionary terms forbidden as substrings (operator brand names,
154
- // product names, etc.). Substring match, case-insensitive. Empty
155
- // by default.
156
- dictionary: [],
157
- });
158
-
159
- var COMPLEXITY_DEFAULT = Object.freeze({
160
- minCategories: 0, // NIST default off; HIPAA-flavoured ops set 3 or 4
161
- categories: ["lower", "upper", "digit", "special"],
162
- minRunRepeat: 0, // reject N+ identical chars in a row; 0 = off
163
- minSequenceLength: 0, // reject N+ ascending or descending chars; 0 = off
164
- });
165
-
166
- // Predefined profiles operators can opt into. Each spreads onto the
167
- // policy opts so the operator can still override individual fields.
168
- var POLICY_PROFILES = Object.freeze({
169
- // NIST 800-63B AAL2 baseline — length + breach, no composition.
170
- // §5.1.1.2 mandates an 8-character floor; routed through C.BYTES.bytes
171
- // so every length-shaped integer in the framework reads through the
172
- // same single source of truth.
173
- "nist-aal2": Object.freeze({
174
- minLength: C.BYTES.bytes(8),
175
- breachCheck: "haveibeenpwned",
176
- }),
177
- // PCI-DSS 4.0 §8.3 — 12-char min, 90-day rotation, history of 4.
178
- // Composition is NOT required by PCI 4.0 (it dropped the older
179
- // version's composition rule); breach check + length covers it.
180
- "pci-4.0": Object.freeze({
181
- minLength: 12,
182
- breachCheck: "haveibeenpwned",
183
- mustRotateAfterMs: C.TIME.days(90),
184
- historyMinDistance: 4,
185
- }),
186
- // HIPAA 164.308 — "procedures for creating, changing, and
187
- // safeguarding". The standard is intentionally vague; the
188
- // commonly-implemented profile pairs length + composition +
189
- // rotation + lockout (lockout is b.auth.lockout, separate
190
- // primitive).
191
- "hipaa-aal2": Object.freeze({
192
- minLength: 12,
193
- breachCheck: "haveibeenpwned",
194
- mustRotateAfterMs: C.TIME.days(180),
195
- historyMinDistance: 4,
196
- complexity: {
197
- minCategories: 3,
198
- minRunRepeat: 3,
199
- minSequenceLength: 3,
200
- },
201
- }),
202
- });
203
-
204
- // Top-10000 common-password set vendored from SecLists
205
- // (CC-BY-3.0 by Daniel Miessler). Loaded lazily on first policy.check
206
- // call — keeps boot fast for apps that never invoke the dictionary.
207
- // Operators wanting deeper enforcement supply opts.forbidCommon (set
208
- // of additional plaintexts) and/or opts.forbidCommonExtra (operator's
209
- // own breach list); both layer additively on top of the bundled set.
210
- var path = require("node:path");
211
- var fs = require("node:fs");
212
- var _bundledCommonPasswords = null;
213
- function _loadBundledCommon() {
214
- if (_bundledCommonPasswords) return _bundledCommonPasswords;
215
- var p = path.join(__dirname, "..", "vendor", "common-passwords-top-10000.txt");
216
- var text = fs.readFileSync(p, "utf8");
217
- var set = new Set();
218
- var lines = text.split(/\r?\n/);
219
- for (var i = 0; i < lines.length; i++) {
220
- var line = lines[i].trim();
221
- if (line.length > 0) set.add(line.toLowerCase());
222
- }
223
- _bundledCommonPasswords = set;
224
- return _bundledCommonPasswords;
225
- }
226
- function _commonPasswordsSize() {
227
- return _loadBundledCommon().size;
228
- }
229
-
230
- function _ok(extra) { return Object.assign({ ok: true }, extra || {}); }
231
- function _fail(code, message) {
232
- return { ok: false, code: "policy/" + code, message: message };
233
- }
234
-
235
- // Argon2id verify with a known stored hash — used by reuseProhibited
236
- // to compare a candidate plaintext against history entries without
237
- // the operator having to wire verify() per row.
238
- async function _argon2Verify(stored, plaintext) {
239
- if (typeof stored !== "string" || stored.indexOf("$argon2id$") !== 0) return false;
240
- try { return await argon2.verify(stored, plaintext); }
241
- catch (_e) { return false; }
242
- }
243
-
244
- function _hasCategory(plaintext, category) {
245
- if (category === "lower") return /[a-z]/.test(plaintext);
246
- if (category === "upper") return /[A-Z]/.test(plaintext);
247
- if (category === "digit") return /[0-9]/.test(plaintext);
248
- if (category === "special") return /[^A-Za-z0-9]/.test(plaintext);
249
- return false;
250
- }
251
-
252
- function _hasRunOfLength(plaintext, n) {
253
- if (n < 2) return false;
254
- for (var i = 0; i + n <= plaintext.length; i++) {
255
- var c = plaintext.charCodeAt(i);
256
- var allSame = true;
257
- for (var j = 1; j < n; j++) {
258
- if (plaintext.charCodeAt(i + j) !== c) { allSame = false; break; }
259
- }
260
- if (allSame) return true;
261
- }
262
- return false;
263
- }
264
-
265
- function _hasSequenceOfLength(plaintext, n) {
266
- if (n < 3) return false;
267
- for (var i = 0; i + n <= plaintext.length; i++) {
268
- var ascending = true, descending = true;
269
- for (var j = 1; j < n; j++) {
270
- var diff = plaintext.charCodeAt(i + j) - plaintext.charCodeAt(i + j - 1);
271
- if (diff !== 1) ascending = false;
272
- if (diff !== -1) descending = false;
273
- }
274
- if (ascending || descending) return true;
275
- }
276
- return false;
277
- }
278
-
279
- function policy(opts) {
280
- opts = opts || {};
281
- // Apply named profile FIRST, then operator opts on top so the
282
- // operator can override profile defaults per-field.
283
- if (typeof opts.profile === "string" && opts.profile.length > 0) {
284
- if (!POLICY_PROFILES[opts.profile]) {
285
- throw new AuthError("auth-password/bad-policy",
286
- "policy.profile must be one of " + Object.keys(POLICY_PROFILES).join("/") +
287
- ", got " + JSON.stringify(opts.profile));
288
- }
289
- opts = Object.assign({}, POLICY_PROFILES[opts.profile], opts);
290
- delete opts.profile;
291
- }
292
- var p = Object.assign({}, DEFAULT_POLICY, opts);
293
- if (typeof p.minLength !== "number" || p.minLength < 1 || p.minLength > MAX_PLAINTEXT_BYTES) {
294
- throw new AuthError("auth-password/bad-policy",
295
- "policy.minLength must be in [1, " + MAX_PLAINTEXT_BYTES + "]");
296
- }
297
- if (typeof p.maxLength !== "number" || p.maxLength < p.minLength || p.maxLength > MAX_PLAINTEXT_BYTES) {
298
- throw new AuthError("auth-password/bad-policy",
299
- "policy.maxLength must be in [minLength, " + MAX_PLAINTEXT_BYTES + "]");
300
- }
301
- if (p.breachCheck !== null && p.breachCheck !== "haveibeenpwned") {
302
- throw new AuthError("auth-password/bad-policy",
303
- "policy.breachCheck must be null or 'haveibeenpwned', got " + JSON.stringify(p.breachCheck));
304
- }
305
- if (p.hibpEndpoint) {
306
- safeUrl.parse(p.hibpEndpoint, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS, errorClass: AuthError });
307
- }
308
- if (p.mustRotateAfterMs !== null &&
309
- (typeof p.mustRotateAfterMs !== "number" || !isFinite(p.mustRotateAfterMs) || p.mustRotateAfterMs <= 0)) {
310
- throw new AuthError("auth-password/bad-policy",
311
- "policy.mustRotateAfterMs must be a positive finite number or null");
312
- }
313
- if (typeof p.historyMinDistance !== "number" || !isFinite(p.historyMinDistance) ||
314
- p.historyMinDistance < 0 || Math.floor(p.historyMinDistance) !== p.historyMinDistance) {
315
- throw new AuthError("auth-password/bad-policy",
316
- "policy.historyMinDistance must be a non-negative integer");
317
- }
318
- if (p.complexity !== null && typeof p.complexity !== "object") {
319
- throw new AuthError("auth-password/bad-policy",
320
- "policy.complexity must be null or an object");
321
- }
322
- var complexity = p.complexity ? Object.assign({}, COMPLEXITY_DEFAULT, p.complexity) : null;
323
- if (complexity) {
324
- if (typeof complexity.minCategories !== "number" || complexity.minCategories < 0 ||
325
- complexity.minCategories > complexity.categories.length) {
326
- throw new AuthError("auth-password/bad-policy",
327
- "policy.complexity.minCategories must be in [0, " + complexity.categories.length + "]");
328
- }
329
- for (var ci = 0; ci < complexity.categories.length; ci++) {
330
- if (["lower", "upper", "digit", "special"].indexOf(complexity.categories[ci]) === -1) {
331
- throw new AuthError("auth-password/bad-policy",
332
- "policy.complexity.categories[" + ci + "] must be lower / upper / digit / special, got " +
333
- JSON.stringify(complexity.categories[ci]));
334
- }
335
- }
336
- }
337
- var forbidLower = (Array.isArray(p.forbidCommon) ? p.forbidCommon : [])
338
- .map(function (s) { return String(s).toLowerCase(); });
339
- var bundledSet = p.useBundledCommon === false ? null : _loadBundledCommon();
340
- var dictionaryLower = (Array.isArray(p.dictionary) ? p.dictionary : [])
341
- .filter(function (s) { return typeof s === "string" && s.length >= 3; })
342
- .map(function (s) { return s.toLowerCase(); });
343
-
344
- async function check(plaintext, context) {
345
- if (typeof plaintext !== "string") {
346
- return _fail("bad-input", "plaintext must be a string");
347
- }
348
- var byteLen = Buffer.byteLength(plaintext, "utf8");
349
- if (byteLen < p.minLength) {
350
- return _fail("too-short", "plaintext is shorter than " + p.minLength + " bytes");
351
- }
352
- if (byteLen > p.maxLength) {
353
- return _fail("too-long", "plaintext exceeds " + p.maxLength + " bytes");
354
- }
355
- var lower = plaintext.toLowerCase();
356
- if (bundledSet && bundledSet.has(lower)) {
357
- return _fail("forbidden-common", "plaintext matches a known breached / common password (bundled top-10000)");
358
- }
359
- for (var i = 0; i < forbidLower.length; i++) {
360
- if (lower === forbidLower[i]) {
361
- return _fail("forbidden-common", "plaintext matches a known weak / common password");
362
- }
363
- }
364
- for (var di2 = 0; di2 < dictionaryLower.length; di2++) {
365
- if (lower.indexOf(dictionaryLower[di2]) !== -1) {
366
- return _fail("forbidden-dictionary",
367
- "plaintext contains a forbidden dictionary term");
368
- }
369
- }
370
- if (p.denyContextSubstrings && context) {
371
- var deny = [];
372
- if (typeof context.email === "string" && context.email.length > 0) {
373
- deny.push(context.email.toLowerCase());
374
- var at = context.email.indexOf("@");
375
- if (at > 0) deny.push(context.email.slice(0, at).toLowerCase());
376
- }
377
- if (typeof context.username === "string" && context.username.length > 0) {
378
- deny.push(context.username.toLowerCase());
379
- }
380
- if (Array.isArray(context.deny)) {
381
- for (var di = 0; di < context.deny.length; di++) {
382
- if (typeof context.deny[di] === "string" && context.deny[di].length >= 3) {
383
- deny.push(context.deny[di].toLowerCase());
384
- }
385
- }
386
- }
387
- for (var dj = 0; dj < deny.length; dj++) {
388
- if (deny[dj].length >= 3 && lower.indexOf(deny[dj]) !== -1) {
389
- return _fail("contains-context",
390
- "plaintext contains a forbidden context substring (account identifier or operator-supplied deny string)");
391
- }
392
- }
393
- }
394
- if (complexity) {
395
- if (complexity.minCategories > 0) {
396
- var hits = 0;
397
- for (var cc = 0; cc < complexity.categories.length; cc++) {
398
- if (_hasCategory(plaintext, complexity.categories[cc])) hits++;
399
- }
400
- if (hits < complexity.minCategories) {
401
- return _fail("complexity-categories",
402
- "plaintext uses " + hits + " character categories; policy requires at least " +
403
- complexity.minCategories + " of [" + complexity.categories.join(", ") + "]");
404
- }
405
- }
406
- if (complexity.minRunRepeat >= 2 && _hasRunOfLength(plaintext, complexity.minRunRepeat)) {
407
- return _fail("complexity-run",
408
- "plaintext contains " + complexity.minRunRepeat + "+ identical consecutive characters");
409
- }
410
- if (complexity.minSequenceLength >= 3 && _hasSequenceOfLength(plaintext, complexity.minSequenceLength)) {
411
- return _fail("complexity-sequence",
412
- "plaintext contains a " + complexity.minSequenceLength + "+-char ascending or descending sequence");
413
- }
414
- }
415
- if (p.breachCheck === "haveibeenpwned") {
416
- // HIBP k-anonymity: send the first 5 hex chars of the SHA-1
417
- // hash, scan the returned suffix list. The framework's only
418
- // SHA-1 usage; HIBP requires it. (See lib/framework-sha1-hibp.js
419
- // for the restriction rationale.)
420
- var sha1Full = hibpSha1.sha1Hex(plaintext).toUpperCase();
421
- var prefix = sha1Full.slice(0, 5);
422
- var suffix = sha1Full.slice(5);
423
- var url = p.hibpEndpoint.replace(/\/+$/, "") + "/range/" + prefix;
424
- var resp;
425
- try {
426
- resp = await httpClient.request({
427
- method: "GET",
428
- url: url,
429
- headers: { "User-Agent": "blamejs-password-policy/1" },
430
- idleTimeoutMs: p.hibpTimeoutMs,
431
- errorClass: AuthError,
432
- });
433
- } catch (e) {
434
- if (p.failClosed) {
435
- return _fail("breach-check-failed",
436
- "HIBP lookup failed and policy is fail-closed: " + ((e && e.message) || String(e)));
437
- }
438
- return _ok({ breachCheckSkipped: true,
439
- breachCheckSkipReason: (e && e.message) || String(e) });
440
- }
441
- if (resp.statusCode !== 200 || !resp.body) {
442
- if (p.failClosed) {
443
- return _fail("breach-check-failed",
444
- "HIBP returned status " + resp.statusCode + " with no body");
445
- }
446
- return _ok({ breachCheckSkipped: true,
447
- breachCheckSkipReason: "hibp-status-" + resp.statusCode });
448
- }
449
- var bodyText = Buffer.isBuffer(resp.body) ? resp.body.toString("utf8") : String(resp.body);
450
- var lines = bodyText.split(/\r?\n/);
451
- for (var li = 0; li < lines.length; li++) {
452
- var line = lines[li].trim();
453
- if (line.length === 0) continue;
454
- var colon = line.indexOf(":");
455
- if (colon < 0) continue;
456
- var hashSuffix = line.slice(0, colon).toUpperCase();
457
- var count = parseInt(line.slice(colon + 1), 10);
458
- if (timingSafeEqual(Buffer.from(hashSuffix, "utf8"), Buffer.from(suffix, "utf8")) &&
459
- isFinite(count) && count >= p.breachThreshold) {
460
- return _fail("breached",
461
- "plaintext appears in HaveIBeenPwned with count " + count +
462
- " (threshold " + p.breachThreshold + ")");
463
- }
464
- }
465
- return _ok({ breachCheckCount: 0 });
466
- }
467
- return _ok();
468
- }
469
-
470
- function shouldRotate(passwordSetAt, now) {
471
- if (p.mustRotateAfterMs === null) return false;
472
- if (typeof passwordSetAt !== "number" || !isFinite(passwordSetAt)) {
473
- throw new AuthError("auth-password/bad-input",
474
- "shouldRotate: passwordSetAt must be a numeric ms-epoch timestamp");
475
- }
476
- var nowMs = typeof now === "number" ? now : Date.now();
477
- return (nowMs - passwordSetAt) >= p.mustRotateAfterMs;
478
- }
479
-
480
- async function reuseProhibited(plaintext, history) {
481
- if (typeof plaintext !== "string" || plaintext.length === 0) return false;
482
- if (p.historyMinDistance <= 0) return false;
483
- if (!Array.isArray(history) || history.length === 0) return false;
484
- // Check the most-recent N entries (history-min-distance bound).
485
- var checkCount = Math.min(history.length, p.historyMinDistance);
486
- for (var i = 0; i < checkCount; i++) {
487
- if (await _argon2Verify(history[i], plaintext)) return true;
488
- }
489
- return false;
490
- }
491
-
492
- return {
493
- check: check,
494
- shouldRotate: shouldRotate,
495
- reuseProhibited: reuseProhibited,
496
- // Operator introspection — handy when an admin tool wants to
497
- // surface "your policy requires X" to end users.
498
- describe: function () {
499
- return {
500
- minLength: p.minLength,
501
- maxLength: p.maxLength,
502
- breachCheck: p.breachCheck,
503
- mustRotateAfterMs: p.mustRotateAfterMs,
504
- historyMinDistance: p.historyMinDistance,
505
- complexity: complexity ? Object.assign({}, complexity) : null,
506
- dictionaryCount: dictionaryLower.length,
507
- forbidCommonCount: forbidLower.length,
508
- bundledCommonCount: bundledSet ? bundledSet.size : 0,
509
- };
510
- },
511
- };
512
- }
513
-
514
- function _validatePlain(plain) {
515
- if (typeof plain !== "string" || plain.length === 0) {
516
- throw new AuthError("auth-password/invalid-plain",
517
- "auth.password.hash requires a non-empty string");
518
- }
519
- if (Buffer.byteLength(plain, "utf8") > MAX_PLAINTEXT_BYTES) {
520
- throw new AuthError("auth-password/plain-too-large",
521
- "plaintext exceeds " + MAX_PLAINTEXT_BYTES + " bytes (UTF-8)");
522
- }
523
- }
524
-
525
- function _resolveParams(opts) {
526
- var p = Object.assign({}, DEFAULT_PARAMS, opts || {});
527
- if (typeof p.memoryCost !== "number" || p.memoryCost < C.BYTES.kib(1)) {
528
- throw new AuthError("auth-password/bad-params",
529
- "memoryCost must be >= 1024 KiB (1 MiB)");
530
- }
531
- if (typeof p.timeCost !== "number" || p.timeCost < 1) {
532
- throw new AuthError("auth-password/bad-params", "timeCost must be >= 1");
533
- }
534
- if (typeof p.parallelism !== "number" || p.parallelism < 1) {
535
- throw new AuthError("auth-password/bad-params", "parallelism must be >= 1");
536
- }
537
- return p;
538
- }
539
-
540
- async function hash(plain, opts) {
541
- _validatePlain(plain);
542
- var p = _resolveParams(opts);
543
- return await argon2.hash(plain, {
544
- type: argon2.argon2id,
545
- memoryCost: p.memoryCost,
546
- timeCost: p.timeCost,
547
- parallelism: p.parallelism,
548
- });
549
- }
550
-
551
- async function verify(stored, plain) {
552
- // verify intentionally tolerates malformed input by returning false
553
- // rather than throwing — login flows already treat false as "credentials
554
- // didn't match" and shouldn't have to wrap each call in try/catch.
555
- if (typeof stored !== "string" || stored.length === 0) return false;
556
- if (typeof plain !== "string" || plain.length === 0) return false;
557
- if (!stored.indexOf || stored.indexOf("$argon2id$") !== 0) return false;
558
- if (Buffer.byteLength(plain, "utf8") > MAX_PLAINTEXT_BYTES) return false;
559
- try {
560
- return await argon2.verify(stored, plain);
561
- } catch (_e) {
562
- // PHC-string parse failures from the vendor surface as throws —
563
- // treat as "doesn't match" so a corrupted DB column can't break
564
- // login flows with an unexpected exception type.
565
- return false;
566
- }
567
- }
568
-
569
- function needsRehash(stored, opts) {
570
- if (typeof stored !== "string" || stored.indexOf("$argon2id$") !== 0) {
571
- // Non-id variant or malformed — force rehash on next successful login
572
- return true;
573
- }
574
- var p = _resolveParams(opts);
575
- try {
576
- return argon2.needsRehash(stored, {
577
- memoryCost: p.memoryCost,
578
- timeCost: p.timeCost,
579
- parallelism: p.parallelism,
580
- });
581
- } catch (_e) {
582
- return true; // unparseable → rehash
583
- }
584
- }
585
-
586
- module.exports = {
587
- hash: hash,
588
- verify: verify,
589
- needsRehash: needsRehash,
590
- policy: policy,
591
- DEFAULT_PARAMS: DEFAULT_PARAMS,
592
- DEFAULT_POLICY: DEFAULT_POLICY,
593
- POLICY_PROFILES: POLICY_PROFILES,
594
- };
1
+ "use strict";
2
+ /**
3
+ * Argon2id password hashing — public framework primitive.
4
+ *
5
+ * Different concern from lib/vault-wrap.js, which also uses Argon2id but
6
+ * for KEK derivation (the output is a KEY used to AEAD-wrap the vault
7
+ * file). This module is for application-layer password storage: the
8
+ * output is a verifiable digest in PHC format, never decrypted, used
9
+ * for "is this the password the user originally set?".
10
+ *
11
+ * Public API:
12
+ *
13
+ * await auth.password.hash(plain, opts?) → string (PHC format)
14
+ * await auth.password.verify(hash, plain) → boolean
15
+ * auth.password.needsRehash(hash, opts?) → boolean
16
+ *
17
+ * The PHC string captures the algorithm + parameters + salt + digest:
18
+ *
19
+ * $argon2id$v=19$m=65536,t=3,p=4$<base64-salt>$<base64-hash>
20
+ *
21
+ * That string is what callers store in the database. verify() parses
22
+ * it to recover the parameters, recomputes the digest with the
23
+ * supplied plaintext, and timing-safe compares.
24
+ *
25
+ * Defaults (memoryCost=64 MiB, timeCost=3, parallelism=4) target
26
+ * ~250–500ms on commodity 2026 hardware — painful for offline brute
27
+ * force, tolerable inside a login latency budget. Operators with
28
+ * tighter budgets (or beefier hardware) tune via opts; needsRehash
29
+ * surfaces when stored hashes lag behind the current defaults so the
30
+ * caller can transparently rehash on next successful login.
31
+ *
32
+ * Validation posture:
33
+ * - plain must be a non-empty string. Empty/whitespace passwords
34
+ * are operator bugs (UI should reject) — failing here surfaces
35
+ * them before they hit the DB.
36
+ * - plain length is capped at 4096 bytes (UTF-8). Same cap as the
37
+ * vault-wrap passphrase. A 5 GiB string fed to Argon2 would peg
38
+ * the box for minutes; the cap is sanity, not security.
39
+ * - hash must be a non-empty string starting with `$argon2id$`.
40
+ * Other Argon2 variants (`$argon2i$` / `$argon2d$`) are out of
41
+ * spec for this framework — verify() returns false rather than
42
+ * attempting to validate them. Callers using needsRehash on a
43
+ * non-id hash get true (forces rehash on next login).
44
+ *
45
+ * Errors are AuthError(code, message) with permanent=true. A failed
46
+ * verify is NOT an error — it returns false. Errors are reserved for
47
+ * "the call shape was wrong" (empty plain, oversize plain).
48
+ */
49
+ var argon2 = require("../vendor/argon2");
50
+ var C = require("../constants");
51
+ var httpClient = require("../http-client");
52
+ var hibpSha1 = require("../framework-sha1-hibp");
53
+ var safeUrl = require("../safe-url");
54
+ var timingSafeEqual = require("../crypto").timingSafeEqual;
55
+ var { AuthError } = require("../framework-error");
56
+
57
+ // Tuning targets ~250–500ms on commodity 2026 hardware. memoryCost
58
+ // is in KiB per Argon2's parameter convention. 64 MiB expressed as
59
+ // KiB through C.BYTES.kib so the framework's byte math has a single
60
+ // source of truth.
61
+ var DEFAULT_PARAMS = Object.freeze({
62
+ memoryCost: C.BYTES.kib(64), // 64 MiB
63
+ timeCost: 3,
64
+ parallelism: 4,
65
+ });
66
+
67
+ // Plaintext upper bound. NIST 800-63B requires >= 64 chars; 4 KiB is
68
+ // the framework's defense against amplification attacks (a hostile
69
+ // caller submitting a multi-megabyte "password" would otherwise burn
70
+ // Argon2 cycles for no security gain).
71
+ var MAX_PLAINTEXT_BYTES = C.BYTES.kib(4);
72
+
73
+ // ---- Policy primitive ----------------------------------------------
74
+ //
75
+ // Argon2id covers the OFFLINE attack model: even with the DB stolen,
76
+ // each guess costs ~250ms of CPU + 64 MiB of RAM. It does NOT cover:
77
+ // - Online weak-credential attacks (operator phishes / reuses)
78
+ // - Periodic rotation requirements (PCI 8.3, NYDFS, some HIPAA)
79
+ // - History reuse (PCI 8.3 last-4 floor)
80
+ // - Operator-tunable composition rules (HIPAA / industry-specific
81
+ // where AAL2-equivalent posture is mandated)
82
+ //
83
+ // b.auth.password.policy(opts) returns:
84
+ // - check(plaintext, context?) → presentation-time gate
85
+ // - shouldRotate(passwordSetAt) → per-account rotation check
86
+ // - reuseProhibited(plaintext, history)→ history-reuse check
87
+ //
88
+ // Standards mapped:
89
+ // - NIST 800-63B §5.1.1.2: 8-char min floor, 64-char min max,
90
+ // breach check, NO MANDATORY composition. (Default posture.)
91
+ // - PCI-DSS 8.3.6 / 8.3.7: 12-char min, 90-day rotation, history
92
+ // of 4. (Operator opts in via { profile: "pci-8.3" }.)
93
+ // - HIPAA 164.308(a)(5)(ii)(D): "procedures for creating, changing,
94
+ // and safeguarding passwords" — addressed via composition opts.
95
+ // - GDPR Art. 32: storage shape (sealed via Argon2id); no
96
+ // additional policy requirement here.
97
+ // - NYDFS 23 NYCRR 500.12 / NIST AAL2: rotation + breach + length.
98
+ //
99
+ // The defaults follow NIST 800-63B (no mandatory composition,
100
+ // length-and-breach over rules). Every other regime layers on
101
+ // opt-in opts; the framework refuses to surprise an operator who
102
+ // followed the defaults.
103
+ //
104
+ // var policy = b.auth.password.policy({
105
+ // minLength: 12,
106
+ // breachCheck: "haveibeenpwned",
107
+ // mustRotateAfterMs: C.TIME.days(90), // PCI 8.3.9
108
+ // historyMinDistance: 4, // PCI 8.3.7
109
+ // complexity: {
110
+ // minCategories: 0, // NIST: don't enforce. opt in for HIPAA-flavoured.
111
+ // categories: ["lower", "upper", "digit", "special"],
112
+ // minRunRepeat: 3, // reject "aaaa…"
113
+ // minSequenceLength: 3, // reject "abcd"/"1234"
114
+ // },
115
+ // dictionary: ["companyName", "productName"],
116
+ // });
117
+ //
118
+ // await policy.check(plain, { email, username, deny: [...], passwordSetAt });
119
+ // policy.shouldRotate(passwordSetAt);
120
+ // await policy.reuseProhibited(plain, [oldHash1, oldHash2, oldHash3]);
121
+ //
122
+ // breachCheck:"haveibeenpwned" uses the HIBP k-anonymity API; the
123
+ // SHA-1 hash is computed in-process via lib/framework-sha1-hibp.js
124
+ // (NOT exported on b.crypto — see comment in lib/crypto.js). Only
125
+ // the first 5 hex chars cross the wire. Rate-limit and failure-mode
126
+ // are operator's call: an HIBP outage returns
127
+ // { ok: true, breachCheckSkipped: true } by default; failClosed:true
128
+ // rejects.
129
+ var DEFAULT_POLICY = Object.freeze({
130
+ minLength: 0x08, // NIST floor — hex literal form
131
+ maxLength: MAX_PLAINTEXT_BYTES,
132
+ forbidCommon: [],
133
+ // The bundled top-10000 list ships in lib/vendor/common-passwords-top-10000.txt
134
+ // (SecLists, CC-BY-3.0). Set false to skip — operators with a richer
135
+ // breach-list (HIBP downloads, NCSC 100k) layered via forbidCommon
136
+ // typically leave this on; it's additive.
137
+ useBundledCommon: true,
138
+ denyContextSubstrings: true,
139
+ breachCheck: null, // null | "haveibeenpwned"
140
+ breachThreshold: 1,
141
+ failClosed: false,
142
+ hibpEndpoint: "https://api.pwnedpasswords.com",
143
+ hibpTimeoutMs: C.TIME.seconds(1.5),
144
+ // Rotation policy (PCI 8.3.9 / NYDFS / industry-specific). null = no rotation.
145
+ mustRotateAfterMs: null,
146
+ // History reuse (PCI 8.3.7 floor: last-4). 0 = disabled.
147
+ // Operator passes the actual stored hash list to reuseProhibited().
148
+ historyMinDistance: 0,
149
+ // Composition rules (NIST 800-63B explicitly says NOT to enforce
150
+ // these; HIPAA / older standards still ask for them. Default is OFF
151
+ // so the NIST-aligned posture is the default; operators opt in.)
152
+ complexity: null,
153
+ // Dictionary terms forbidden as substrings (operator brand names,
154
+ // product names, etc.). Substring match, case-insensitive. Empty
155
+ // by default.
156
+ dictionary: [],
157
+ });
158
+
159
+ var COMPLEXITY_DEFAULT = Object.freeze({
160
+ minCategories: 0, // NIST default off; HIPAA-flavoured ops set 3 or 4
161
+ categories: ["lower", "upper", "digit", "special"],
162
+ minRunRepeat: 0, // reject N+ identical chars in a row; 0 = off
163
+ minSequenceLength: 0, // reject N+ ascending or descending chars; 0 = off
164
+ });
165
+
166
+ // Predefined profiles operators can opt into. Each spreads onto the
167
+ // policy opts so the operator can still override individual fields.
168
+ var POLICY_PROFILES = Object.freeze({
169
+ // NIST 800-63B AAL2 baseline — length + breach, no composition.
170
+ // §5.1.1.2 mandates an 8-character floor; routed through C.BYTES.bytes
171
+ // so every length-shaped integer in the framework reads through the
172
+ // same single source of truth.
173
+ "nist-aal2": Object.freeze({
174
+ minLength: C.BYTES.bytes(8),
175
+ breachCheck: "haveibeenpwned",
176
+ }),
177
+ // PCI-DSS 4.0 §8.3 — 12-char min, 90-day rotation, history of 4.
178
+ // Composition is NOT required by PCI 4.0 (it dropped the older
179
+ // version's composition rule); breach check + length covers it.
180
+ "pci-4.0": Object.freeze({
181
+ minLength: 12,
182
+ breachCheck: "haveibeenpwned",
183
+ mustRotateAfterMs: C.TIME.days(90),
184
+ historyMinDistance: 4,
185
+ }),
186
+ // HIPAA 164.308 — "procedures for creating, changing, and
187
+ // safeguarding". The standard is intentionally vague; the
188
+ // commonly-implemented profile pairs length + composition +
189
+ // rotation + lockout (lockout is b.auth.lockout, separate
190
+ // primitive).
191
+ "hipaa-aal2": Object.freeze({
192
+ minLength: 12,
193
+ breachCheck: "haveibeenpwned",
194
+ mustRotateAfterMs: C.TIME.days(180),
195
+ historyMinDistance: 4,
196
+ complexity: {
197
+ minCategories: 3,
198
+ minRunRepeat: 3,
199
+ minSequenceLength: 3,
200
+ },
201
+ }),
202
+ });
203
+
204
+ // Top-10000 common-password set vendored from SecLists
205
+ // (CC-BY-3.0 by Daniel Miessler). Loaded lazily on first policy.check
206
+ // call — keeps boot fast for apps that never invoke the dictionary.
207
+ // Operators wanting deeper enforcement supply opts.forbidCommon (set
208
+ // of additional plaintexts) and/or opts.forbidCommonExtra (operator's
209
+ // own breach list); both layer additively on top of the bundled set.
210
+ var path = require("node:path");
211
+ var fs = require("node:fs");
212
+ var _bundledCommonPasswords = null;
213
+ function _loadBundledCommon() {
214
+ if (_bundledCommonPasswords) return _bundledCommonPasswords;
215
+ var p = path.join(__dirname, "..", "vendor", "common-passwords-top-10000.txt");
216
+ var text = fs.readFileSync(p, "utf8");
217
+ var set = new Set();
218
+ var lines = text.split(/\r?\n/);
219
+ for (var i = 0; i < lines.length; i++) {
220
+ var line = lines[i].trim();
221
+ if (line.length > 0) set.add(line.toLowerCase());
222
+ }
223
+ _bundledCommonPasswords = set;
224
+ return _bundledCommonPasswords;
225
+ }
226
+ function _commonPasswordsSize() {
227
+ return _loadBundledCommon().size;
228
+ }
229
+
230
+ function _ok(extra) { return Object.assign({ ok: true }, extra || {}); }
231
+ function _fail(code, message) {
232
+ return { ok: false, code: "policy/" + code, message: message };
233
+ }
234
+
235
+ // Argon2id verify with a known stored hash — used by reuseProhibited
236
+ // to compare a candidate plaintext against history entries without
237
+ // the operator having to wire verify() per row.
238
+ async function _argon2Verify(stored, plaintext) {
239
+ if (typeof stored !== "string" || stored.indexOf("$argon2id$") !== 0) return false;
240
+ try { return await argon2.verify(stored, plaintext); }
241
+ catch (_e) { return false; }
242
+ }
243
+
244
+ function _hasCategory(plaintext, category) {
245
+ if (category === "lower") return /[a-z]/.test(plaintext);
246
+ if (category === "upper") return /[A-Z]/.test(plaintext);
247
+ if (category === "digit") return /[0-9]/.test(plaintext);
248
+ if (category === "special") return /[^A-Za-z0-9]/.test(plaintext);
249
+ return false;
250
+ }
251
+
252
+ function _hasRunOfLength(plaintext, n) {
253
+ if (n < 2) return false;
254
+ for (var i = 0; i + n <= plaintext.length; i++) {
255
+ var c = plaintext.charCodeAt(i);
256
+ var allSame = true;
257
+ for (var j = 1; j < n; j++) {
258
+ if (plaintext.charCodeAt(i + j) !== c) { allSame = false; break; }
259
+ }
260
+ if (allSame) return true;
261
+ }
262
+ return false;
263
+ }
264
+
265
+ function _hasSequenceOfLength(plaintext, n) {
266
+ if (n < 3) return false;
267
+ for (var i = 0; i + n <= plaintext.length; i++) {
268
+ var ascending = true, descending = true;
269
+ for (var j = 1; j < n; j++) {
270
+ var diff = plaintext.charCodeAt(i + j) - plaintext.charCodeAt(i + j - 1);
271
+ if (diff !== 1) ascending = false;
272
+ if (diff !== -1) descending = false;
273
+ }
274
+ if (ascending || descending) return true;
275
+ }
276
+ return false;
277
+ }
278
+
279
+ function policy(opts) {
280
+ opts = opts || {};
281
+ // Apply named profile FIRST, then operator opts on top so the
282
+ // operator can override profile defaults per-field.
283
+ if (typeof opts.profile === "string" && opts.profile.length > 0) {
284
+ if (!POLICY_PROFILES[opts.profile]) {
285
+ throw new AuthError("auth-password/bad-policy",
286
+ "policy.profile must be one of " + Object.keys(POLICY_PROFILES).join("/") +
287
+ ", got " + JSON.stringify(opts.profile));
288
+ }
289
+ opts = Object.assign({}, POLICY_PROFILES[opts.profile], opts);
290
+ delete opts.profile;
291
+ }
292
+ var p = Object.assign({}, DEFAULT_POLICY, opts);
293
+ if (typeof p.minLength !== "number" || p.minLength < 1 || p.minLength > MAX_PLAINTEXT_BYTES) {
294
+ throw new AuthError("auth-password/bad-policy",
295
+ "policy.minLength must be in [1, " + MAX_PLAINTEXT_BYTES + "]");
296
+ }
297
+ if (typeof p.maxLength !== "number" || p.maxLength < p.minLength || p.maxLength > MAX_PLAINTEXT_BYTES) {
298
+ throw new AuthError("auth-password/bad-policy",
299
+ "policy.maxLength must be in [minLength, " + MAX_PLAINTEXT_BYTES + "]");
300
+ }
301
+ if (p.breachCheck !== null && p.breachCheck !== "haveibeenpwned") {
302
+ throw new AuthError("auth-password/bad-policy",
303
+ "policy.breachCheck must be null or 'haveibeenpwned', got " + JSON.stringify(p.breachCheck));
304
+ }
305
+ if (p.hibpEndpoint) {
306
+ safeUrl.parse(p.hibpEndpoint, { allowedProtocols: safeUrl.ALLOW_HTTP_TLS, errorClass: AuthError });
307
+ }
308
+ if (p.mustRotateAfterMs !== null &&
309
+ (typeof p.mustRotateAfterMs !== "number" || !isFinite(p.mustRotateAfterMs) || p.mustRotateAfterMs <= 0)) {
310
+ throw new AuthError("auth-password/bad-policy",
311
+ "policy.mustRotateAfterMs must be a positive finite number or null");
312
+ }
313
+ if (typeof p.historyMinDistance !== "number" || !isFinite(p.historyMinDistance) ||
314
+ p.historyMinDistance < 0 || Math.floor(p.historyMinDistance) !== p.historyMinDistance) {
315
+ throw new AuthError("auth-password/bad-policy",
316
+ "policy.historyMinDistance must be a non-negative integer");
317
+ }
318
+ if (p.complexity !== null && typeof p.complexity !== "object") {
319
+ throw new AuthError("auth-password/bad-policy",
320
+ "policy.complexity must be null or an object");
321
+ }
322
+ var complexity = p.complexity ? Object.assign({}, COMPLEXITY_DEFAULT, p.complexity) : null;
323
+ if (complexity) {
324
+ if (typeof complexity.minCategories !== "number" || complexity.minCategories < 0 ||
325
+ complexity.minCategories > complexity.categories.length) {
326
+ throw new AuthError("auth-password/bad-policy",
327
+ "policy.complexity.minCategories must be in [0, " + complexity.categories.length + "]");
328
+ }
329
+ for (var ci = 0; ci < complexity.categories.length; ci++) {
330
+ if (["lower", "upper", "digit", "special"].indexOf(complexity.categories[ci]) === -1) {
331
+ throw new AuthError("auth-password/bad-policy",
332
+ "policy.complexity.categories[" + ci + "] must be lower / upper / digit / special, got " +
333
+ JSON.stringify(complexity.categories[ci]));
334
+ }
335
+ }
336
+ }
337
+ var forbidLower = (Array.isArray(p.forbidCommon) ? p.forbidCommon : [])
338
+ .map(function (s) { return String(s).toLowerCase(); });
339
+ var bundledSet = p.useBundledCommon === false ? null : _loadBundledCommon();
340
+ var dictionaryLower = (Array.isArray(p.dictionary) ? p.dictionary : [])
341
+ .filter(function (s) { return typeof s === "string" && s.length >= 3; })
342
+ .map(function (s) { return s.toLowerCase(); });
343
+
344
+ async function check(plaintext, context) {
345
+ if (typeof plaintext !== "string") {
346
+ return _fail("bad-input", "plaintext must be a string");
347
+ }
348
+ var byteLen = Buffer.byteLength(plaintext, "utf8");
349
+ if (byteLen < p.minLength) {
350
+ return _fail("too-short", "plaintext is shorter than " + p.minLength + " bytes");
351
+ }
352
+ if (byteLen > p.maxLength) {
353
+ return _fail("too-long", "plaintext exceeds " + p.maxLength + " bytes");
354
+ }
355
+ var lower = plaintext.toLowerCase();
356
+ if (bundledSet && bundledSet.has(lower)) {
357
+ return _fail("forbidden-common", "plaintext matches a known breached / common password (bundled top-10000)");
358
+ }
359
+ for (var i = 0; i < forbidLower.length; i++) {
360
+ if (lower === forbidLower[i]) {
361
+ return _fail("forbidden-common", "plaintext matches a known weak / common password");
362
+ }
363
+ }
364
+ for (var di2 = 0; di2 < dictionaryLower.length; di2++) {
365
+ if (lower.indexOf(dictionaryLower[di2]) !== -1) {
366
+ return _fail("forbidden-dictionary",
367
+ "plaintext contains a forbidden dictionary term");
368
+ }
369
+ }
370
+ if (p.denyContextSubstrings && context) {
371
+ var deny = [];
372
+ if (typeof context.email === "string" && context.email.length > 0) {
373
+ deny.push(context.email.toLowerCase());
374
+ var at = context.email.indexOf("@");
375
+ if (at > 0) deny.push(context.email.slice(0, at).toLowerCase());
376
+ }
377
+ if (typeof context.username === "string" && context.username.length > 0) {
378
+ deny.push(context.username.toLowerCase());
379
+ }
380
+ if (Array.isArray(context.deny)) {
381
+ for (var di = 0; di < context.deny.length; di++) {
382
+ if (typeof context.deny[di] === "string" && context.deny[di].length >= 3) {
383
+ deny.push(context.deny[di].toLowerCase());
384
+ }
385
+ }
386
+ }
387
+ for (var dj = 0; dj < deny.length; dj++) {
388
+ if (deny[dj].length >= 3 && lower.indexOf(deny[dj]) !== -1) {
389
+ return _fail("contains-context",
390
+ "plaintext contains a forbidden context substring (account identifier or operator-supplied deny string)");
391
+ }
392
+ }
393
+ }
394
+ if (complexity) {
395
+ if (complexity.minCategories > 0) {
396
+ var hits = 0;
397
+ for (var cc = 0; cc < complexity.categories.length; cc++) {
398
+ if (_hasCategory(plaintext, complexity.categories[cc])) hits++;
399
+ }
400
+ if (hits < complexity.minCategories) {
401
+ return _fail("complexity-categories",
402
+ "plaintext uses " + hits + " character categories; policy requires at least " +
403
+ complexity.minCategories + " of [" + complexity.categories.join(", ") + "]");
404
+ }
405
+ }
406
+ if (complexity.minRunRepeat >= 2 && _hasRunOfLength(plaintext, complexity.minRunRepeat)) {
407
+ return _fail("complexity-run",
408
+ "plaintext contains " + complexity.minRunRepeat + "+ identical consecutive characters");
409
+ }
410
+ if (complexity.minSequenceLength >= 3 && _hasSequenceOfLength(plaintext, complexity.minSequenceLength)) {
411
+ return _fail("complexity-sequence",
412
+ "plaintext contains a " + complexity.minSequenceLength + "+-char ascending or descending sequence");
413
+ }
414
+ }
415
+ if (p.breachCheck === "haveibeenpwned") {
416
+ // HIBP k-anonymity: send the first 5 hex chars of the SHA-1
417
+ // hash, scan the returned suffix list. The framework's only
418
+ // SHA-1 usage; HIBP requires it. (See lib/framework-sha1-hibp.js
419
+ // for the restriction rationale.)
420
+ var sha1Full = hibpSha1.sha1Hex(plaintext).toUpperCase();
421
+ var prefix = sha1Full.slice(0, 5);
422
+ var suffix = sha1Full.slice(5);
423
+ var url = p.hibpEndpoint.replace(/\/+$/, "") + "/range/" + prefix;
424
+ var resp;
425
+ try {
426
+ resp = await httpClient.request({
427
+ method: "GET",
428
+ url: url,
429
+ headers: { "User-Agent": "blamejs-password-policy/1" },
430
+ idleTimeoutMs: p.hibpTimeoutMs,
431
+ errorClass: AuthError,
432
+ });
433
+ } catch (e) {
434
+ if (p.failClosed) {
435
+ return _fail("breach-check-failed",
436
+ "HIBP lookup failed and policy is fail-closed: " + ((e && e.message) || String(e)));
437
+ }
438
+ return _ok({ breachCheckSkipped: true,
439
+ breachCheckSkipReason: (e && e.message) || String(e) });
440
+ }
441
+ if (resp.statusCode !== 200 || !resp.body) {
442
+ if (p.failClosed) {
443
+ return _fail("breach-check-failed",
444
+ "HIBP returned status " + resp.statusCode + " with no body");
445
+ }
446
+ return _ok({ breachCheckSkipped: true,
447
+ breachCheckSkipReason: "hibp-status-" + resp.statusCode });
448
+ }
449
+ var bodyText = Buffer.isBuffer(resp.body) ? resp.body.toString("utf8") : String(resp.body);
450
+ var lines = bodyText.split(/\r?\n/);
451
+ for (var li = 0; li < lines.length; li++) {
452
+ var line = lines[li].trim();
453
+ if (line.length === 0) continue;
454
+ var colon = line.indexOf(":");
455
+ if (colon < 0) continue;
456
+ var hashSuffix = line.slice(0, colon).toUpperCase();
457
+ var count = parseInt(line.slice(colon + 1), 10);
458
+ if (timingSafeEqual(Buffer.from(hashSuffix, "utf8"), Buffer.from(suffix, "utf8")) &&
459
+ isFinite(count) && count >= p.breachThreshold) {
460
+ return _fail("breached",
461
+ "plaintext appears in HaveIBeenPwned with count " + count +
462
+ " (threshold " + p.breachThreshold + ")");
463
+ }
464
+ }
465
+ return _ok({ breachCheckCount: 0 });
466
+ }
467
+ return _ok();
468
+ }
469
+
470
+ function shouldRotate(passwordSetAt, now) {
471
+ if (p.mustRotateAfterMs === null) return false;
472
+ if (typeof passwordSetAt !== "number" || !isFinite(passwordSetAt)) {
473
+ throw new AuthError("auth-password/bad-input",
474
+ "shouldRotate: passwordSetAt must be a numeric ms-epoch timestamp");
475
+ }
476
+ var nowMs = typeof now === "number" ? now : Date.now();
477
+ return (nowMs - passwordSetAt) >= p.mustRotateAfterMs;
478
+ }
479
+
480
+ async function reuseProhibited(plaintext, history) {
481
+ if (typeof plaintext !== "string" || plaintext.length === 0) return false;
482
+ if (p.historyMinDistance <= 0) return false;
483
+ if (!Array.isArray(history) || history.length === 0) return false;
484
+ // Check the most-recent N entries (history-min-distance bound).
485
+ var checkCount = Math.min(history.length, p.historyMinDistance);
486
+ for (var i = 0; i < checkCount; i++) {
487
+ if (await _argon2Verify(history[i], plaintext)) return true;
488
+ }
489
+ return false;
490
+ }
491
+
492
+ return {
493
+ check: check,
494
+ shouldRotate: shouldRotate,
495
+ reuseProhibited: reuseProhibited,
496
+ // Operator introspection — handy when an admin tool wants to
497
+ // surface "your policy requires X" to end users.
498
+ describe: function () {
499
+ return {
500
+ minLength: p.minLength,
501
+ maxLength: p.maxLength,
502
+ breachCheck: p.breachCheck,
503
+ mustRotateAfterMs: p.mustRotateAfterMs,
504
+ historyMinDistance: p.historyMinDistance,
505
+ complexity: complexity ? Object.assign({}, complexity) : null,
506
+ dictionaryCount: dictionaryLower.length,
507
+ forbidCommonCount: forbidLower.length,
508
+ bundledCommonCount: bundledSet ? bundledSet.size : 0,
509
+ };
510
+ },
511
+ };
512
+ }
513
+
514
+ function _validatePlain(plain) {
515
+ if (typeof plain !== "string" || plain.length === 0) {
516
+ throw new AuthError("auth-password/invalid-plain",
517
+ "auth.password.hash requires a non-empty string");
518
+ }
519
+ if (Buffer.byteLength(plain, "utf8") > MAX_PLAINTEXT_BYTES) {
520
+ throw new AuthError("auth-password/plain-too-large",
521
+ "plaintext exceeds " + MAX_PLAINTEXT_BYTES + " bytes (UTF-8)");
522
+ }
523
+ }
524
+
525
+ function _resolveParams(opts) {
526
+ var p = Object.assign({}, DEFAULT_PARAMS, opts || {});
527
+ if (typeof p.memoryCost !== "number" || p.memoryCost < C.BYTES.kib(1)) {
528
+ throw new AuthError("auth-password/bad-params",
529
+ "memoryCost must be >= 1024 KiB (1 MiB)");
530
+ }
531
+ if (typeof p.timeCost !== "number" || p.timeCost < 1) {
532
+ throw new AuthError("auth-password/bad-params", "timeCost must be >= 1");
533
+ }
534
+ if (typeof p.parallelism !== "number" || p.parallelism < 1) {
535
+ throw new AuthError("auth-password/bad-params", "parallelism must be >= 1");
536
+ }
537
+ return p;
538
+ }
539
+
540
+ async function hash(plain, opts) {
541
+ _validatePlain(plain);
542
+ var p = _resolveParams(opts);
543
+ return await argon2.hash(plain, {
544
+ type: argon2.argon2id,
545
+ memoryCost: p.memoryCost,
546
+ timeCost: p.timeCost,
547
+ parallelism: p.parallelism,
548
+ });
549
+ }
550
+
551
+ async function verify(stored, plain) {
552
+ // verify intentionally tolerates malformed input by returning false
553
+ // rather than throwing — login flows already treat false as "credentials
554
+ // didn't match" and shouldn't have to wrap each call in try/catch.
555
+ if (typeof stored !== "string" || stored.length === 0) return false;
556
+ if (typeof plain !== "string" || plain.length === 0) return false;
557
+ if (!stored.indexOf || stored.indexOf("$argon2id$") !== 0) return false;
558
+ if (Buffer.byteLength(plain, "utf8") > MAX_PLAINTEXT_BYTES) return false;
559
+ try {
560
+ return await argon2.verify(stored, plain);
561
+ } catch (_e) {
562
+ // PHC-string parse failures from the vendor surface as throws —
563
+ // treat as "doesn't match" so a corrupted DB column can't break
564
+ // login flows with an unexpected exception type.
565
+ return false;
566
+ }
567
+ }
568
+
569
+ function needsRehash(stored, opts) {
570
+ if (typeof stored !== "string" || stored.indexOf("$argon2id$") !== 0) {
571
+ // Non-id variant or malformed — force rehash on next successful login
572
+ return true;
573
+ }
574
+ var p = _resolveParams(opts);
575
+ try {
576
+ return argon2.needsRehash(stored, {
577
+ memoryCost: p.memoryCost,
578
+ timeCost: p.timeCost,
579
+ parallelism: p.parallelism,
580
+ });
581
+ } catch (_e) {
582
+ return true; // unparseable → rehash
583
+ }
584
+ }
585
+
586
+ // OWASP 2026 Argon2id minimum floor — operator audit visibility.
587
+ // Any deploy MUST satisfy m >= 19 MiB, t >= 2, p >= 1. params() exposes
588
+ // the active defaults so an operator audit (or compliance scan) can
589
+ // verify the floor without parsing PHC strings out of the database.
590
+ //
591
+ // Argon2 expresses memoryCost in KiB. C.BYTES.kib(19) returns 19456,
592
+ // which argon2 reads as 19456 KiB = 19 MiB — the same shape as the
593
+ // active DEFAULT_PARAMS.memoryCost (C.BYTES.kib(64) = 65536 KiB = 64
594
+ // MiB). timeCost + parallelism are unitless argon2 parameters.
595
+ var OWASP_FLOOR_2026 = Object.freeze({
596
+ memoryCostKib: C.BYTES.kib(19),
597
+ timeCost: 2,
598
+ parallelism: 1,
599
+ });
600
+
601
+ function params() {
602
+ // Active framework defaults plus the OWASP 2026 floor for comparison.
603
+ var active = {
604
+ memoryCostKib: DEFAULT_PARAMS.memoryCost,
605
+ timeCost: DEFAULT_PARAMS.timeCost,
606
+ parallelism: DEFAULT_PARAMS.parallelism,
607
+ };
608
+ return {
609
+ algorithm: "argon2id",
610
+ active: active,
611
+ owaspFloor: OWASP_FLOOR_2026,
612
+ meetsFloor: active.memoryCostKib >= OWASP_FLOOR_2026.memoryCostKib &&
613
+ active.timeCost >= OWASP_FLOOR_2026.timeCost &&
614
+ active.parallelism >= OWASP_FLOOR_2026.parallelism,
615
+ };
616
+ }
617
+
618
+ module.exports = {
619
+ hash: hash,
620
+ verify: verify,
621
+ needsRehash: needsRehash,
622
+ policy: policy,
623
+ params: params,
624
+ DEFAULT_PARAMS: DEFAULT_PARAMS,
625
+ DEFAULT_POLICY: DEFAULT_POLICY,
626
+ POLICY_PROFILES: POLICY_PROFILES,
627
+ OWASP_FLOOR_2026: OWASP_FLOOR_2026,
628
+ };