@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.
- package/CHANGELOG.md +425 -423
- package/README.md +150 -150
- package/bin/blamejs.js +0 -0
- package/index.js +310 -308
- package/lib/api-key.js +660 -660
- package/lib/api-snapshot.js +338 -338
- package/lib/app-shutdown.js +385 -385
- package/lib/app.js +365 -365
- package/lib/archive.js +250 -250
- package/lib/atomic-file.js +544 -544
- package/lib/audit-chain.js +177 -177
- package/lib/audit-sign.js +344 -344
- package/lib/audit-tools.js +677 -677
- package/lib/audit.js +766 -766
- package/lib/auth/jwt-external.js +365 -0
- package/lib/auth/jwt.js +337 -311
- package/lib/auth/lockout.js +436 -436
- package/lib/auth/oauth.js +721 -721
- package/lib/auth/passkey.js +181 -181
- package/lib/auth/password.js +628 -594
- package/lib/backup/bundle.js +217 -217
- package/lib/backup/crypto.js +176 -176
- package/lib/backup/index.js +515 -515
- package/lib/backup/manifest.js +282 -282
- package/lib/break-glass.js +1338 -1338
- package/lib/bundler.js +441 -441
- package/lib/cache-redis.js +256 -256
- package/lib/cache.js +1206 -1206
- package/lib/canonical-json.js +115 -115
- package/lib/chain-writer.js +234 -234
- package/lib/cli-helpers.js +206 -206
- package/lib/cli.js +2334 -2334
- package/lib/cluster-provider-db.js +317 -317
- package/lib/cluster-storage.js +226 -226
- package/lib/cluster.js +703 -703
- package/lib/config-drift.js +301 -301
- package/lib/consent.js +222 -222
- package/lib/constants.js +191 -191
- package/lib/cookies.js +315 -315
- package/lib/credential-hash.js +322 -322
- package/lib/crypto.js +266 -266
- package/lib/csv.js +275 -275
- package/lib/db-declare-row-policy.js +267 -267
- package/lib/db-declare-view.js +420 -420
- package/lib/db-query.js +406 -406
- package/lib/db-schema.js +319 -319
- package/lib/db.js +1288 -1288
- package/lib/deprecate.js +222 -222
- package/lib/dev.js +335 -335
- package/lib/dual-control.js +473 -473
- package/lib/error-page.js +420 -420
- package/lib/external-db-migrate.js +441 -441
- package/lib/external-db.js +1061 -1061
- package/lib/file-type.js +273 -273
- package/lib/forms.js +422 -422
- package/lib/framework-error.js +293 -293
- package/lib/framework-schema.js +717 -717
- package/lib/handlers.js +350 -350
- package/lib/http-client-cookie-jar.js +508 -508
- package/lib/http-client.js +1195 -1195
- package/lib/i18n.js +878 -878
- package/lib/jobs.js +185 -185
- package/lib/log-stream-cloudwatch.js +369 -369
- package/lib/log-stream-local.js +146 -146
- package/lib/log-stream-otlp-grpc.js +410 -410
- package/lib/log-stream-otlp.js +286 -286
- package/lib/log-stream-syslog.js +302 -302
- package/lib/log-stream-webhook.js +199 -199
- package/lib/log-stream.js +330 -330
- package/lib/log.js +500 -500
- package/lib/mail-bounce.js +528 -528
- package/lib/mail-dkim.js +369 -369
- package/lib/mail.js +981 -981
- package/lib/metrics.js +683 -683
- package/lib/middleware/api-encrypt.js +936 -936
- package/lib/middleware/attach-user.js +157 -157
- package/lib/middleware/bearer-auth.js +152 -0
- package/lib/middleware/body-parser.js +1170 -1170
- package/lib/middleware/bot-guard.js +178 -178
- package/lib/middleware/compression.js +452 -452
- package/lib/middleware/cors.js +314 -314
- package/lib/middleware/csp-nonce.js +348 -348
- package/lib/middleware/csrf-protect.js +316 -316
- package/lib/middleware/db-role-for.js +264 -264
- package/lib/middleware/health.js +392 -392
- package/lib/middleware/index.js +82 -79
- package/lib/middleware/rate-limit.js +358 -358
- package/lib/middleware/request-id.js +61 -61
- package/lib/middleware/request-log.js +168 -168
- package/lib/middleware/require-auth.js +104 -104
- package/lib/middleware/security-headers.js +116 -116
- package/lib/middleware/sse.js +166 -166
- package/lib/migrations.js +383 -383
- package/lib/mtls-ca.js +518 -518
- package/lib/mtls-engine-default.js +481 -481
- package/lib/network-dns.js +632 -632
- package/lib/network-heartbeat.js +290 -290
- package/lib/network-nts.js +574 -574
- package/lib/network-proxy.js +265 -265
- package/lib/network-tls.js +328 -328
- package/lib/network.js +233 -233
- package/lib/notify.js +612 -612
- package/lib/ntp-check.js +229 -229
- package/lib/numeric-bounds.js +111 -111
- package/lib/object-store/azure-blob-bucket-ops.js +349 -349
- package/lib/object-store/azure-blob.js +488 -488
- package/lib/object-store/gcs-bucket-ops.js +351 -351
- package/lib/object-store/gcs.js +519 -519
- package/lib/object-store/http-put.js +153 -153
- package/lib/object-store/index.js +197 -197
- package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
- package/lib/object-store/sigv4.js +903 -903
- package/lib/observability.js +151 -151
- package/lib/otel-export.js +269 -269
- package/lib/pagination.js +464 -464
- package/lib/parsers/index.js +80 -80
- package/lib/parsers/safe-env.js +642 -642
- package/lib/parsers/safe-ini.js +292 -292
- package/lib/parsers/safe-toml.js +784 -784
- package/lib/parsers/safe-xml.js +390 -390
- package/lib/parsers/safe-yaml.js +1015 -1015
- package/lib/permissions.js +708 -708
- package/lib/pqc-agent.js +87 -87
- package/lib/pqc-gate.js +279 -279
- package/lib/protobuf-encoder.js +190 -190
- package/lib/protocol-dispatcher.js +161 -161
- package/lib/pubsub-redis.js +167 -167
- package/lib/pubsub.js +429 -429
- package/lib/queue-local.js +476 -476
- package/lib/queue-redis.js +745 -745
- package/lib/queue-sqs.js +319 -319
- package/lib/queue.js +695 -695
- package/lib/redis-client.js +519 -519
- package/lib/request-helpers.js +340 -340
- package/lib/restore-bundle.js +237 -237
- package/lib/restore-rollback.js +259 -259
- package/lib/restore.js +409 -409
- package/lib/retry.js +376 -376
- package/lib/router.js +748 -748
- package/lib/safe-async.js +735 -735
- package/lib/safe-buffer.js +237 -237
- package/lib/safe-json.js +541 -541
- package/lib/safe-schema.js +1266 -1266
- package/lib/safe-url.js +159 -159
- package/lib/scheduler.js +706 -706
- package/lib/security-assert.js +373 -373
- package/lib/seeders.js +618 -618
- package/lib/session.js +535 -478
- package/lib/slug.js +269 -269
- package/lib/ssrf-guard.js +401 -401
- package/lib/storage.js +471 -471
- package/lib/subject.js +281 -281
- package/lib/template.js +791 -791
- package/lib/testing.js +798 -798
- package/lib/time.js +310 -310
- package/lib/totp.js +302 -302
- package/lib/tracing.js +494 -494
- package/lib/uuid.js +132 -132
- package/lib/validate-opts.js +340 -340
- package/lib/vault/index.js +308 -308
- package/lib/vault/rotate.js +784 -784
- package/lib/vault/wrap.js +296 -296
- package/lib/vendor/noble-ciphers.cjs +9 -9
- package/lib/webhook.js +595 -595
- package/lib/websocket.js +1048 -1048
- package/package.json +77 -77
- 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
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
//
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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
|
+
};
|