@blamejs/core 0.4.1

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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
@@ -0,0 +1,280 @@
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 safeJson = require("../safe-json");
75
+ var { AuthError } = require("../framework-error");
76
+
77
+ // Algorithm registry. The string keys are the JWT header `alg` values
78
+ // the framework emits + accepts. The values map to Node's
79
+ // generateKeyPairSync / sign / verify identifiers.
80
+ var ALGORITHM_TO_NODE = {
81
+ "SLH-DSA-SHAKE-256f": "slh-dsa-shake-256f",
82
+ "ML-DSA-87": "ml-dsa-87",
83
+ };
84
+ var DEFAULT_ALGORITHM = "SLH-DSA-SHAKE-256f";
85
+ var SUPPORTED_ALGORITHMS = Object.freeze(Object.keys(ALGORITHM_TO_NODE));
86
+
87
+ function _b64urlEncode(buf) {
88
+ if (typeof buf === "string") buf = Buffer.from(buf, "utf8");
89
+ return buf.toString("base64").replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
90
+ }
91
+
92
+ function _b64urlDecode(s) {
93
+ if (typeof s !== "string") throw new AuthError("auth-jwt/malformed", "expected base64url string");
94
+ var padded = s.replace(/-/g, "+").replace(/_/g, "/");
95
+ while (padded.length % 4) padded += "=";
96
+ return Buffer.from(padded, "base64");
97
+ }
98
+
99
+ function _toKeyObject(pemOrKey, kind) {
100
+ // kind is 'private' or 'public' — passes through if already a KeyObject;
101
+ // converts PEM string via createPrivateKey/createPublicKey.
102
+ if (pemOrKey == null) {
103
+ throw new AuthError("auth-jwt/missing-key", kind + "Key is required");
104
+ }
105
+ if (typeof pemOrKey === "object" && typeof pemOrKey.asymmetricKeyType === "string") {
106
+ return pemOrKey;
107
+ }
108
+ if (typeof pemOrKey === "string") {
109
+ if (kind === "private") return nodeCrypto.createPrivateKey({ key: pemOrKey, format: "pem" });
110
+ return nodeCrypto.createPublicKey({ key: pemOrKey, format: "pem" });
111
+ }
112
+ throw new AuthError("auth-jwt/bad-key", kind + "Key must be PEM string or KeyObject");
113
+ }
114
+
115
+ function _resolveAlgorithm(alg) {
116
+ if (typeof alg !== "string" || !ALGORITHM_TO_NODE[alg]) {
117
+ throw new AuthError("auth-jwt/unsupported-algorithm",
118
+ "algorithm must be one of " + SUPPORTED_ALGORITHMS.join(", ") + " (got: " + alg + ")");
119
+ }
120
+ return ALGORITHM_TO_NODE[alg];
121
+ }
122
+
123
+ // ---- sign ----
124
+
125
+ async function sign(claims, opts) {
126
+ if (typeof claims !== "object" || claims === null) {
127
+ throw new AuthError("auth-jwt/bad-claims", "claims must be an object");
128
+ }
129
+ opts = opts || {};
130
+ var alg = opts.algorithm || DEFAULT_ALGORITHM;
131
+ _resolveAlgorithm(alg);
132
+ var key = _toKeyObject(opts.privateKey, "private");
133
+
134
+ var nowMs = opts.now || Date.now();
135
+ var nowSec = Math.floor(nowMs / 1000);
136
+
137
+ // Build the claims object. Operator-provided claim values take
138
+ // precedence over opts shorthand to avoid surprising overrides.
139
+ var payload = Object.assign({}, claims);
140
+ if (payload.iat === undefined) payload.iat = nowSec;
141
+ if (opts.issuer !== undefined && payload.iss === undefined) payload.iss = opts.issuer;
142
+ if (opts.audience !== undefined && payload.aud === undefined) payload.aud = opts.audience;
143
+ if (opts.subject !== undefined && payload.sub === undefined) payload.sub = opts.subject;
144
+ if (opts.jti !== undefined && payload.jti === undefined) payload.jti = opts.jti;
145
+ if (typeof opts.expiresInSec === "number" && payload.exp === undefined) {
146
+ payload.exp = nowSec + opts.expiresInSec;
147
+ }
148
+ if (typeof opts.notBeforeSec === "number" && payload.nbf === undefined) {
149
+ payload.nbf = nowSec + opts.notBeforeSec;
150
+ }
151
+
152
+ var header = { alg: alg, typ: opts.typ || "JWT" };
153
+ if (opts.kid) header.kid = String(opts.kid);
154
+
155
+ var headerB64 = _b64urlEncode(JSON.stringify(header));
156
+ var payloadB64 = _b64urlEncode(JSON.stringify(payload));
157
+ var signingInput = headerB64 + "." + payloadB64;
158
+
159
+ // node:crypto.sign with null algorithm — KeyObject knows its own alg.
160
+ var sig = nodeCrypto.sign(null, Buffer.from(signingInput, "ascii"), key);
161
+ return signingInput + "." + _b64urlEncode(sig);
162
+ }
163
+
164
+ // ---- decode (no verify — for inspection) ----
165
+
166
+ function decode(token) {
167
+ if (typeof token !== "string" || token.length === 0) {
168
+ throw new AuthError("auth-jwt/malformed", "token must be a non-empty string");
169
+ }
170
+ var parts = token.split(".");
171
+ if (parts.length !== 3) {
172
+ throw new AuthError("auth-jwt/malformed", "token must have three dot-separated parts");
173
+ }
174
+ var header, payload;
175
+ try { header = safeJson.parse(_b64urlDecode(parts[0])); }
176
+ catch (_e) { throw new AuthError("auth-jwt/malformed", "header is not valid base64url-JSON"); }
177
+ try { payload = safeJson.parse(_b64urlDecode(parts[1])); }
178
+ catch (_e) { throw new AuthError("auth-jwt/malformed", "payload is not valid base64url-JSON"); }
179
+ var signature;
180
+ try { signature = _b64urlDecode(parts[2]); }
181
+ catch (_e) { throw new AuthError("auth-jwt/malformed", "signature is not valid base64url"); }
182
+ return { header: header, payload: payload, signature: signature, signingInput: parts[0] + "." + parts[1] };
183
+ }
184
+
185
+ // ---- verify ----
186
+
187
+ function _matchClaim(actual, expected, claimName) {
188
+ // expected is string OR string[]. actual is string OR string[].
189
+ // Match is "any-of": at least one expected value must appear in
190
+ // actual (or equal it when actual is scalar). Mirrors RFC 7519
191
+ // §4.1.3's tolerance for `aud` being an array.
192
+ var expectedList = Array.isArray(expected) ? expected : [expected];
193
+ var actualList = Array.isArray(actual) ? actual : [actual];
194
+ for (var i = 0; i < expectedList.length; i++) {
195
+ if (actualList.indexOf(expectedList[i]) !== -1) return true;
196
+ }
197
+ return false;
198
+ }
199
+
200
+ async function verify(token, opts) {
201
+ opts = opts || {};
202
+ var allowed = Array.isArray(opts.algorithms) && opts.algorithms.length > 0
203
+ ? opts.algorithms
204
+ : [DEFAULT_ALGORITHM];
205
+ // Validate the allowlist itself — typoed entries should surface here,
206
+ // not as silent "every token rejected."
207
+ for (var i = 0; i < allowed.length; i++) {
208
+ if (!ALGORITHM_TO_NODE[allowed[i]]) {
209
+ throw new AuthError("auth-jwt/unsupported-algorithm",
210
+ "opts.algorithms[" + i + "] = '" + allowed[i] + "' is not in the supported list (" +
211
+ SUPPORTED_ALGORITHMS.join(", ") + ")");
212
+ }
213
+ }
214
+ var key = _toKeyObject(opts.publicKey, "public");
215
+ var decoded = decode(token);
216
+
217
+ // Reject unknown critical-header extensions outright (RFC 7515 §4.1.11)
218
+ if (decoded.header.crit !== undefined) {
219
+ throw new AuthError("auth-jwt/unknown-crit",
220
+ "token declares critical extensions which this verifier does not support");
221
+ }
222
+
223
+ // Algorithm must be in the allowed list AND match what we know how
224
+ // to verify (i.e. one of SUPPORTED_ALGORITHMS).
225
+ if (allowed.indexOf(decoded.header.alg) === -1) {
226
+ throw new AuthError("auth-jwt/algorithm-not-allowed",
227
+ "token alg='" + decoded.header.alg + "' is not in the allowed list [" + allowed.join(", ") + "]");
228
+ }
229
+
230
+ var verified = false;
231
+ try {
232
+ verified = nodeCrypto.verify(null, Buffer.from(decoded.signingInput, "ascii"), key, decoded.signature);
233
+ } catch (e) {
234
+ // node:crypto throws on key/signature shape mismatches (e.g. ML-DSA
235
+ // signature against an SLH-DSA key). Treat as bad-signature so
236
+ // operators can audit a single class of "this token isn't ours."
237
+ throw new AuthError("auth-jwt/invalid-signature",
238
+ "signature verification failed: " + (e.message || String(e)));
239
+ }
240
+ if (!verified) {
241
+ throw new AuthError("auth-jwt/invalid-signature", "signature verification failed");
242
+ }
243
+
244
+ // Time-based claim validation
245
+ var nowSec = Math.floor((opts.now || Date.now()) / 1000);
246
+ var tol = typeof opts.clockToleranceSec === "number" ? opts.clockToleranceSec : 0;
247
+ var p = decoded.payload;
248
+ if (typeof p.exp === "number" && p.exp + tol < nowSec) {
249
+ throw new AuthError("auth-jwt/expired",
250
+ "token expired at exp=" + p.exp + " (now=" + nowSec + ", tolerance=" + tol + "s)");
251
+ }
252
+ if (typeof p.nbf === "number" && p.nbf - tol > nowSec) {
253
+ throw new AuthError("auth-jwt/not-yet-valid",
254
+ "token not yet valid: nbf=" + p.nbf + " (now=" + nowSec + ", tolerance=" + tol + "s)");
255
+ }
256
+
257
+ // String-claim assertions
258
+ if (opts.issuer !== undefined && !_matchClaim(p.iss, opts.issuer, "iss")) {
259
+ throw new AuthError("auth-jwt/iss-mismatch",
260
+ "iss='" + p.iss + "' does not match expected " + JSON.stringify(opts.issuer));
261
+ }
262
+ if (opts.audience !== undefined && !_matchClaim(p.aud, opts.audience, "aud")) {
263
+ throw new AuthError("auth-jwt/aud-mismatch",
264
+ "aud=" + JSON.stringify(p.aud) + " does not match expected " + JSON.stringify(opts.audience));
265
+ }
266
+ if (opts.subject !== undefined && p.sub !== opts.subject) {
267
+ throw new AuthError("auth-jwt/sub-mismatch",
268
+ "sub='" + p.sub + "' does not match expected '" + opts.subject + "'");
269
+ }
270
+
271
+ return p;
272
+ }
273
+
274
+ module.exports = {
275
+ sign: sign,
276
+ verify: verify,
277
+ decode: decode,
278
+ DEFAULT_ALGORITHM: DEFAULT_ALGORITHM,
279
+ SUPPORTED_ALGORITHMS: SUPPORTED_ALGORITHMS,
280
+ };