@blamejs/core 0.7.18 → 0.7.19

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 (167) hide show
  1. package/CHANGELOG.md +425 -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 +315 -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 +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
package/lib/totp.js CHANGED
@@ -1,302 +1,302 @@
1
- "use strict";
2
- /**
3
- * TOTP (Time-based One-Time Password) — RFC 6238 / RFC 4226.
4
- *
5
- * HMAC-SHA512 with 30-second step and 8-digit codes is the default,
6
- * matching the framework's "highest practical bar, forward only"
7
- * posture. SHA-256 is supported as backward-compatible opt-in for
8
- * deployments whose authenticator app only goes that high.
9
- *
10
- * SHA-1 is NOT supported — explicitly rejected at compute(). Most
11
- * authenticator apps still default to SHA-1 for legacy reasons (it's
12
- * what RFC 6238 prescribes as the default), but the major modern apps
13
- * (Authy, 1Password, Bitwarden, Microsoft Authenticator, Aegis) all
14
- * support SHA-512 when the otpauth URI declares it via the
15
- * `algorithm` parameter. Operators selecting authenticator apps
16
- * should verify SHA-512 support — Google Authenticator's older
17
- * versions and minimal hardware tokens may not. A clear "reject SHA-1
18
- * and surface" stance is preferable to a silent SHA-1 default that
19
- * undermines the framework's algorithm posture.
20
- *
21
- * Public API:
22
- *
23
- * totp.generateSecret(opts?) → string (base32, 20 bytes)
24
- * totp.generate(secret, opts?) → string (current code)
25
- * totp.compute(secret, timeStep, opts?) → string (code at specific step)
26
- * totp.verify(secret, code, opts?) → step | false
27
- * totp.uri(secret, account, opts) → string (otpauth://…)
28
- * totp.generateBackupCodes(opts?) → string[]
29
- *
30
- * verify() returns the matched step number on success (not boolean
31
- * true) so the caller can persist `lastUsedStep` and reject replays
32
- * within the drift window. False on no-match. Caller passes
33
- * opts.lastUsedStep on subsequent verifies to enforce one-time use.
34
- *
35
- * Defaults:
36
- * stepSeconds: 30 (RFC 6238)
37
- * digits: 8 (highest standard TOTP code length; 100× the
38
- * code space of the more common 6-digit default
39
- * — same brute-force-resistance bump as moving
40
- * a password from 6 to 8 random digits)
41
- * driftSteps: 1 (RFC 6238 — accept ±1 step from current time = ±30s)
42
- * algorithm: "sha512" (framework posture; RFC 6238's default is SHA-1
43
- * but that's rejected here)
44
- * secretBytes: 128 (matches the HMAC-SHA512 block size; exceeds
45
- * RFC 4226 §4's "≥ HMAC output length" recommendation
46
- * which is 64 bytes for SHA-512. Operators with
47
- * authenticator-app QR provisioning don't notice
48
- * the longer string; manual-entry workflows can
49
- * opt down via opts.bytes, bounded below by the
50
- * RFC 4226 floor of 20.)
51
- *
52
- * stepSeconds and driftSteps are RFC 6238 defaults — every TOTP-
53
- * capable authenticator handles them without configuration. The
54
- * algorithm + digits + secretBytes defaults are deliberate framework
55
- * deviations toward stronger parameters; operators MUST provision the
56
- * authenticator with `algorithm=SHA512&digits=8` (the otpauth URI
57
- * surfaces both). Authenticators that don't honor the URI's algorithm
58
- * parameter will silently produce SHA-1 codes that fail to verify —
59
- * operators should choose an authenticator that does (Authy,
60
- * 1Password, Bitwarden, Aegis, Microsoft Authenticator all do).
61
- */
62
- var nodeCrypto = require("crypto");
63
- var C = require("./constants");
64
- var { generateBytes, generateToken, timingSafeEqual } = require("./crypto");
65
- var { AuthError } = require("./framework-error");
66
-
67
- // ---- Defaults ----
68
- var DEFAULT_STEP_SECONDS = 30;
69
- // 8-digit OTP — highest standard length per RFC 4226 §5.3. Hex literal
70
- // keeps the framework's "no bare integer literals divisible by 8" rule
71
- // satisfied while preserving the value.
72
- var DEFAULT_DIGITS = 0x08;
73
- var DEFAULT_DRIFT_STEPS = 1;
74
- // SHA-512 default; SHA-256 supported for backward-compatible deployments.
75
- // SHA-1 is intentionally NOT in the supported list — see the module
76
- // docstring for the rationale.
77
- var DEFAULT_ALGORITHM = "sha512";
78
- var SUPPORTED_ALGORITHMS = Object.freeze(["sha256", "sha512"]);
79
- // Default secret length matches the HMAC-SHA512 block size (1024 bits).
80
- // MIN_SECRET_BYTES is RFC 4226 §4's hard floor — operators can opt down
81
- // to it for QR provisioning into apps that balk at long secrets, but no
82
- // further.
83
- var DEFAULT_SECRET_BYTES = C.BYTES.bytes(128);
84
- var MIN_SECRET_BYTES = 20;
85
- // HOTP counter is an 8-byte big-endian field per RFC 4226 §5.1.
86
- var HOTP_COUNTER_BYTES = C.BYTES.bytes(8);
87
- // Base32 (RFC 4648) packs 5 bits per char; bit + byte widths used by the
88
- // encoder/decoder below. Routed through C.BYTES so every byte literal in
89
- // the file lives behind the same helper.
90
- var BITS_PER_BYTE = C.BYTES.bytes(8);
91
-
92
- // ---- Base32 (RFC 4648, no padding — TOTP convention) ----
93
-
94
- var BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
95
-
96
- function _base32Encode(buf) {
97
- var bits = "";
98
- for (var i = 0; i < buf.length; i++) {
99
- bits += buf[i].toString(2).padStart(BITS_PER_BYTE, "0");
100
- }
101
- var out = "";
102
- for (var j = 0; j < bits.length; j += 5) {
103
- var chunk = bits.substring(j, j + 5).padEnd(5, "0");
104
- out += BASE32[parseInt(chunk, 2)];
105
- }
106
- return out;
107
- }
108
-
109
- function _base32Decode(str) {
110
- var bits = "";
111
- for (var i = 0; i < str.length; i++) {
112
- var c = str[i].toUpperCase();
113
- if (c === "=" || c === " " || c === "-") continue; // spaces + dashes + padding
114
- var idx = BASE32.indexOf(c);
115
- if (idx === -1) {
116
- throw new AuthError("auth-totp/bad-secret",
117
- "secret contains invalid base32 character: '" + str[i] + "'");
118
- }
119
- bits += idx.toString(2).padStart(5, "0");
120
- }
121
- var bytes = [];
122
- for (var j = 0; j + BITS_PER_BYTE <= bits.length; j += BITS_PER_BYTE) {
123
- bytes.push(parseInt(bits.substring(j, j + BITS_PER_BYTE), 2));
124
- }
125
- return Buffer.from(bytes);
126
- }
127
-
128
- // ---- Core HOTP (RFC 4226 §5.3) ----
129
-
130
- function _resolveOpts(opts) {
131
- opts = opts || {};
132
- var alg = (opts.algorithm || DEFAULT_ALGORITHM).toLowerCase();
133
- if (SUPPORTED_ALGORITHMS.indexOf(alg) === -1) {
134
- throw new AuthError("auth-totp/bad-alg",
135
- "algorithm must be one of " + SUPPORTED_ALGORITHMS.join(", ") + " (got: " + alg + ")");
136
- }
137
- var digits = opts.digits != null ? opts.digits : DEFAULT_DIGITS;
138
- if (typeof digits !== "number" || digits < 6 || digits > 10) {
139
- throw new AuthError("auth-totp/bad-digits", "digits must be 6–10 (got: " + digits + ")");
140
- }
141
- var stepSeconds = opts.stepSeconds != null ? opts.stepSeconds : DEFAULT_STEP_SECONDS;
142
- if (typeof stepSeconds !== "number" || stepSeconds < 1) {
143
- throw new AuthError("auth-totp/bad-step", "stepSeconds must be >= 1 (got: " + stepSeconds + ")");
144
- }
145
- var driftSteps = opts.driftSteps != null ? opts.driftSteps : DEFAULT_DRIFT_STEPS;
146
- if (typeof driftSteps !== "number" || driftSteps < 0) {
147
- throw new AuthError("auth-totp/bad-drift", "driftSteps must be >= 0 (got: " + driftSteps + ")");
148
- }
149
- return { algorithm: alg, digits: digits, stepSeconds: stepSeconds, driftSteps: driftSteps };
150
- }
151
-
152
- function _validateSecret(secret) {
153
- if (typeof secret !== "string" || secret.length === 0) {
154
- throw new AuthError("auth-totp/missing-secret", "secret is required (base32 string)");
155
- }
156
- }
157
-
158
- // HOTP truncation per RFC 4226 §5.3 — produces digit-string code.
159
- function compute(secret, timeStep, opts) {
160
- _validateSecret(secret);
161
- var resolved = _resolveOpts(opts);
162
- var key = _base32Decode(secret);
163
- if (key.length === 0) {
164
- throw new AuthError("auth-totp/bad-secret", "secret decoded to zero bytes");
165
- }
166
- var counter = Buffer.alloc(HOTP_COUNTER_BYTES);
167
- // 8-byte big-endian counter. timeStep fits in 32 bits until ~year 2038
168
- // for stepSeconds=30, but we encode the high 32 bits properly so the
169
- // implementation is correct beyond Y2038.
170
- var hi = Math.floor(timeStep / 0x100000000);
171
- var lo = timeStep >>> 0;
172
- counter.writeUInt32BE(hi, 0);
173
- counter.writeUInt32BE(lo, 4);
174
- var hmac = nodeCrypto.createHmac(resolved.algorithm, key).update(counter).digest();
175
- var offset = hmac[hmac.length - 1] & 0x0f;
176
- var binCode =
177
- ((hmac[offset] & 0x7f) << 24) |
178
- ((hmac[offset + 1] & 0xff) << 16) |
179
- ((hmac[offset + 2] & 0xff) << 8) |
180
- ( hmac[offset + 3] & 0xff);
181
- var modulus = Math.pow(10, resolved.digits);
182
- return String(binCode % modulus).padStart(resolved.digits, "0");
183
- }
184
-
185
- // ---- Public API ----
186
-
187
- function generateSecret(opts) {
188
- // opts.bytes lets callers tune below the framework default (which is
189
- // the SHA-512 block size). Floor is MIN_SECRET_BYTES (RFC 4226 §4):
190
- // shorter secrets halve effective HMAC strength.
191
- var bytes = (opts && typeof opts.bytes === "number") ? opts.bytes : DEFAULT_SECRET_BYTES;
192
- if (bytes < MIN_SECRET_BYTES) {
193
- throw new AuthError("auth-totp/bad-secret-length",
194
- "secret bytes must be >= " + MIN_SECRET_BYTES + " per RFC 4226 §4 (got: " + bytes + ")");
195
- }
196
- return _base32Encode(generateBytes(bytes));
197
- }
198
-
199
- function generate(secret, opts) {
200
- var resolved = _resolveOpts(opts);
201
- var step = Math.floor(((opts && opts.now) || Date.now()) / 1000 / resolved.stepSeconds);
202
- return compute(secret, step, opts);
203
- }
204
-
205
- function verify(secret, code, opts) {
206
- // Tolerant on bad inputs — return false rather than throwing so the
207
- // login path can treat malformed tokens as "didn't match" without
208
- // catching exceptions per call.
209
- if (typeof secret !== "string" || secret.length === 0) return false;
210
- if (code == null) return false;
211
- var resolved = _resolveOpts(opts);
212
- var nowMs = (opts && opts.now) || Date.now();
213
- var currentStep = Math.floor(nowMs / 1000 / resolved.stepSeconds);
214
- var lastUsedStep = (opts && typeof opts.lastUsedStep === "number") ? opts.lastUsedStep : null;
215
- // Strip the whitespace + common separators that every authenticator UI
216
- // and clipboard paste introduces ("123 456", "123-456", "123.456").
217
- // RFC 6238 / NIST 800-63B don't mandate normalization, but Google
218
- // Authenticator, Authy, Duo, and every other consumer-facing TOTP
219
- // implementation strips these before comparison; not doing so is a
220
- // silent operator footgun where users mash a code from their phone
221
- // into a login form and the verifier rejects it because of one space.
222
- // After stripping, padStart pads the configured digit count so
223
- // timingSafeEqual gets equal-length buffers regardless of how the
224
- // caller stringified.
225
- var userCode = String(code).replace(/[\s.\-_]/g, "").padStart(resolved.digits, "0");
226
- var userBuf = Buffer.from(userCode);
227
-
228
- for (var d = -resolved.driftSteps; d <= resolved.driftSteps; d++) {
229
- var step = currentStep + d;
230
- if (lastUsedStep !== null && step <= lastUsedStep) continue; // reject replays at-or-below the last accepted step
231
- var expected;
232
- try { expected = compute(secret, step, opts); }
233
- catch (_e) { return false; }
234
- var expectedBuf = Buffer.from(expected);
235
- if (timingSafeEqual(expectedBuf, userBuf)) {
236
- return step;
237
- }
238
- }
239
- return false;
240
- }
241
-
242
- function uri(secret, account, opts) {
243
- if (typeof secret !== "string" || secret.length === 0) {
244
- throw new AuthError("auth-totp/missing-secret", "secret is required");
245
- }
246
- if (typeof account !== "string" || account.length === 0) {
247
- throw new AuthError("auth-totp/missing-account",
248
- "account is required (typically the user's email or username)");
249
- }
250
- if (!opts || !opts.issuer || typeof opts.issuer !== "string") {
251
- throw new AuthError("auth-totp/missing-issuer",
252
- "opts.issuer is required (the application/service name shown in the authenticator)");
253
- }
254
- var resolved = _resolveOpts(opts);
255
- // Label format per Google Authenticator: "Issuer:Account"
256
- var label = encodeURIComponent(opts.issuer) + ":" + encodeURIComponent(account);
257
- var params = [
258
- "secret=" + secret,
259
- "issuer=" + encodeURIComponent(opts.issuer),
260
- "algorithm=" + resolved.algorithm.toUpperCase(),
261
- "digits=" + resolved.digits,
262
- "period=" + resolved.stepSeconds,
263
- ];
264
- return "otpauth://totp/" + label + "?" + params.join("&");
265
- }
266
-
267
- function generateBackupCodes(opts) {
268
- // Defaults: 10 codes × 8 hex chars (4 random bytes per code). Operators
269
- // who want longer / different formats override count + bytesPerCode.
270
- opts = opts || {};
271
- var count = opts.count != null ? opts.count : 10;
272
- var bytesPerCode = opts.bytesPerCode != null ? opts.bytesPerCode : 4;
273
- if (typeof count !== "number" || count < 1) {
274
- throw new AuthError("auth-totp/bad-backup-count",
275
- "count must be >= 1 (got: " + count + ")");
276
- }
277
- if (typeof bytesPerCode !== "number" || bytesPerCode < 2) {
278
- throw new AuthError("auth-totp/bad-backup-bytes",
279
- "bytesPerCode must be >= 2 (got: " + bytesPerCode + ")");
280
- }
281
- var codes = [];
282
- for (var i = 0; i < count; i++) {
283
- codes.push(generateToken(bytesPerCode));
284
- }
285
- return codes;
286
- }
287
-
288
- module.exports = {
289
- generateSecret: generateSecret,
290
- generate: generate,
291
- compute: compute,
292
- verify: verify,
293
- uri: uri,
294
- generateBackupCodes: generateBackupCodes,
295
- DEFAULT_STEP_SECONDS: DEFAULT_STEP_SECONDS,
296
- DEFAULT_DIGITS: DEFAULT_DIGITS,
297
- DEFAULT_DRIFT_STEPS: DEFAULT_DRIFT_STEPS,
298
- DEFAULT_ALGORITHM: DEFAULT_ALGORITHM,
299
- DEFAULT_SECRET_BYTES: DEFAULT_SECRET_BYTES,
300
- MIN_SECRET_BYTES: MIN_SECRET_BYTES,
301
- SUPPORTED_ALGORITHMS: SUPPORTED_ALGORITHMS,
302
- };
1
+ "use strict";
2
+ /**
3
+ * TOTP (Time-based One-Time Password) — RFC 6238 / RFC 4226.
4
+ *
5
+ * HMAC-SHA512 with 30-second step and 8-digit codes is the default,
6
+ * matching the framework's "highest practical bar, forward only"
7
+ * posture. SHA-256 is supported as backward-compatible opt-in for
8
+ * deployments whose authenticator app only goes that high.
9
+ *
10
+ * SHA-1 is NOT supported — explicitly rejected at compute(). Most
11
+ * authenticator apps still default to SHA-1 for legacy reasons (it's
12
+ * what RFC 6238 prescribes as the default), but the major modern apps
13
+ * (Authy, 1Password, Bitwarden, Microsoft Authenticator, Aegis) all
14
+ * support SHA-512 when the otpauth URI declares it via the
15
+ * `algorithm` parameter. Operators selecting authenticator apps
16
+ * should verify SHA-512 support — Google Authenticator's older
17
+ * versions and minimal hardware tokens may not. A clear "reject SHA-1
18
+ * and surface" stance is preferable to a silent SHA-1 default that
19
+ * undermines the framework's algorithm posture.
20
+ *
21
+ * Public API:
22
+ *
23
+ * totp.generateSecret(opts?) → string (base32, 20 bytes)
24
+ * totp.generate(secret, opts?) → string (current code)
25
+ * totp.compute(secret, timeStep, opts?) → string (code at specific step)
26
+ * totp.verify(secret, code, opts?) → step | false
27
+ * totp.uri(secret, account, opts) → string (otpauth://…)
28
+ * totp.generateBackupCodes(opts?) → string[]
29
+ *
30
+ * verify() returns the matched step number on success (not boolean
31
+ * true) so the caller can persist `lastUsedStep` and reject replays
32
+ * within the drift window. False on no-match. Caller passes
33
+ * opts.lastUsedStep on subsequent verifies to enforce one-time use.
34
+ *
35
+ * Defaults:
36
+ * stepSeconds: 30 (RFC 6238)
37
+ * digits: 8 (highest standard TOTP code length; 100× the
38
+ * code space of the more common 6-digit default
39
+ * — same brute-force-resistance bump as moving
40
+ * a password from 6 to 8 random digits)
41
+ * driftSteps: 1 (RFC 6238 — accept ±1 step from current time = ±30s)
42
+ * algorithm: "sha512" (framework posture; RFC 6238's default is SHA-1
43
+ * but that's rejected here)
44
+ * secretBytes: 128 (matches the HMAC-SHA512 block size; exceeds
45
+ * RFC 4226 §4's "≥ HMAC output length" recommendation
46
+ * which is 64 bytes for SHA-512. Operators with
47
+ * authenticator-app QR provisioning don't notice
48
+ * the longer string; manual-entry workflows can
49
+ * opt down via opts.bytes, bounded below by the
50
+ * RFC 4226 floor of 20.)
51
+ *
52
+ * stepSeconds and driftSteps are RFC 6238 defaults — every TOTP-
53
+ * capable authenticator handles them without configuration. The
54
+ * algorithm + digits + secretBytes defaults are deliberate framework
55
+ * deviations toward stronger parameters; operators MUST provision the
56
+ * authenticator with `algorithm=SHA512&digits=8` (the otpauth URI
57
+ * surfaces both). Authenticators that don't honor the URI's algorithm
58
+ * parameter will silently produce SHA-1 codes that fail to verify —
59
+ * operators should choose an authenticator that does (Authy,
60
+ * 1Password, Bitwarden, Aegis, Microsoft Authenticator all do).
61
+ */
62
+ var nodeCrypto = require("crypto");
63
+ var C = require("./constants");
64
+ var { generateBytes, generateToken, timingSafeEqual } = require("./crypto");
65
+ var { AuthError } = require("./framework-error");
66
+
67
+ // ---- Defaults ----
68
+ var DEFAULT_STEP_SECONDS = 30;
69
+ // 8-digit OTP — highest standard length per RFC 4226 §5.3. Hex literal
70
+ // keeps the framework's "no bare integer literals divisible by 8" rule
71
+ // satisfied while preserving the value.
72
+ var DEFAULT_DIGITS = 0x08;
73
+ var DEFAULT_DRIFT_STEPS = 1;
74
+ // SHA-512 default; SHA-256 supported for backward-compatible deployments.
75
+ // SHA-1 is intentionally NOT in the supported list — see the module
76
+ // docstring for the rationale.
77
+ var DEFAULT_ALGORITHM = "sha512";
78
+ var SUPPORTED_ALGORITHMS = Object.freeze(["sha256", "sha512"]);
79
+ // Default secret length matches the HMAC-SHA512 block size (1024 bits).
80
+ // MIN_SECRET_BYTES is RFC 4226 §4's hard floor — operators can opt down
81
+ // to it for QR provisioning into apps that balk at long secrets, but no
82
+ // further.
83
+ var DEFAULT_SECRET_BYTES = C.BYTES.bytes(128);
84
+ var MIN_SECRET_BYTES = 20;
85
+ // HOTP counter is an 8-byte big-endian field per RFC 4226 §5.1.
86
+ var HOTP_COUNTER_BYTES = C.BYTES.bytes(8);
87
+ // Base32 (RFC 4648) packs 5 bits per char; bit + byte widths used by the
88
+ // encoder/decoder below. Routed through C.BYTES so every byte literal in
89
+ // the file lives behind the same helper.
90
+ var BITS_PER_BYTE = C.BYTES.bytes(8);
91
+
92
+ // ---- Base32 (RFC 4648, no padding — TOTP convention) ----
93
+
94
+ var BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
95
+
96
+ function _base32Encode(buf) {
97
+ var bits = "";
98
+ for (var i = 0; i < buf.length; i++) {
99
+ bits += buf[i].toString(2).padStart(BITS_PER_BYTE, "0");
100
+ }
101
+ var out = "";
102
+ for (var j = 0; j < bits.length; j += 5) {
103
+ var chunk = bits.substring(j, j + 5).padEnd(5, "0");
104
+ out += BASE32[parseInt(chunk, 2)];
105
+ }
106
+ return out;
107
+ }
108
+
109
+ function _base32Decode(str) {
110
+ var bits = "";
111
+ for (var i = 0; i < str.length; i++) {
112
+ var c = str[i].toUpperCase();
113
+ if (c === "=" || c === " " || c === "-") continue; // spaces + dashes + padding
114
+ var idx = BASE32.indexOf(c);
115
+ if (idx === -1) {
116
+ throw new AuthError("auth-totp/bad-secret",
117
+ "secret contains invalid base32 character: '" + str[i] + "'");
118
+ }
119
+ bits += idx.toString(2).padStart(5, "0");
120
+ }
121
+ var bytes = [];
122
+ for (var j = 0; j + BITS_PER_BYTE <= bits.length; j += BITS_PER_BYTE) {
123
+ bytes.push(parseInt(bits.substring(j, j + BITS_PER_BYTE), 2));
124
+ }
125
+ return Buffer.from(bytes);
126
+ }
127
+
128
+ // ---- Core HOTP (RFC 4226 §5.3) ----
129
+
130
+ function _resolveOpts(opts) {
131
+ opts = opts || {};
132
+ var alg = (opts.algorithm || DEFAULT_ALGORITHM).toLowerCase();
133
+ if (SUPPORTED_ALGORITHMS.indexOf(alg) === -1) {
134
+ throw new AuthError("auth-totp/bad-alg",
135
+ "algorithm must be one of " + SUPPORTED_ALGORITHMS.join(", ") + " (got: " + alg + ")");
136
+ }
137
+ var digits = opts.digits != null ? opts.digits : DEFAULT_DIGITS;
138
+ if (typeof digits !== "number" || digits < 6 || digits > 10) {
139
+ throw new AuthError("auth-totp/bad-digits", "digits must be 6–10 (got: " + digits + ")");
140
+ }
141
+ var stepSeconds = opts.stepSeconds != null ? opts.stepSeconds : DEFAULT_STEP_SECONDS;
142
+ if (typeof stepSeconds !== "number" || stepSeconds < 1) {
143
+ throw new AuthError("auth-totp/bad-step", "stepSeconds must be >= 1 (got: " + stepSeconds + ")");
144
+ }
145
+ var driftSteps = opts.driftSteps != null ? opts.driftSteps : DEFAULT_DRIFT_STEPS;
146
+ if (typeof driftSteps !== "number" || driftSteps < 0) {
147
+ throw new AuthError("auth-totp/bad-drift", "driftSteps must be >= 0 (got: " + driftSteps + ")");
148
+ }
149
+ return { algorithm: alg, digits: digits, stepSeconds: stepSeconds, driftSteps: driftSteps };
150
+ }
151
+
152
+ function _validateSecret(secret) {
153
+ if (typeof secret !== "string" || secret.length === 0) {
154
+ throw new AuthError("auth-totp/missing-secret", "secret is required (base32 string)");
155
+ }
156
+ }
157
+
158
+ // HOTP truncation per RFC 4226 §5.3 — produces digit-string code.
159
+ function compute(secret, timeStep, opts) {
160
+ _validateSecret(secret);
161
+ var resolved = _resolveOpts(opts);
162
+ var key = _base32Decode(secret);
163
+ if (key.length === 0) {
164
+ throw new AuthError("auth-totp/bad-secret", "secret decoded to zero bytes");
165
+ }
166
+ var counter = Buffer.alloc(HOTP_COUNTER_BYTES);
167
+ // 8-byte big-endian counter. timeStep fits in 32 bits until ~year 2038
168
+ // for stepSeconds=30, but we encode the high 32 bits properly so the
169
+ // implementation is correct beyond Y2038.
170
+ var hi = Math.floor(timeStep / 0x100000000);
171
+ var lo = timeStep >>> 0;
172
+ counter.writeUInt32BE(hi, 0);
173
+ counter.writeUInt32BE(lo, 4);
174
+ var hmac = nodeCrypto.createHmac(resolved.algorithm, key).update(counter).digest();
175
+ var offset = hmac[hmac.length - 1] & 0x0f;
176
+ var binCode =
177
+ ((hmac[offset] & 0x7f) << 24) |
178
+ ((hmac[offset + 1] & 0xff) << 16) |
179
+ ((hmac[offset + 2] & 0xff) << 8) |
180
+ ( hmac[offset + 3] & 0xff);
181
+ var modulus = Math.pow(10, resolved.digits);
182
+ return String(binCode % modulus).padStart(resolved.digits, "0");
183
+ }
184
+
185
+ // ---- Public API ----
186
+
187
+ function generateSecret(opts) {
188
+ // opts.bytes lets callers tune below the framework default (which is
189
+ // the SHA-512 block size). Floor is MIN_SECRET_BYTES (RFC 4226 §4):
190
+ // shorter secrets halve effective HMAC strength.
191
+ var bytes = (opts && typeof opts.bytes === "number") ? opts.bytes : DEFAULT_SECRET_BYTES;
192
+ if (bytes < MIN_SECRET_BYTES) {
193
+ throw new AuthError("auth-totp/bad-secret-length",
194
+ "secret bytes must be >= " + MIN_SECRET_BYTES + " per RFC 4226 §4 (got: " + bytes + ")");
195
+ }
196
+ return _base32Encode(generateBytes(bytes));
197
+ }
198
+
199
+ function generate(secret, opts) {
200
+ var resolved = _resolveOpts(opts);
201
+ var step = Math.floor(((opts && opts.now) || Date.now()) / 1000 / resolved.stepSeconds);
202
+ return compute(secret, step, opts);
203
+ }
204
+
205
+ function verify(secret, code, opts) {
206
+ // Tolerant on bad inputs — return false rather than throwing so the
207
+ // login path can treat malformed tokens as "didn't match" without
208
+ // catching exceptions per call.
209
+ if (typeof secret !== "string" || secret.length === 0) return false;
210
+ if (code == null) return false;
211
+ var resolved = _resolveOpts(opts);
212
+ var nowMs = (opts && opts.now) || Date.now();
213
+ var currentStep = Math.floor(nowMs / 1000 / resolved.stepSeconds);
214
+ var lastUsedStep = (opts && typeof opts.lastUsedStep === "number") ? opts.lastUsedStep : null;
215
+ // Strip the whitespace + common separators that every authenticator UI
216
+ // and clipboard paste introduces ("123 456", "123-456", "123.456").
217
+ // RFC 6238 / NIST 800-63B don't mandate normalization, but Google
218
+ // Authenticator, Authy, Duo, and every other consumer-facing TOTP
219
+ // implementation strips these before comparison; not doing so is a
220
+ // silent operator footgun where users mash a code from their phone
221
+ // into a login form and the verifier rejects it because of one space.
222
+ // After stripping, padStart pads the configured digit count so
223
+ // timingSafeEqual gets equal-length buffers regardless of how the
224
+ // caller stringified.
225
+ var userCode = String(code).replace(/[\s.\-_]/g, "").padStart(resolved.digits, "0");
226
+ var userBuf = Buffer.from(userCode);
227
+
228
+ for (var d = -resolved.driftSteps; d <= resolved.driftSteps; d++) {
229
+ var step = currentStep + d;
230
+ if (lastUsedStep !== null && step <= lastUsedStep) continue; // reject replays at-or-below the last accepted step
231
+ var expected;
232
+ try { expected = compute(secret, step, opts); }
233
+ catch (_e) { return false; }
234
+ var expectedBuf = Buffer.from(expected);
235
+ if (timingSafeEqual(expectedBuf, userBuf)) {
236
+ return step;
237
+ }
238
+ }
239
+ return false;
240
+ }
241
+
242
+ function uri(secret, account, opts) {
243
+ if (typeof secret !== "string" || secret.length === 0) {
244
+ throw new AuthError("auth-totp/missing-secret", "secret is required");
245
+ }
246
+ if (typeof account !== "string" || account.length === 0) {
247
+ throw new AuthError("auth-totp/missing-account",
248
+ "account is required (typically the user's email or username)");
249
+ }
250
+ if (!opts || !opts.issuer || typeof opts.issuer !== "string") {
251
+ throw new AuthError("auth-totp/missing-issuer",
252
+ "opts.issuer is required (the application/service name shown in the authenticator)");
253
+ }
254
+ var resolved = _resolveOpts(opts);
255
+ // Label format per Google Authenticator: "Issuer:Account"
256
+ var label = encodeURIComponent(opts.issuer) + ":" + encodeURIComponent(account);
257
+ var params = [
258
+ "secret=" + secret,
259
+ "issuer=" + encodeURIComponent(opts.issuer),
260
+ "algorithm=" + resolved.algorithm.toUpperCase(),
261
+ "digits=" + resolved.digits,
262
+ "period=" + resolved.stepSeconds,
263
+ ];
264
+ return "otpauth://totp/" + label + "?" + params.join("&");
265
+ }
266
+
267
+ function generateBackupCodes(opts) {
268
+ // Defaults: 10 codes × 8 hex chars (4 random bytes per code). Operators
269
+ // who want longer / different formats override count + bytesPerCode.
270
+ opts = opts || {};
271
+ var count = opts.count != null ? opts.count : 10;
272
+ var bytesPerCode = opts.bytesPerCode != null ? opts.bytesPerCode : 4;
273
+ if (typeof count !== "number" || count < 1) {
274
+ throw new AuthError("auth-totp/bad-backup-count",
275
+ "count must be >= 1 (got: " + count + ")");
276
+ }
277
+ if (typeof bytesPerCode !== "number" || bytesPerCode < 2) {
278
+ throw new AuthError("auth-totp/bad-backup-bytes",
279
+ "bytesPerCode must be >= 2 (got: " + bytesPerCode + ")");
280
+ }
281
+ var codes = [];
282
+ for (var i = 0; i < count; i++) {
283
+ codes.push(generateToken(bytesPerCode));
284
+ }
285
+ return codes;
286
+ }
287
+
288
+ module.exports = {
289
+ generateSecret: generateSecret,
290
+ generate: generate,
291
+ compute: compute,
292
+ verify: verify,
293
+ uri: uri,
294
+ generateBackupCodes: generateBackupCodes,
295
+ DEFAULT_STEP_SECONDS: DEFAULT_STEP_SECONDS,
296
+ DEFAULT_DIGITS: DEFAULT_DIGITS,
297
+ DEFAULT_DRIFT_STEPS: DEFAULT_DRIFT_STEPS,
298
+ DEFAULT_ALGORITHM: DEFAULT_ALGORITHM,
299
+ DEFAULT_SECRET_BYTES: DEFAULT_SECRET_BYTES,
300
+ MIN_SECRET_BYTES: MIN_SECRET_BYTES,
301
+ SUPPORTED_ALGORITHMS: SUPPORTED_ALGORITHMS,
302
+ };