@blamejs/core 0.7.1 → 0.7.18

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 (180) hide show
  1. package/CHANGELOG.md +423 -389
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -282
  5. package/lib/api-key.js +660 -672
  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.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -266
  27. package/lib/cache.js +1206 -1211
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  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 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  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/file-upload.js +1136 -0
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -202
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -573
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -269
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -614
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -451
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -479
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -855
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -177
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -752
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -489
  146. package/lib/request-helpers.js +340 -336
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -630
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +879 -114
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -270
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -598
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
package/lib/auth/jwt.js CHANGED
@@ -1,311 +1,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 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 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
+ };