@blamejs/core 0.7.18 → 0.7.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
@@ -1,348 +1,348 @@
1
- "use strict";
2
- /**
3
- * csp-nonce — per-request CSP nonce + render integration.
4
- *
5
- * The framework's `security-headers` middleware ships a strict CSP
6
- * that doesn't allow inline scripts (no 'unsafe-inline'). Templates
7
- * with inline `<script>` blocks therefore break out of the box — the
8
- * browser refuses to execute them. This middleware closes the gap:
9
- *
10
- * 1. Generate a fresh random nonce per request (base64, default
11
- * 16 bytes / 22 chars).
12
- * 2. Attach it to `req.cspNonce` (handler-readable) AND
13
- * `res.locals.cspNonce` (template-data-readable — render.js
14
- * auto-merges res.locals into template data).
15
- * 3. Patch the existing Content-Security-Policy header set by
16
- * security-headers — append `'nonce-XYZ'` to the operator-
17
- * configured directives (defaults: script-src, style-src).
18
- * If no CSP header is set yet, build a minimal one.
19
- *
20
- * Operators wire it after security-headers and write `nonce="..."`
21
- * on their inline scripts:
22
- *
23
- * router.use(b.middleware.securityHeaders());
24
- * router.use(b.middleware.cspNonce({
25
- * directives: ["script-src", "style-src"],
26
- * nonceBytes: 16,
27
- * strictDynamic: true,
28
- * }));
29
- *
30
- * // In a template:
31
- * // <script nonce="{{ cspNonce }}">console.log("ok")</script>
32
- * //
33
- * // Or in a handler:
34
- * // res.write('<script nonce="' + req.cspNonce + '">...</script>');
35
- *
36
- * Handler shape: req.cspNonce is the raw base64 nonce. Templates
37
- * receive it via the auto-merged res.locals so the html() render
38
- * helper doesn't need an extra argument — the operator just writes
39
- * `{{ cspNonce }}` in the view.
40
- *
41
- * strict-dynamic mode (opt-in): when true, the nonce directive also
42
- * gets `'strict-dynamic'`. Modern browsers then trust scripts loaded
43
- * by a nonced script — no need to allowlist their origins. This is
44
- * the recommended posture for SPA hydration scripts that themselves
45
- * load dependencies (e.g. tiny inline bootstrap that imports a
46
- * versioned bundle). See https://www.w3.org/TR/CSP3/#strict-dynamic-usage.
47
- *
48
- * Nonce strength:
49
- * - Default 16 bytes (128 bits) of crypto-strong randomness via
50
- * `b.crypto.generateBytes` (OS-RNG → SHAKE256). Standard for
51
- * CSP nonces.
52
- * - Operators with stricter posture set nonceBytes: 32 (256 bits).
53
- * - Going below 16 bytes is refused at config time.
54
- *
55
- * Cacheable-render pattern (when the response HTML is cached but the
56
- * CSP header rotates per request):
57
- *
58
- * var nonceMw = b.middleware.cspNonce();
59
- * router.use(nonceMw);
60
- *
61
- * var pageCache = b.cache.create({ namespace: "wiki", ttlMs: 5*60_000 });
62
- *
63
- * router.get("/:slug", async function (req, res) {
64
- * var html = await pageCache.wrap(req.params.slug, function () {
65
- * // Render with the placeholder — the cached string contains a
66
- * // stable token, never a request-specific nonce. Safe to cache.
67
- * return template.render("page", {
68
- * cspNonce: nonceMw.PLACEHOLDER,
69
- * ...,
70
- * });
71
- * });
72
- * // Replace the placeholder with this request's nonce so the
73
- * // script tag's nonce attribute matches the CSP header.
74
- * res.send(nonceMw.substitute(html, req));
75
- * });
76
- *
77
- * Without this pattern, caching HTML rendered with `{{ cspNonce }}`
78
- * captures the FIRST request's nonce and reuses it on every cache
79
- * hit — the response's CSP header rotates per request, so script
80
- * tags carry a stale nonce the browser refuses. Symptom: scripts
81
- * silently fail to execute on every cache hit after the first.
82
- *
83
- * The placeholder is per-instance random by default — operators with
84
- * caches that survive process restart (Redis, cluster backend) pin
85
- * a stable token via `opts.placeholder` so HTML cached before the
86
- * restart still substitutes correctly after.
87
- *
88
- * What `substitute()` does NOT do (deferred — structural reasons):
89
- * - Streaming substitution across chunk boundaries. `substitute()`
90
- * takes a complete HTML string. Operators streaming HTML in
91
- * chunks (Node Writable, fs.createReadStream → res piping cached
92
- * bytes) must concatenate first or call substitute on each chunk
93
- * where the placeholder is guaranteed not to span a boundary.
94
- * A buffered streaming version requires per-stream state to
95
- * hold up to (PLACEHOLDER.length - 1) bytes between chunks; that
96
- * surface gets its own primitive when an operator hits it.
97
- *
98
- * What this middleware does NOT do:
99
- * - It doesn't ALSO set 'unsafe-inline'. The browser silently ignores
100
- * 'unsafe-inline' when a nonce is present (CSP3 spec), so this is
101
- * a non-issue, but operators sometimes add 'unsafe-inline' "just
102
- * in case" — that defeats the entire point of the nonce.
103
- * - It doesn't attempt to strip 'unsafe-inline' from operator-
104
- * supplied CSP. If the operator configured 'unsafe-inline' and
105
- * adds csp-nonce, both are present; the browser ignores
106
- * 'unsafe-inline' but the static analysis tool might still flag
107
- * it. Removing operator-supplied directives without explicit
108
- * consent is more astonishing than helpful.
109
- * - It doesn't generate nonces for non-HTML responses (JSON, raw
110
- * bytes). The middleware skips when there's no template / inline-
111
- * script context — operators who want a nonce on every response
112
- * pass `always: true`.
113
- */
114
-
115
- var C = require("../constants");
116
- var crypto = require("../crypto");
117
- var numericBounds = require("../numeric-bounds");
118
- var validateOpts = require("../validate-opts");
119
- var { defineClass } = require("../framework-error");
120
-
121
- var CspNonceError = defineClass("CspNonceError", { alwaysPermanent: true });
122
-
123
- var DEFAULT_DIRECTIVES = Object.freeze(["script-src", "style-src"]);
124
- var DEFAULT_NONCE_BYTES = C.BYTES.bytes(16);
125
- var MIN_NONCE_BYTES = C.BYTES.bytes(16);
126
- var PLACEHOLDER_PREFIX = "__BLAMEJS_CSP_NONCE_";
127
- var PLACEHOLDER_SUFFIX = "__";
128
- // 16 bytes / 128 bits — matches the default nonce strength so the
129
- // placeholder is no weaker than the value it stands in for.
130
- var PLACEHOLDER_RAND_BYTES = C.BYTES.bytes(16);
131
-
132
- // Build the substitute helper for a specific placeholder + property.
133
- // Each cspNonce instance has its own placeholder (random by default,
134
- // stable per process) so multiple middleware instances in the same app
135
- // don't share state, and operator content can't accidentally match a
136
- // hardcoded string that lives in source.
137
- function _buildSubstitute(placeholder, property) {
138
- return function substitute(html, reqOrNonce) {
139
- if (typeof html !== "string" || html.length === 0) return html;
140
- if (html.indexOf(placeholder) === -1) return html;
141
- var nonce;
142
- if (typeof reqOrNonce === "string") {
143
- nonce = reqOrNonce;
144
- } else if (reqOrNonce && typeof reqOrNonce === "object") {
145
- nonce = reqOrNonce[property] ||
146
- (reqOrNonce.res && reqOrNonce.res.locals && reqOrNonce.res.locals[property]) ||
147
- "";
148
- } else {
149
- nonce = "";
150
- }
151
- return html.split(placeholder).join(nonce);
152
- };
153
- }
154
-
155
- // Build a fresh CSP from scratch when none is set. Conservative defaults
156
- // — the nonced directive replaces what 'unsafe-inline' would have done.
157
- function _defaultCsp(nonceToken) {
158
- return "default-src 'self'; " +
159
- "script-src 'self' " + nonceToken + "; " +
160
- "style-src 'self' " + nonceToken + "; " +
161
- "img-src 'self' data:; " +
162
- "frame-ancestors 'none'; " +
163
- "base-uri 'self'; " +
164
- "form-action 'self'; " +
165
- "object-src 'none'";
166
- }
167
-
168
- // Parse the CSP header into [{ name, valueParts }] preserving operator
169
- // ordering. Each entry is `directive-name [value...]`.
170
- function _parseCsp(headerValue) {
171
- var parts = String(headerValue).split(";");
172
- var out = [];
173
- for (var i = 0; i < parts.length; i++) {
174
- var p = parts[i].trim();
175
- if (p.length === 0) continue;
176
- // Split on whitespace runs.
177
- var tokens = p.split(/\s+/);
178
- var name = tokens.shift().toLowerCase();
179
- out.push({ name: name, values: tokens });
180
- }
181
- return out;
182
- }
183
-
184
- function _serializeCsp(parts) {
185
- return parts.map(function (p) {
186
- if (p.values.length === 0) return p.name;
187
- return p.name + " " + p.values.join(" ");
188
- }).join("; ");
189
- }
190
-
191
- function _injectNonce(cspHeader, nonce, directives, strictDynamic) {
192
- var nonceToken = "'nonce-" + nonce + "'";
193
- if (!cspHeader) {
194
- // Build a minimal CSP from scratch. strictDynamic isn't applied
195
- // to a fresh CSP because the operator hasn't told us their script
196
- // load pattern yet — they can opt in by combining their own CSP
197
- // with cspNonce.
198
- return _defaultCsp(nonceToken);
199
- }
200
- var parts = _parseCsp(cspHeader);
201
- var seen = Object.create(null);
202
- for (var i = 0; i < parts.length; i++) {
203
- var name = parts[i].name;
204
- seen[name] = i;
205
- if (directives.indexOf(name) !== -1) {
206
- // Avoid duplicate nonce tokens if the middleware ever runs twice.
207
- if (parts[i].values.indexOf(nonceToken) === -1) {
208
- parts[i].values.push(nonceToken);
209
- }
210
- // strict-dynamic only meaningful for script-src.
211
- if (strictDynamic && name === "script-src" && parts[i].values.indexOf("'strict-dynamic'") === -1) {
212
- parts[i].values.push("'strict-dynamic'");
213
- }
214
- }
215
- }
216
- // Add target directives that were missing from the original CSP.
217
- for (var j = 0; j < directives.length; j++) {
218
- var d = directives[j].toLowerCase();
219
- if (Object.prototype.hasOwnProperty.call(seen, d)) continue;
220
- var values = [nonceToken];
221
- if (strictDynamic && d === "script-src") values.push("'strict-dynamic'");
222
- parts.push({ name: d, values: values });
223
- }
224
- return _serializeCsp(parts);
225
- }
226
-
227
- function create(opts) {
228
- opts = opts || {};
229
- validateOpts(opts, [
230
- "directives", "nonceBytes", "strictDynamic", "headerName",
231
- "property", "always", "placeholder",
232
- ], "middleware.cspNonce");
233
- var directives = Array.isArray(opts.directives) && opts.directives.length > 0
234
- ? opts.directives.slice() : DEFAULT_DIRECTIVES.slice();
235
- for (var i = 0; i < directives.length; i++) {
236
- if (typeof directives[i] !== "string" || directives[i].length === 0) {
237
- throw new CspNonceError("csp-nonce/bad-directive",
238
- "directives must be non-empty strings (e.g. 'script-src')");
239
- }
240
- directives[i] = directives[i].toLowerCase();
241
- }
242
- var nonceBytes = opts.nonceBytes !== undefined ? opts.nonceBytes : DEFAULT_NONCE_BYTES;
243
- // Pre-fix the typeof-only check accepted Infinity / NaN — both
244
- // bypassed the `< MIN_NONCE_BYTES` guard (NaN < N is always false,
245
- // Infinity < N is always false), then crashed per-request when
246
- // `crypto.generateBytes(Infinity)` hit ERR_OUT_OF_RANGE. Route through
247
- // shared numeric-bounds (positive finite int) before the lower-bound
248
- // check so the typo / coercion is caught at create() time.
249
- if (!numericBounds.isPositiveFiniteInt(nonceBytes)) {
250
- throw new CspNonceError("csp-nonce/bad-nonce-bytes",
251
- "nonceBytes must be a positive finite integer; got " +
252
- numericBounds.shape(nonceBytes));
253
- }
254
- if (nonceBytes < MIN_NONCE_BYTES) {
255
- throw new CspNonceError("csp-nonce/bad-nonce-bytes",
256
- "nonceBytes must be >= " + MIN_NONCE_BYTES + " (got " + nonceBytes + "). " +
257
- "CSP nonces below 128 bits weaken the security boundary.");
258
- }
259
- var strictDynamic = !!opts.strictDynamic;
260
- var headerName = opts.headerName || "Content-Security-Policy";
261
- var property = (typeof opts.property === "string" && opts.property.length > 0) ? opts.property : "cspNonce";
262
- var always = !!opts.always;
263
-
264
- // Token string used by the cacheable-render pattern: templates render
265
- // with `cspNonce: nonceMw.PLACEHOLDER`, the rendered HTML is cached,
266
- // then nonceMw.substitute(html, req) swaps in the per-request nonce
267
- // at serve time. Per-instance random by default — multiple cspNonce
268
- // instances in the same process get different placeholders, and the
269
- // literal string never appears in source so operator content can't
270
- // accidentally collide.
271
- //
272
- // Operators with caches that persist across process restarts (Redis,
273
- // cluster backend) pass `opts.placeholder` to pin a stable token —
274
- // otherwise cached HTML rendered before restart still contains the
275
- // old placeholder, and substitute() finds nothing to replace.
276
- //
277
- // Validation tier: A (config-time throw). A typo'd placeholder type
278
- // is the kind of bug that surfaces three days later as "scripts
279
- // intermittently broken in production"; throwing at create() catches
280
- // it at app boot.
281
- var placeholder;
282
- if (opts.placeholder === undefined) {
283
- // OS-RNG → SHAKE256 → hex via the framework random helper.
284
- placeholder = PLACEHOLDER_PREFIX +
285
- crypto.generateToken(PLACEHOLDER_RAND_BYTES) +
286
- PLACEHOLDER_SUFFIX;
287
- } else if (typeof opts.placeholder !== "string" || opts.placeholder.length === 0) {
288
- throw new CspNonceError("csp-nonce/bad-placeholder",
289
- "placeholder must be a non-empty string (got " + typeof opts.placeholder + " " +
290
- JSON.stringify(opts.placeholder) + "). Pass nothing to use the default per-instance random token.");
291
- } else {
292
- placeholder = opts.placeholder;
293
- }
294
-
295
- function cspNonce(req, res, next) {
296
- // Generate the nonce. Cheap (16 bytes from getrandom → SHAKE256 →
297
- // base64 encode); do it always for consistency unless `always:
298
- // false` was set explicitly.
299
- var nonce = crypto.generateBytes(nonceBytes).toString("base64");
300
-
301
- // Attach to req for handler access.
302
- req[property] = nonce;
303
- // Attach to res.locals for template-data auto-merge (render.js).
304
- if (!res.locals || typeof res.locals !== "object") res.locals = {};
305
- res.locals[property] = nonce;
306
-
307
- if (typeof res.setHeader !== "function" || typeof res.getHeader !== "function") {
308
- // Plain object response (test mock without setHeader). Skip header
309
- // patching; the operator's still got req.cspNonce.
310
- return next();
311
- }
312
-
313
- // Patch the CSP header. If security-headers already set one, mutate
314
- // it; otherwise build a fresh minimal CSP. Operators who DON'T want
315
- // a CSP header set when none exists pass `always: false` (default
316
- // behavior is to set one).
317
- var existing = res.getHeader(headerName);
318
- if (!existing && !always) {
319
- // No existing CSP and operator didn't ask for always — leave
320
- // alone. The req.cspNonce is still available for templates that
321
- // want to use it.
322
- return next();
323
- }
324
- var patched = _injectNonce(existing, nonce, directives, strictDynamic);
325
- res.setHeader(headerName, patched);
326
- return next();
327
- }
328
-
329
- // Cacheable-render API on the returned middleware. The PLACEHOLDER
330
- // is per-instance random (or operator-pinned via opts.placeholder).
331
- // Templates render with `cspNonce: nonceMw.PLACEHOLDER` and the
332
- // rendered HTML is safe to cache; at serve time, call
333
- // `nonceMw.substitute(html, req)` on the cache hit so the script
334
- // tag's nonce attribute matches the response's per-request CSP nonce.
335
- cspNonce.PLACEHOLDER = placeholder;
336
- cspNonce.substitute = _buildSubstitute(placeholder, property);
337
- return cspNonce;
338
- }
339
-
340
- module.exports = {
341
- create: create,
342
- CspNonceError: CspNonceError,
343
- DEFAULT_DIRECTIVES: DEFAULT_DIRECTIVES,
344
- // Internal helpers exposed for tests
345
- _injectNonce: _injectNonce,
346
- _parseCsp: _parseCsp,
347
- _serializeCsp: _serializeCsp,
348
- };
1
+ "use strict";
2
+ /**
3
+ * csp-nonce — per-request CSP nonce + render integration.
4
+ *
5
+ * The framework's `security-headers` middleware ships a strict CSP
6
+ * that doesn't allow inline scripts (no 'unsafe-inline'). Templates
7
+ * with inline `<script>` blocks therefore break out of the box — the
8
+ * browser refuses to execute them. This middleware closes the gap:
9
+ *
10
+ * 1. Generate a fresh random nonce per request (base64, default
11
+ * 16 bytes / 22 chars).
12
+ * 2. Attach it to `req.cspNonce` (handler-readable) AND
13
+ * `res.locals.cspNonce` (template-data-readable — render.js
14
+ * auto-merges res.locals into template data).
15
+ * 3. Patch the existing Content-Security-Policy header set by
16
+ * security-headers — append `'nonce-XYZ'` to the operator-
17
+ * configured directives (defaults: script-src, style-src).
18
+ * If no CSP header is set yet, build a minimal one.
19
+ *
20
+ * Operators wire it after security-headers and write `nonce="..."`
21
+ * on their inline scripts:
22
+ *
23
+ * router.use(b.middleware.securityHeaders());
24
+ * router.use(b.middleware.cspNonce({
25
+ * directives: ["script-src", "style-src"],
26
+ * nonceBytes: 16,
27
+ * strictDynamic: true,
28
+ * }));
29
+ *
30
+ * // In a template:
31
+ * // <script nonce="{{ cspNonce }}">console.log("ok")</script>
32
+ * //
33
+ * // Or in a handler:
34
+ * // res.write('<script nonce="' + req.cspNonce + '">...</script>');
35
+ *
36
+ * Handler shape: req.cspNonce is the raw base64 nonce. Templates
37
+ * receive it via the auto-merged res.locals so the html() render
38
+ * helper doesn't need an extra argument — the operator just writes
39
+ * `{{ cspNonce }}` in the view.
40
+ *
41
+ * strict-dynamic mode (opt-in): when true, the nonce directive also
42
+ * gets `'strict-dynamic'`. Modern browsers then trust scripts loaded
43
+ * by a nonced script — no need to allowlist their origins. This is
44
+ * the recommended posture for SPA hydration scripts that themselves
45
+ * load dependencies (e.g. tiny inline bootstrap that imports a
46
+ * versioned bundle). See https://www.w3.org/TR/CSP3/#strict-dynamic-usage.
47
+ *
48
+ * Nonce strength:
49
+ * - Default 16 bytes (128 bits) of crypto-strong randomness via
50
+ * `b.crypto.generateBytes` (OS-RNG → SHAKE256). Standard for
51
+ * CSP nonces.
52
+ * - Operators with stricter posture set nonceBytes: 32 (256 bits).
53
+ * - Going below 16 bytes is refused at config time.
54
+ *
55
+ * Cacheable-render pattern (when the response HTML is cached but the
56
+ * CSP header rotates per request):
57
+ *
58
+ * var nonceMw = b.middleware.cspNonce();
59
+ * router.use(nonceMw);
60
+ *
61
+ * var pageCache = b.cache.create({ namespace: "wiki", ttlMs: 5*60_000 });
62
+ *
63
+ * router.get("/:slug", async function (req, res) {
64
+ * var html = await pageCache.wrap(req.params.slug, function () {
65
+ * // Render with the placeholder — the cached string contains a
66
+ * // stable token, never a request-specific nonce. Safe to cache.
67
+ * return template.render("page", {
68
+ * cspNonce: nonceMw.PLACEHOLDER,
69
+ * ...,
70
+ * });
71
+ * });
72
+ * // Replace the placeholder with this request's nonce so the
73
+ * // script tag's nonce attribute matches the CSP header.
74
+ * res.send(nonceMw.substitute(html, req));
75
+ * });
76
+ *
77
+ * Without this pattern, caching HTML rendered with `{{ cspNonce }}`
78
+ * captures the FIRST request's nonce and reuses it on every cache
79
+ * hit — the response's CSP header rotates per request, so script
80
+ * tags carry a stale nonce the browser refuses. Symptom: scripts
81
+ * silently fail to execute on every cache hit after the first.
82
+ *
83
+ * The placeholder is per-instance random by default — operators with
84
+ * caches that survive process restart (Redis, cluster backend) pin
85
+ * a stable token via `opts.placeholder` so HTML cached before the
86
+ * restart still substitutes correctly after.
87
+ *
88
+ * What `substitute()` does NOT do (deferred — structural reasons):
89
+ * - Streaming substitution across chunk boundaries. `substitute()`
90
+ * takes a complete HTML string. Operators streaming HTML in
91
+ * chunks (Node Writable, fs.createReadStream → res piping cached
92
+ * bytes) must concatenate first or call substitute on each chunk
93
+ * where the placeholder is guaranteed not to span a boundary.
94
+ * A buffered streaming version requires per-stream state to
95
+ * hold up to (PLACEHOLDER.length - 1) bytes between chunks; that
96
+ * surface gets its own primitive when an operator hits it.
97
+ *
98
+ * What this middleware does NOT do:
99
+ * - It doesn't ALSO set 'unsafe-inline'. The browser silently ignores
100
+ * 'unsafe-inline' when a nonce is present (CSP3 spec), so this is
101
+ * a non-issue, but operators sometimes add 'unsafe-inline' "just
102
+ * in case" — that defeats the entire point of the nonce.
103
+ * - It doesn't attempt to strip 'unsafe-inline' from operator-
104
+ * supplied CSP. If the operator configured 'unsafe-inline' and
105
+ * adds csp-nonce, both are present; the browser ignores
106
+ * 'unsafe-inline' but the static analysis tool might still flag
107
+ * it. Removing operator-supplied directives without explicit
108
+ * consent is more astonishing than helpful.
109
+ * - It doesn't generate nonces for non-HTML responses (JSON, raw
110
+ * bytes). The middleware skips when there's no template / inline-
111
+ * script context — operators who want a nonce on every response
112
+ * pass `always: true`.
113
+ */
114
+
115
+ var C = require("../constants");
116
+ var crypto = require("../crypto");
117
+ var numericBounds = require("../numeric-bounds");
118
+ var validateOpts = require("../validate-opts");
119
+ var { defineClass } = require("../framework-error");
120
+
121
+ var CspNonceError = defineClass("CspNonceError", { alwaysPermanent: true });
122
+
123
+ var DEFAULT_DIRECTIVES = Object.freeze(["script-src", "style-src"]);
124
+ var DEFAULT_NONCE_BYTES = C.BYTES.bytes(16);
125
+ var MIN_NONCE_BYTES = C.BYTES.bytes(16);
126
+ var PLACEHOLDER_PREFIX = "__BLAMEJS_CSP_NONCE_";
127
+ var PLACEHOLDER_SUFFIX = "__";
128
+ // 16 bytes / 128 bits — matches the default nonce strength so the
129
+ // placeholder is no weaker than the value it stands in for.
130
+ var PLACEHOLDER_RAND_BYTES = C.BYTES.bytes(16);
131
+
132
+ // Build the substitute helper for a specific placeholder + property.
133
+ // Each cspNonce instance has its own placeholder (random by default,
134
+ // stable per process) so multiple middleware instances in the same app
135
+ // don't share state, and operator content can't accidentally match a
136
+ // hardcoded string that lives in source.
137
+ function _buildSubstitute(placeholder, property) {
138
+ return function substitute(html, reqOrNonce) {
139
+ if (typeof html !== "string" || html.length === 0) return html;
140
+ if (html.indexOf(placeholder) === -1) return html;
141
+ var nonce;
142
+ if (typeof reqOrNonce === "string") {
143
+ nonce = reqOrNonce;
144
+ } else if (reqOrNonce && typeof reqOrNonce === "object") {
145
+ nonce = reqOrNonce[property] ||
146
+ (reqOrNonce.res && reqOrNonce.res.locals && reqOrNonce.res.locals[property]) ||
147
+ "";
148
+ } else {
149
+ nonce = "";
150
+ }
151
+ return html.split(placeholder).join(nonce);
152
+ };
153
+ }
154
+
155
+ // Build a fresh CSP from scratch when none is set. Conservative defaults
156
+ // — the nonced directive replaces what 'unsafe-inline' would have done.
157
+ function _defaultCsp(nonceToken) {
158
+ return "default-src 'self'; " +
159
+ "script-src 'self' " + nonceToken + "; " +
160
+ "style-src 'self' " + nonceToken + "; " +
161
+ "img-src 'self' data:; " +
162
+ "frame-ancestors 'none'; " +
163
+ "base-uri 'self'; " +
164
+ "form-action 'self'; " +
165
+ "object-src 'none'";
166
+ }
167
+
168
+ // Parse the CSP header into [{ name, valueParts }] preserving operator
169
+ // ordering. Each entry is `directive-name [value...]`.
170
+ function _parseCsp(headerValue) {
171
+ var parts = String(headerValue).split(";");
172
+ var out = [];
173
+ for (var i = 0; i < parts.length; i++) {
174
+ var p = parts[i].trim();
175
+ if (p.length === 0) continue;
176
+ // Split on whitespace runs.
177
+ var tokens = p.split(/\s+/);
178
+ var name = tokens.shift().toLowerCase();
179
+ out.push({ name: name, values: tokens });
180
+ }
181
+ return out;
182
+ }
183
+
184
+ function _serializeCsp(parts) {
185
+ return parts.map(function (p) {
186
+ if (p.values.length === 0) return p.name;
187
+ return p.name + " " + p.values.join(" ");
188
+ }).join("; ");
189
+ }
190
+
191
+ function _injectNonce(cspHeader, nonce, directives, strictDynamic) {
192
+ var nonceToken = "'nonce-" + nonce + "'";
193
+ if (!cspHeader) {
194
+ // Build a minimal CSP from scratch. strictDynamic isn't applied
195
+ // to a fresh CSP because the operator hasn't told us their script
196
+ // load pattern yet — they can opt in by combining their own CSP
197
+ // with cspNonce.
198
+ return _defaultCsp(nonceToken);
199
+ }
200
+ var parts = _parseCsp(cspHeader);
201
+ var seen = Object.create(null);
202
+ for (var i = 0; i < parts.length; i++) {
203
+ var name = parts[i].name;
204
+ seen[name] = i;
205
+ if (directives.indexOf(name) !== -1) {
206
+ // Avoid duplicate nonce tokens if the middleware ever runs twice.
207
+ if (parts[i].values.indexOf(nonceToken) === -1) {
208
+ parts[i].values.push(nonceToken);
209
+ }
210
+ // strict-dynamic only meaningful for script-src.
211
+ if (strictDynamic && name === "script-src" && parts[i].values.indexOf("'strict-dynamic'") === -1) {
212
+ parts[i].values.push("'strict-dynamic'");
213
+ }
214
+ }
215
+ }
216
+ // Add target directives that were missing from the original CSP.
217
+ for (var j = 0; j < directives.length; j++) {
218
+ var d = directives[j].toLowerCase();
219
+ if (Object.prototype.hasOwnProperty.call(seen, d)) continue;
220
+ var values = [nonceToken];
221
+ if (strictDynamic && d === "script-src") values.push("'strict-dynamic'");
222
+ parts.push({ name: d, values: values });
223
+ }
224
+ return _serializeCsp(parts);
225
+ }
226
+
227
+ function create(opts) {
228
+ opts = opts || {};
229
+ validateOpts(opts, [
230
+ "directives", "nonceBytes", "strictDynamic", "headerName",
231
+ "property", "always", "placeholder",
232
+ ], "middleware.cspNonce");
233
+ var directives = Array.isArray(opts.directives) && opts.directives.length > 0
234
+ ? opts.directives.slice() : DEFAULT_DIRECTIVES.slice();
235
+ for (var i = 0; i < directives.length; i++) {
236
+ if (typeof directives[i] !== "string" || directives[i].length === 0) {
237
+ throw new CspNonceError("csp-nonce/bad-directive",
238
+ "directives must be non-empty strings (e.g. 'script-src')");
239
+ }
240
+ directives[i] = directives[i].toLowerCase();
241
+ }
242
+ var nonceBytes = opts.nonceBytes !== undefined ? opts.nonceBytes : DEFAULT_NONCE_BYTES;
243
+ // Pre-fix the typeof-only check accepted Infinity / NaN — both
244
+ // bypassed the `< MIN_NONCE_BYTES` guard (NaN < N is always false,
245
+ // Infinity < N is always false), then crashed per-request when
246
+ // `crypto.generateBytes(Infinity)` hit ERR_OUT_OF_RANGE. Route through
247
+ // shared numeric-bounds (positive finite int) before the lower-bound
248
+ // check so the typo / coercion is caught at create() time.
249
+ if (!numericBounds.isPositiveFiniteInt(nonceBytes)) {
250
+ throw new CspNonceError("csp-nonce/bad-nonce-bytes",
251
+ "nonceBytes must be a positive finite integer; got " +
252
+ numericBounds.shape(nonceBytes));
253
+ }
254
+ if (nonceBytes < MIN_NONCE_BYTES) {
255
+ throw new CspNonceError("csp-nonce/bad-nonce-bytes",
256
+ "nonceBytes must be >= " + MIN_NONCE_BYTES + " (got " + nonceBytes + "). " +
257
+ "CSP nonces below 128 bits weaken the security boundary.");
258
+ }
259
+ var strictDynamic = !!opts.strictDynamic;
260
+ var headerName = opts.headerName || "Content-Security-Policy";
261
+ var property = (typeof opts.property === "string" && opts.property.length > 0) ? opts.property : "cspNonce";
262
+ var always = !!opts.always;
263
+
264
+ // Token string used by the cacheable-render pattern: templates render
265
+ // with `cspNonce: nonceMw.PLACEHOLDER`, the rendered HTML is cached,
266
+ // then nonceMw.substitute(html, req) swaps in the per-request nonce
267
+ // at serve time. Per-instance random by default — multiple cspNonce
268
+ // instances in the same process get different placeholders, and the
269
+ // literal string never appears in source so operator content can't
270
+ // accidentally collide.
271
+ //
272
+ // Operators with caches that persist across process restarts (Redis,
273
+ // cluster backend) pass `opts.placeholder` to pin a stable token —
274
+ // otherwise cached HTML rendered before restart still contains the
275
+ // old placeholder, and substitute() finds nothing to replace.
276
+ //
277
+ // Validation tier: A (config-time throw). A typo'd placeholder type
278
+ // is the kind of bug that surfaces three days later as "scripts
279
+ // intermittently broken in production"; throwing at create() catches
280
+ // it at app boot.
281
+ var placeholder;
282
+ if (opts.placeholder === undefined) {
283
+ // OS-RNG → SHAKE256 → hex via the framework random helper.
284
+ placeholder = PLACEHOLDER_PREFIX +
285
+ crypto.generateToken(PLACEHOLDER_RAND_BYTES) +
286
+ PLACEHOLDER_SUFFIX;
287
+ } else if (typeof opts.placeholder !== "string" || opts.placeholder.length === 0) {
288
+ throw new CspNonceError("csp-nonce/bad-placeholder",
289
+ "placeholder must be a non-empty string (got " + typeof opts.placeholder + " " +
290
+ JSON.stringify(opts.placeholder) + "). Pass nothing to use the default per-instance random token.");
291
+ } else {
292
+ placeholder = opts.placeholder;
293
+ }
294
+
295
+ function cspNonce(req, res, next) {
296
+ // Generate the nonce. Cheap (16 bytes from getrandom → SHAKE256 →
297
+ // base64 encode); do it always for consistency unless `always:
298
+ // false` was set explicitly.
299
+ var nonce = crypto.generateBytes(nonceBytes).toString("base64");
300
+
301
+ // Attach to req for handler access.
302
+ req[property] = nonce;
303
+ // Attach to res.locals for template-data auto-merge (render.js).
304
+ if (!res.locals || typeof res.locals !== "object") res.locals = {};
305
+ res.locals[property] = nonce;
306
+
307
+ if (typeof res.setHeader !== "function" || typeof res.getHeader !== "function") {
308
+ // Plain object response (test mock without setHeader). Skip header
309
+ // patching; the operator's still got req.cspNonce.
310
+ return next();
311
+ }
312
+
313
+ // Patch the CSP header. If security-headers already set one, mutate
314
+ // it; otherwise build a fresh minimal CSP. Operators who DON'T want
315
+ // a CSP header set when none exists pass `always: false` (default
316
+ // behavior is to set one).
317
+ var existing = res.getHeader(headerName);
318
+ if (!existing && !always) {
319
+ // No existing CSP and operator didn't ask for always — leave
320
+ // alone. The req.cspNonce is still available for templates that
321
+ // want to use it.
322
+ return next();
323
+ }
324
+ var patched = _injectNonce(existing, nonce, directives, strictDynamic);
325
+ res.setHeader(headerName, patched);
326
+ return next();
327
+ }
328
+
329
+ // Cacheable-render API on the returned middleware. The PLACEHOLDER
330
+ // is per-instance random (or operator-pinned via opts.placeholder).
331
+ // Templates render with `cspNonce: nonceMw.PLACEHOLDER` and the
332
+ // rendered HTML is safe to cache; at serve time, call
333
+ // `nonceMw.substitute(html, req)` on the cache hit so the script
334
+ // tag's nonce attribute matches the response's per-request CSP nonce.
335
+ cspNonce.PLACEHOLDER = placeholder;
336
+ cspNonce.substitute = _buildSubstitute(placeholder, property);
337
+ return cspNonce;
338
+ }
339
+
340
+ module.exports = {
341
+ create: create,
342
+ CspNonceError: CspNonceError,
343
+ DEFAULT_DIRECTIVES: DEFAULT_DIRECTIVES,
344
+ // Internal helpers exposed for tests
345
+ _injectNonce: _injectNonce,
346
+ _parseCsp: _parseCsp,
347
+ _serializeCsp: _serializeCsp,
348
+ };