@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
package/lib/auth/jwt.js CHANGED
@@ -1,311 +1,337 @@
1
- "use strict";
2
- /**
3
- * JWT (RFC 7519) — PQC-signed JSON Web Tokens.
4
- *
5
- * Default signing algorithm: SLH-DSA-SHAKE-256f (FIPS 205, hash-only,
6
- * Cat-5 PQC). Matches the framework's SHAKE-family hash posture and
7
- * the audit-sign default — long-lived signed claims should sit on the
8
- * worst-case-PQC side of the choice. ML-DSA-87 (FIPS 204, lattice-
9
- * based, Cat-5 PQC) is the opt-in for high-throughput JWT issuance
10
- * paths where the ~80× sign-time penalty of SLH-DSA matters more than
11
- * the conservative-PQC argument.
12
- *
13
- * Caveats on emitting PQC-signed JWTs to the wild:
14
- *
15
- * - Signature size: SLH-DSA-SHAKE-256f signatures are ~50 KB. A
16
- * base64url-encoded JWT containing one is ~67 KB on the wire.
17
- * Acceptable for stored long-lived tokens (license attestations,
18
- * refresh tokens with multi-day validity, signed compliance
19
- * receipts) — not for high-frequency request-bearer tokens.
20
- * ML-DSA-87 brings this down to ~6 KB encoded.
21
- *
22
- * - Algorithm naming is NOT in the IANA JOSE registry yet. The
23
- * framework uses the IETF working-draft names ("SLH-DSA-SHAKE-256f",
24
- * "ML-DSA-87") — when those become registered, the header `alg`
25
- * value may shift; verify accepts whatever the supported-list
26
- * declares. Expect to re-issue tokens at registry-stabilization
27
- * time the same way you'd re-issue at any algorithm rotation.
28
- *
29
- * - JWS-RFC-7515-required `crit` header parameter handling is NOT
30
- * implemented (no critical extensions defined here). A token
31
- * bearing an unknown `crit` is rejected as malformed.
32
- *
33
- * Public API (b.auth.jwt.*):
34
- *
35
- * jwt.sign(claims, opts) → string (compact JWS, async)
36
- * jwt.verify(token, opts) → claims (async; throws AuthError)
37
- * jwt.decode(token) → { header, payload, signature }
38
- * (NO verification — inspection only)
39
- *
40
- * Sign opts:
41
- * algorithm: "SLH-DSA-SHAKE-256f" (default) | "ML-DSA-87"
42
- * privateKey: PEM string OR KeyObject from node:crypto.createPrivateKey
43
- * kid: optional key ID embedded in header (rotation hint)
44
- * typ: "JWT" (default) — operators emitting access-tokens may
45
- * want "at+jwt" per RFC 9068
46
- * issuer: claims.iss override (also accepts claims.iss directly)
47
- * audience: claims.aud override (string or string[])
48
- * subject: claims.sub override
49
- * expiresInSec: relative exp (claims.exp = now + expiresInSec)
50
- * notBeforeSec: relative nbf (claims.nbf = now + notBeforeSec)
51
- * jti: claims.jti override (string; if missing, no jti is added —
52
- * the framework doesn't auto-mint without an operator request
53
- * since jti has uniqueness/replay-tracking semantics that
54
- * belong at the application layer)
55
- * now: test-time clock injection (epoch milliseconds)
56
- *
57
- * Verify opts:
58
- * publicKey: PEM string OR KeyObject (required)
59
- * algorithms: [string] allowed alg list. Default: [DEFAULT_ALGORITHM]
60
- * Pass an explicit list when accepting tokens
61
- * signed with multiple algos (e.g. mid-rotation).
62
- * issuer: expected iss (string OR string[]; matched any-of)
63
- * audience: expected aud (same shape; matches any-of, since
64
- * aud itself can be array per RFC 7519 §4.1.3)
65
- * subject: expected sub (string)
66
- * clockToleranceSec: leeway on exp/nbf comparisons. Default 0.
67
- * now: test-time clock injection
68
- *
69
- * Errors are AuthError(code, message) with permanent=true. Distinct
70
- * codes per failure class so callers can branch (display "expired"
71
- * vs "not yet valid" UX, audit "bad-signature" attempts separately).
72
- */
73
- var nodeCrypto = require("crypto");
74
- var C = require("../constants");
75
- var safeJson = require("../safe-json");
76
- var { AuthError } = require("../framework-error");
77
-
78
- // Algorithm registry. The string keys are the JWT header `alg` values
79
- // the framework emits + accepts. The values map to Node's
80
- // generateKeyPairSync / sign / verify identifiers.
81
- var ALGORITHM_TO_NODE = {
82
- "SLH-DSA-SHAKE-256f": "slh-dsa-shake-256f",
83
- "ML-DSA-87": "ml-dsa-87",
84
- };
85
- var DEFAULT_ALGORITHM = "SLH-DSA-SHAKE-256f";
86
- var SUPPORTED_ALGORITHMS = Object.freeze(Object.keys(ALGORITHM_TO_NODE));
87
-
88
- function _b64urlEncode(buf) {
89
- if (typeof buf === "string") buf = Buffer.from(buf, "utf8");
90
- return buf.toString("base64").replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
91
- }
92
-
93
- function _b64urlDecode(s) {
94
- if (typeof s !== "string") throw new AuthError("auth-jwt/malformed", "expected base64url string");
95
- var padded = s.replace(/-/g, "+").replace(/_/g, "/");
96
- while (padded.length % 4) padded += "=";
97
- return Buffer.from(padded, "base64");
98
- }
99
-
100
- function _toKeyObject(pemOrKey, kind) {
101
- // kind is 'private' or 'public' — passes through if already a KeyObject;
102
- // converts PEM string via createPrivateKey/createPublicKey.
103
- if (pemOrKey == null) {
104
- throw new AuthError("auth-jwt/missing-key", kind + "Key is required");
105
- }
106
- if (typeof pemOrKey === "object" && typeof pemOrKey.asymmetricKeyType === "string") {
107
- return pemOrKey;
108
- }
109
- if (typeof pemOrKey === "string") {
110
- if (kind === "private") return nodeCrypto.createPrivateKey({ key: pemOrKey, format: "pem" });
111
- return nodeCrypto.createPublicKey({ key: pemOrKey, format: "pem" });
112
- }
113
- throw new AuthError("auth-jwt/bad-key", kind + "Key must be PEM string or KeyObject");
114
- }
115
-
116
- function _resolveAlgorithm(alg) {
117
- if (typeof alg !== "string" || !ALGORITHM_TO_NODE[alg]) {
118
- throw new AuthError("auth-jwt/unsupported-algorithm",
119
- "algorithm must be one of " + SUPPORTED_ALGORITHMS.join(", ") + " (got: " + alg + ")");
120
- }
121
- return ALGORITHM_TO_NODE[alg];
122
- }
123
-
124
- // ---- sign ----
125
-
126
- async function sign(claims, opts) {
127
- if (typeof claims !== "object" || claims === null) {
128
- throw new AuthError("auth-jwt/bad-claims", "claims must be an object");
129
- }
130
- opts = opts || {};
131
- var alg = opts.algorithm || DEFAULT_ALGORITHM;
132
- _resolveAlgorithm(alg);
133
- var key = _toKeyObject(opts.privateKey, "private");
134
-
135
- var nowMs = opts.now || Date.now();
136
- var nowSec = Math.floor(nowMs / C.TIME.seconds(1));
137
-
138
- // Build the claims object. Operator-provided claim values take
139
- // precedence over opts shorthand to avoid surprising overrides.
140
- var payload = Object.assign({}, claims);
141
- if (payload.iat === undefined) payload.iat = nowSec;
142
- if (opts.issuer !== undefined && payload.iss === undefined) payload.iss = opts.issuer;
143
- if (opts.audience !== undefined && payload.aud === undefined) payload.aud = opts.audience;
144
- if (opts.subject !== undefined && payload.sub === undefined) payload.sub = opts.subject;
145
- if (opts.jti !== undefined && payload.jti === undefined) payload.jti = opts.jti;
146
- if (typeof opts.expiresInSec === "number" && payload.exp === undefined) {
147
- payload.exp = nowSec + opts.expiresInSec;
148
- }
149
- if (typeof opts.notBeforeSec === "number" && payload.nbf === undefined) {
150
- payload.nbf = nowSec + opts.notBeforeSec;
151
- }
152
-
153
- var header = { alg: alg, typ: opts.typ || "JWT" };
154
- if (opts.kid) header.kid = String(opts.kid);
155
-
156
- var headerB64 = _b64urlEncode(JSON.stringify(header));
157
- var payloadB64 = _b64urlEncode(JSON.stringify(payload));
158
- var signingInput = headerB64 + "." + payloadB64;
159
-
160
- // node:crypto.sign with null algorithm — KeyObject knows its own alg.
161
- var sig = nodeCrypto.sign(null, Buffer.from(signingInput, "ascii"), key);
162
- return signingInput + "." + _b64urlEncode(sig);
163
- }
164
-
165
- // ---- decode (no verify — for inspection) ----
166
-
167
- function decode(token) {
168
- if (typeof token !== "string" || token.length === 0) {
169
- throw new AuthError("auth-jwt/malformed", "token must be a non-empty string");
170
- }
171
- var parts = token.split(".");
172
- if (parts.length !== 3) {
173
- throw new AuthError("auth-jwt/malformed", "token must have three dot-separated parts");
174
- }
175
- var header, payload;
176
- try { header = safeJson.parse(_b64urlDecode(parts[0])); }
177
- catch (_e) { throw new AuthError("auth-jwt/malformed", "header is not valid base64url-JSON"); }
178
- try { payload = safeJson.parse(_b64urlDecode(parts[1])); }
179
- catch (_e) { throw new AuthError("auth-jwt/malformed", "payload is not valid base64url-JSON"); }
180
- var signature;
181
- try { signature = _b64urlDecode(parts[2]); }
182
- catch (_e) { throw new AuthError("auth-jwt/malformed", "signature is not valid base64url"); }
183
- return { header: header, payload: payload, signature: signature, signingInput: parts[0] + "." + parts[1] };
184
- }
185
-
186
- // ---- verify ----
187
-
188
- function _matchClaim(actual, expected, claimName) {
189
- // expected is string OR string[]. actual is string OR string[].
190
- // Match is "any-of": at least one expected value must appear in
191
- // actual (or equal it when actual is scalar). Mirrors RFC 7519
192
- // §4.1.3's tolerance for `aud` being an array.
193
- var expectedList = Array.isArray(expected) ? expected : [expected];
194
- var actualList = Array.isArray(actual) ? actual : [actual];
195
- for (var i = 0; i < expectedList.length; i++) {
196
- if (actualList.indexOf(expectedList[i]) !== -1) return true;
197
- }
198
- return false;
199
- }
200
-
201
- async function verify(token, opts) {
202
- opts = opts || {};
203
- var allowed = Array.isArray(opts.algorithms) && opts.algorithms.length > 0
204
- ? opts.algorithms
205
- : [DEFAULT_ALGORITHM];
206
- // Validate the allowlist itself — typoed entries should surface here,
207
- // not as silent "every token rejected."
208
- for (var i = 0; i < allowed.length; i++) {
209
- if (!ALGORITHM_TO_NODE[allowed[i]]) {
210
- throw new AuthError("auth-jwt/unsupported-algorithm",
211
- "opts.algorithms[" + i + "] = '" + allowed[i] + "' is not in the supported list (" +
212
- SUPPORTED_ALGORITHMS.join(", ") + ")");
213
- }
214
- }
215
- var key = _toKeyObject(opts.publicKey, "public");
216
- var decoded = decode(token);
217
-
218
- // Reject unknown critical-header extensions outright (RFC 7515 §4.1.11)
219
- if (decoded.header.crit !== undefined) {
220
- throw new AuthError("auth-jwt/unknown-crit",
221
- "token declares critical extensions which this verifier does not support");
222
- }
223
-
224
- // Algorithm must be in the allowed list AND match what we know how
225
- // to verify (i.e. one of SUPPORTED_ALGORITHMS).
226
- if (allowed.indexOf(decoded.header.alg) === -1) {
227
- throw new AuthError("auth-jwt/algorithm-not-allowed",
228
- "token alg='" + decoded.header.alg + "' is not in the allowed list [" + allowed.join(", ") + "]");
229
- }
230
-
231
- var verified = false;
232
- try {
233
- verified = nodeCrypto.verify(null, Buffer.from(decoded.signingInput, "ascii"), key, decoded.signature);
234
- } catch (e) {
235
- // node:crypto throws on key/signature shape mismatches (e.g. ML-DSA
236
- // signature against an SLH-DSA key). Treat as bad-signature so
237
- // operators can audit a single class of "this token isn't ours."
238
- throw new AuthError("auth-jwt/invalid-signature",
239
- "signature verification failed: " + (e.message || String(e)));
240
- }
241
- if (!verified) {
242
- throw new AuthError("auth-jwt/invalid-signature", "signature verification failed");
243
- }
244
-
245
- // Time-based claim validation
246
- var nowSec = Math.floor((opts.now || Date.now()) / C.TIME.seconds(1));
247
- if (opts.clockToleranceSec !== undefined && opts.clockToleranceSec !== null) {
248
- if (typeof opts.clockToleranceSec !== "number" ||
249
- !isFinite(opts.clockToleranceSec) ||
250
- opts.clockToleranceSec < 0) {
251
- // Throw at config time: a negative tolerance over-tightens the
252
- // window (legit tokens get rejected as expired or not-yet-valid)
253
- // and a non-finite value would NaN-poison the comparison. Catch
254
- // both here rather than producing surprise rejections in production.
255
- throw new AuthError("auth-jwt/bad-clock-tolerance",
256
- "verify: clockToleranceSec must be a non-negative finite number, got " +
257
- JSON.stringify(opts.clockToleranceSec));
258
- }
259
- }
260
- var tol = typeof opts.clockToleranceSec === "number" ? opts.clockToleranceSec : 0;
261
- var p = decoded.payload;
262
-
263
- // Strict registered-claim typing per RFC 7519 §4.1. exp / nbf / iat MUST
264
- // be NumericDate values (JSON numeric, seconds since epoch). A claim
265
- // present-but-not-a-number is a malformed token silently skipping the
266
- // check would let a token with `exp: "0"` or `exp: "9999999999"` (string)
267
- // bypass expiration enforcement entirely.
268
- function _requireNumericDate(name, value) {
269
- if (typeof value !== "number" || !isFinite(value)) {
270
- throw new AuthError("auth-jwt/malformed",
271
- "claim '" + name + "' must be a finite number (RFC 7519 NumericDate), got " +
272
- (value === null ? "null" : typeof value));
273
- }
274
- }
275
- if (p.exp !== undefined) _requireNumericDate("exp", p.exp);
276
- if (p.nbf !== undefined) _requireNumericDate("nbf", p.nbf);
277
- if (p.iat !== undefined) _requireNumericDate("iat", p.iat);
278
-
279
- if (p.exp !== undefined && p.exp + tol < nowSec) {
280
- throw new AuthError("auth-jwt/expired",
281
- "token expired at exp=" + p.exp + " (now=" + nowSec + ", tolerance=" + tol + "s)");
282
- }
283
- if (p.nbf !== undefined && p.nbf - tol > nowSec) {
284
- throw new AuthError("auth-jwt/not-yet-valid",
285
- "token not yet valid: nbf=" + p.nbf + " (now=" + nowSec + ", tolerance=" + tol + "s)");
286
- }
287
-
288
- // String-claim assertions
289
- if (opts.issuer !== undefined && !_matchClaim(p.iss, opts.issuer, "iss")) {
290
- throw new AuthError("auth-jwt/iss-mismatch",
291
- "iss='" + p.iss + "' does not match expected " + JSON.stringify(opts.issuer));
292
- }
293
- if (opts.audience !== undefined && !_matchClaim(p.aud, opts.audience, "aud")) {
294
- throw new AuthError("auth-jwt/aud-mismatch",
295
- "aud=" + JSON.stringify(p.aud) + " does not match expected " + JSON.stringify(opts.audience));
296
- }
297
- if (opts.subject !== undefined && p.sub !== opts.subject) {
298
- throw new AuthError("auth-jwt/sub-mismatch",
299
- "sub='" + p.sub + "' does not match expected '" + opts.subject + "'");
300
- }
301
-
302
- return p;
303
- }
304
-
305
- module.exports = {
306
- sign: sign,
307
- verify: verify,
308
- decode: decode,
309
- DEFAULT_ALGORITHM: DEFAULT_ALGORITHM,
310
- SUPPORTED_ALGORITHMS: SUPPORTED_ALGORITHMS,
311
- };
1
+ "use strict";
2
+ /**
3
+ * JWT (RFC 7519) — PQC-signed JSON Web Tokens.
4
+ *
5
+ * Default signing algorithm: SLH-DSA-SHAKE-256f (FIPS 205, hash-only,
6
+ * Cat-5 PQC). Matches the framework's SHAKE-family hash posture and
7
+ * the audit-sign default — long-lived signed claims should sit on the
8
+ * worst-case-PQC side of the choice. ML-DSA-87 (FIPS 204, lattice-
9
+ * based, Cat-5 PQC) is the opt-in for high-throughput JWT issuance
10
+ * paths where the ~80× sign-time penalty of SLH-DSA matters more than
11
+ * the conservative-PQC argument.
12
+ *
13
+ * Caveats on emitting PQC-signed JWTs to the wild:
14
+ *
15
+ * - Signature size: SLH-DSA-SHAKE-256f signatures are ~50 KB. A
16
+ * base64url-encoded JWT containing one is ~67 KB on the wire.
17
+ * Acceptable for stored long-lived tokens (license attestations,
18
+ * refresh tokens with multi-day validity, signed compliance
19
+ * receipts) — not for high-frequency request-bearer tokens.
20
+ * ML-DSA-87 brings this down to ~6 KB encoded.
21
+ *
22
+ * - Algorithm naming is NOT in the IANA JOSE registry yet. The
23
+ * framework uses the IETF working-draft names ("SLH-DSA-SHAKE-256f",
24
+ * "ML-DSA-87") — when those become registered, the header `alg`
25
+ * value may shift; verify accepts whatever the supported-list
26
+ * declares. Expect to re-issue tokens at registry-stabilization
27
+ * time the same way you'd re-issue at any algorithm rotation.
28
+ *
29
+ * - JWS-RFC-7515-required `crit` header parameter handling is NOT
30
+ * implemented (no critical extensions defined here). A token
31
+ * bearing an unknown `crit` is rejected as malformed.
32
+ *
33
+ * Public API (b.auth.jwt.*):
34
+ *
35
+ * jwt.sign(claims, opts) → string (compact JWS, async)
36
+ * jwt.verify(token, opts) → claims (async; throws AuthError)
37
+ * jwt.decode(token) → { header, payload, signature }
38
+ * (NO verification — inspection only)
39
+ *
40
+ * Sign opts:
41
+ * algorithm: "SLH-DSA-SHAKE-256f" (default) | "ML-DSA-87"
42
+ * privateKey: PEM string OR KeyObject from node:crypto.createPrivateKey
43
+ * kid: optional key ID embedded in header (rotation hint)
44
+ * typ: "JWT" (default) — operators emitting access-tokens may
45
+ * want "at+jwt" per RFC 9068
46
+ * issuer: claims.iss override (also accepts claims.iss directly)
47
+ * audience: claims.aud override (string or string[])
48
+ * subject: claims.sub override
49
+ * expiresInSec: relative exp (claims.exp = now + expiresInSec)
50
+ * notBeforeSec: relative nbf (claims.nbf = now + notBeforeSec)
51
+ * jti: claims.jti override (string; if missing, no jti is added —
52
+ * the framework doesn't auto-mint without an operator request
53
+ * since jti has uniqueness/replay-tracking semantics that
54
+ * belong at the application layer)
55
+ * now: test-time clock injection (epoch milliseconds)
56
+ *
57
+ * Verify opts:
58
+ * publicKey: PEM string OR KeyObject (required)
59
+ * algorithms: [string] allowed alg list. Default: [DEFAULT_ALGORITHM]
60
+ * Pass an explicit list when accepting tokens
61
+ * signed with multiple algos (e.g. mid-rotation).
62
+ * issuer: expected iss (string OR string[]; matched any-of)
63
+ * audience: expected aud (same shape; matches any-of, since
64
+ * aud itself can be array per RFC 7519 §4.1.3)
65
+ * subject: expected sub (string)
66
+ * clockToleranceSec: leeway on exp/nbf comparisons. Default 0.
67
+ * now: test-time clock injection
68
+ *
69
+ * Errors are AuthError(code, message) with permanent=true. Distinct
70
+ * codes per failure class so callers can branch (display "expired"
71
+ * vs "not yet valid" UX, audit "bad-signature" attempts separately).
72
+ */
73
+ var nodeCrypto = require("crypto");
74
+ var C = require("../constants");
75
+ var safeJson = require("../safe-json");
76
+ var { AuthError } = require("../framework-error");
77
+
78
+ // Algorithm registry. The string keys are the JWT header `alg` values
79
+ // the framework emits + accepts. The values map to Node's
80
+ // generateKeyPairSync / sign / verify identifiers.
81
+ var ALGORITHM_TO_NODE = {
82
+ "SLH-DSA-SHAKE-256f": "slh-dsa-shake-256f",
83
+ "ML-DSA-87": "ml-dsa-87",
84
+ };
85
+ var DEFAULT_ALGORITHM = "SLH-DSA-SHAKE-256f";
86
+ var SUPPORTED_ALGORITHMS = Object.freeze(Object.keys(ALGORITHM_TO_NODE));
87
+
88
+ function _b64urlEncode(buf) {
89
+ if (typeof buf === "string") buf = Buffer.from(buf, "utf8");
90
+ return buf.toString("base64").replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
91
+ }
92
+
93
+ function _b64urlDecode(s) {
94
+ if (typeof s !== "string") throw new AuthError("auth-jwt/malformed", "expected base64url string");
95
+ var padded = s.replace(/-/g, "+").replace(/_/g, "/");
96
+ while (padded.length % 4) padded += "=";
97
+ return Buffer.from(padded, "base64");
98
+ }
99
+
100
+ function _toKeyObject(pemOrKey, kind) {
101
+ // kind is 'private' or 'public' — passes through if already a KeyObject;
102
+ // converts PEM string via createPrivateKey/createPublicKey.
103
+ if (pemOrKey == null) {
104
+ throw new AuthError("auth-jwt/missing-key", kind + "Key is required");
105
+ }
106
+ if (typeof pemOrKey === "object" && typeof pemOrKey.asymmetricKeyType === "string") {
107
+ return pemOrKey;
108
+ }
109
+ if (typeof pemOrKey === "string") {
110
+ if (kind === "private") return nodeCrypto.createPrivateKey({ key: pemOrKey, format: "pem" });
111
+ return nodeCrypto.createPublicKey({ key: pemOrKey, format: "pem" });
112
+ }
113
+ throw new AuthError("auth-jwt/bad-key", kind + "Key must be PEM string or KeyObject");
114
+ }
115
+
116
+ function _resolveAlgorithm(alg) {
117
+ if (typeof alg !== "string" || !ALGORITHM_TO_NODE[alg]) {
118
+ throw new AuthError("auth-jwt/unsupported-algorithm",
119
+ "algorithm must be one of " + SUPPORTED_ALGORITHMS.join(", ") + " (got: " + alg + ")");
120
+ }
121
+ return ALGORITHM_TO_NODE[alg];
122
+ }
123
+
124
+ // ---- sign ----
125
+
126
+ async function sign(claims, opts) {
127
+ if (typeof claims !== "object" || claims === null) {
128
+ throw new AuthError("auth-jwt/bad-claims", "claims must be an object");
129
+ }
130
+ opts = opts || {};
131
+ var alg = opts.algorithm || DEFAULT_ALGORITHM;
132
+ _resolveAlgorithm(alg);
133
+ var key = _toKeyObject(opts.privateKey, "private");
134
+
135
+ var nowMs = opts.now || Date.now();
136
+ var nowSec = Math.floor(nowMs / C.TIME.seconds(1));
137
+
138
+ // Build the claims object. Operator-provided claim values take
139
+ // precedence over opts shorthand to avoid surprising overrides.
140
+ var payload = Object.assign({}, claims);
141
+ if (payload.iat === undefined) payload.iat = nowSec;
142
+ if (opts.issuer !== undefined && payload.iss === undefined) payload.iss = opts.issuer;
143
+ if (opts.audience !== undefined && payload.aud === undefined) payload.aud = opts.audience;
144
+ if (opts.subject !== undefined && payload.sub === undefined) payload.sub = opts.subject;
145
+ if (opts.jti !== undefined && payload.jti === undefined) payload.jti = opts.jti;
146
+ if (typeof opts.expiresInSec === "number" && payload.exp === undefined) {
147
+ payload.exp = nowSec + opts.expiresInSec;
148
+ }
149
+ if (typeof opts.notBeforeSec === "number" && payload.nbf === undefined) {
150
+ payload.nbf = nowSec + opts.notBeforeSec;
151
+ }
152
+
153
+ var header = { alg: alg, typ: opts.typ || "JWT" };
154
+ if (opts.kid) header.kid = String(opts.kid);
155
+
156
+ var headerB64 = _b64urlEncode(JSON.stringify(header));
157
+ var payloadB64 = _b64urlEncode(JSON.stringify(payload));
158
+ var signingInput = headerB64 + "." + payloadB64;
159
+
160
+ // node:crypto.sign with null algorithm — KeyObject knows its own alg.
161
+ var sig = nodeCrypto.sign(null, Buffer.from(signingInput, "ascii"), key);
162
+ return signingInput + "." + _b64urlEncode(sig);
163
+ }
164
+
165
+ // ---- decode (no verify — for inspection) ----
166
+
167
+ function decode(token) {
168
+ if (typeof token !== "string" || token.length === 0) {
169
+ throw new AuthError("auth-jwt/malformed", "token must be a non-empty string");
170
+ }
171
+ var parts = token.split(".");
172
+ if (parts.length !== 3) {
173
+ throw new AuthError("auth-jwt/malformed", "token must have three dot-separated parts");
174
+ }
175
+ var header, payload;
176
+ try { header = safeJson.parse(_b64urlDecode(parts[0])); }
177
+ catch (_e) { throw new AuthError("auth-jwt/malformed", "header is not valid base64url-JSON"); }
178
+ try { payload = safeJson.parse(_b64urlDecode(parts[1])); }
179
+ catch (_e) { throw new AuthError("auth-jwt/malformed", "payload is not valid base64url-JSON"); }
180
+ var signature;
181
+ try { signature = _b64urlDecode(parts[2]); }
182
+ catch (_e) { throw new AuthError("auth-jwt/malformed", "signature is not valid base64url"); }
183
+ return { header: header, payload: payload, signature: signature, signingInput: parts[0] + "." + parts[1] };
184
+ }
185
+
186
+ // ---- verify ----
187
+
188
+ function _matchClaim(actual, expected, claimName) {
189
+ // expected is string OR string[]. actual is string OR string[].
190
+ // Match is "any-of": at least one expected value must appear in
191
+ // actual (or equal it when actual is scalar). Mirrors RFC 7519
192
+ // §4.1.3's tolerance for `aud` being an array.
193
+ var expectedList = Array.isArray(expected) ? expected : [expected];
194
+ var actualList = Array.isArray(actual) ? actual : [actual];
195
+ for (var i = 0; i < expectedList.length; i++) {
196
+ if (actualList.indexOf(expectedList[i]) !== -1) return true;
197
+ }
198
+ return false;
199
+ }
200
+
201
+ async function verify(token, opts) {
202
+ opts = opts || {};
203
+ var allowed = Array.isArray(opts.algorithms) && opts.algorithms.length > 0
204
+ ? opts.algorithms
205
+ : [DEFAULT_ALGORITHM];
206
+ // Validate the allowlist itself — typoed entries should surface here,
207
+ // not as silent "every token rejected."
208
+ for (var i = 0; i < allowed.length; i++) {
209
+ if (!ALGORITHM_TO_NODE[allowed[i]]) {
210
+ throw new AuthError("auth-jwt/unsupported-algorithm",
211
+ "opts.algorithms[" + i + "] = '" + allowed[i] + "' is not in the supported list (" +
212
+ SUPPORTED_ALGORITHMS.join(", ") + ")");
213
+ }
214
+ }
215
+ var decoded = decode(token);
216
+
217
+ // keyResolver — operator-supplied per-token key lookup (typically by
218
+ // header.kid against a rotation table or remote JWKS). Mutually
219
+ // exclusive with opts.publicKey: pass one or the other, not both.
220
+ // The resolver receives the FULL decoded header and returns either
221
+ // the key (sync) or a Promise<key> (async).
222
+ var key;
223
+ if (typeof opts.keyResolver === "function") {
224
+ if (opts.publicKey !== undefined) {
225
+ throw new AuthError("auth-jwt/conflicting-key-source",
226
+ "verify: pass keyResolver OR publicKey, not both");
227
+ }
228
+ var resolved;
229
+ try { resolved = await opts.keyResolver(decoded.header); }
230
+ catch (e) {
231
+ throw new AuthError("auth-jwt/key-resolver-failed",
232
+ "keyResolver threw: " + ((e && e.message) || String(e)));
233
+ }
234
+ if (!resolved) {
235
+ throw new AuthError("auth-jwt/key-not-found",
236
+ "keyResolver returned no key for kid='" +
237
+ (decoded.header.kid || "<absent>") + "'");
238
+ }
239
+ key = _toKeyObject(resolved, "public");
240
+ } else {
241
+ key = _toKeyObject(opts.publicKey, "public");
242
+ }
243
+
244
+ // Reject unknown critical-header extensions outright (RFC 7515 §4.1.11)
245
+ if (decoded.header.crit !== undefined) {
246
+ throw new AuthError("auth-jwt/unknown-crit",
247
+ "token declares critical extensions which this verifier does not support");
248
+ }
249
+
250
+ // Algorithm must be in the allowed list AND match what we know how
251
+ // to verify (i.e. one of SUPPORTED_ALGORITHMS).
252
+ if (allowed.indexOf(decoded.header.alg) === -1) {
253
+ throw new AuthError("auth-jwt/algorithm-not-allowed",
254
+ "token alg='" + decoded.header.alg + "' is not in the allowed list [" + allowed.join(", ") + "]");
255
+ }
256
+
257
+ var verified = false;
258
+ try {
259
+ verified = nodeCrypto.verify(null, Buffer.from(decoded.signingInput, "ascii"), key, decoded.signature);
260
+ } catch (e) {
261
+ // node:crypto throws on key/signature shape mismatches (e.g. ML-DSA
262
+ // signature against an SLH-DSA key). Treat as bad-signature so
263
+ // operators can audit a single class of "this token isn't ours."
264
+ throw new AuthError("auth-jwt/invalid-signature",
265
+ "signature verification failed: " + (e.message || String(e)));
266
+ }
267
+ if (!verified) {
268
+ throw new AuthError("auth-jwt/invalid-signature", "signature verification failed");
269
+ }
270
+
271
+ // Time-based claim validation
272
+ var nowSec = Math.floor((opts.now || Date.now()) / C.TIME.seconds(1));
273
+ if (opts.clockToleranceSec !== undefined && opts.clockToleranceSec !== null) {
274
+ if (typeof opts.clockToleranceSec !== "number" ||
275
+ !isFinite(opts.clockToleranceSec) ||
276
+ opts.clockToleranceSec < 0) {
277
+ // Throw at config time: a negative tolerance over-tightens the
278
+ // window (legit tokens get rejected as expired or not-yet-valid)
279
+ // and a non-finite value would NaN-poison the comparison. Catch
280
+ // both here rather than producing surprise rejections in production.
281
+ throw new AuthError("auth-jwt/bad-clock-tolerance",
282
+ "verify: clockToleranceSec must be a non-negative finite number, got " +
283
+ JSON.stringify(opts.clockToleranceSec));
284
+ }
285
+ }
286
+ var tol = typeof opts.clockToleranceSec === "number" ? opts.clockToleranceSec : 0;
287
+ var p = decoded.payload;
288
+
289
+ // Strict registered-claim typing per RFC 7519 §4.1. exp / nbf / iat MUST
290
+ // be NumericDate values (JSON numeric, seconds since epoch). A claim
291
+ // present-but-not-a-number is a malformed token silently skipping the
292
+ // check would let a token with `exp: "0"` or `exp: "9999999999"` (string)
293
+ // bypass expiration enforcement entirely.
294
+ function _requireNumericDate(name, value) {
295
+ if (typeof value !== "number" || !isFinite(value)) {
296
+ throw new AuthError("auth-jwt/malformed",
297
+ "claim '" + name + "' must be a finite number (RFC 7519 NumericDate), got " +
298
+ (value === null ? "null" : typeof value));
299
+ }
300
+ }
301
+ if (p.exp !== undefined) _requireNumericDate("exp", p.exp);
302
+ if (p.nbf !== undefined) _requireNumericDate("nbf", p.nbf);
303
+ if (p.iat !== undefined) _requireNumericDate("iat", p.iat);
304
+
305
+ if (p.exp !== undefined && p.exp + tol < nowSec) {
306
+ throw new AuthError("auth-jwt/expired",
307
+ "token expired at exp=" + p.exp + " (now=" + nowSec + ", tolerance=" + tol + "s)");
308
+ }
309
+ if (p.nbf !== undefined && p.nbf - tol > nowSec) {
310
+ throw new AuthError("auth-jwt/not-yet-valid",
311
+ "token not yet valid: nbf=" + p.nbf + " (now=" + nowSec + ", tolerance=" + tol + "s)");
312
+ }
313
+
314
+ // String-claim assertions
315
+ if (opts.issuer !== undefined && !_matchClaim(p.iss, opts.issuer, "iss")) {
316
+ throw new AuthError("auth-jwt/iss-mismatch",
317
+ "iss='" + p.iss + "' does not match expected " + JSON.stringify(opts.issuer));
318
+ }
319
+ if (opts.audience !== undefined && !_matchClaim(p.aud, opts.audience, "aud")) {
320
+ throw new AuthError("auth-jwt/aud-mismatch",
321
+ "aud=" + JSON.stringify(p.aud) + " does not match expected " + JSON.stringify(opts.audience));
322
+ }
323
+ if (opts.subject !== undefined && p.sub !== opts.subject) {
324
+ throw new AuthError("auth-jwt/sub-mismatch",
325
+ "sub='" + p.sub + "' does not match expected '" + opts.subject + "'");
326
+ }
327
+
328
+ return p;
329
+ }
330
+
331
+ module.exports = {
332
+ sign: sign,
333
+ verify: verify,
334
+ decode: decode,
335
+ DEFAULT_ALGORITHM: DEFAULT_ALGORITHM,
336
+ SUPPORTED_ALGORITHMS: SUPPORTED_ALGORITHMS,
337
+ };