@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,236 @@
1
+ "use strict";
2
+ /**
3
+ * CORS middleware — allow-list-only by default. No '*' wildcard support
4
+ * for credentialed requests (which spec disallows anyway). Operators must
5
+ * explicitly enumerate origins they trust.
6
+ *
7
+ * Same-origin requests pass through without consulting the allow-list:
8
+ * the Fetch spec instructs browsers to send an Origin header on every
9
+ * POST / PUT / PATCH / DELETE — even same-origin ones — so an empty
10
+ * allow-list would otherwise refuse the operator's own login form.
11
+ * Same-origin is detected by:
12
+ * 1. Origin === opts.siteOrigin if configured (explicit, recommended —
13
+ * works behind TLS-terminating proxies where the framework can't
14
+ * infer scheme), or
15
+ * 2. Origin === request's inferred scheme/host/port (from req.socket
16
+ * and req.headers.host — correct for direct deployments), or
17
+ * 3. Origin == "null" AND Sec-Fetch-Site == "same-origin" or "none".
18
+ * Browsers send `Origin: null` on form-navigation POSTs from a
19
+ * page whose response carries `Referrer-Policy: no-referrer` (or
20
+ * similarly strict policy) — the Origin is opaqued to prevent a
21
+ * cross-site leak of the page's origin. Sec-Fetch-Site is the
22
+ * Fetch-metadata signal that distinguishes a same-origin nav
23
+ * from a genuine cross-site post in that opaque-origin world.
24
+ *
25
+ * Options:
26
+ * {
27
+ * origins: [ 'https://app.example.com', /^https:\/\/.+\.example\.com$/ ]
28
+ * siteOrigin: 'https://wiki.example.com' // string OR array
29
+ * methods: [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH' ]
30
+ * headers: [ 'Content-Type', 'Authorization', 'X-Request-Id' ]
31
+ * exposeHeaders: [ 'X-Request-Id', 'X-Response-Time' ]
32
+ * credentials: true (sets Access-Control-Allow-Credentials: true)
33
+ * maxAgeSeconds: 600
34
+ * refuseUnknown: true (refuse cross-origin requests from unlisted
35
+ * origins instead of just omitting CORS headers)
36
+ * }
37
+ *
38
+ * Audit: refuseUnknown blocks emit system.cors.block with the offending Origin.
39
+ *
40
+ * Validation tier: Tier A (config-time throw) — opts.siteOrigin must
41
+ * parse as an http(s) URL, opts.origins entries must be strings or
42
+ * RegExp. Bad config surfaces at create() not at first cross-origin
43
+ * request.
44
+ */
45
+ var lazyRequire = require("../lazy-require");
46
+ var audit = lazyRequire(function () { return require("../audit"); });
47
+ var safeUrl = require("../safe-url");
48
+ var validateOpts = require("../validate-opts");
49
+ var { defineClass } = require("../framework-error");
50
+
51
+ var CorsError = defineClass("CorsError", { alwaysPermanent: true });
52
+
53
+ function _matchOrigin(origin, allowList) {
54
+ if (!origin) return null;
55
+ for (var i = 0; i < allowList.length; i++) {
56
+ var entry = allowList[i];
57
+ if (typeof entry === "string" && entry === origin) return origin;
58
+ if (entry instanceof RegExp && entry.test(origin)) return origin;
59
+ }
60
+ return null;
61
+ }
62
+
63
+ // Normalize an origin string by parsing it through safeUrl and
64
+ // returning `protocol//host[:port]` with no trailing slash. Used for
65
+ // equality checks that have to handle case differences and the URL
66
+ // parser's auto-port-omission for default ports (80/443).
67
+ //
68
+ // safeUrl defaults to ALLOW_HTTP_TLS (https only). CORS origins
69
+ // legitimately include http for local dev; pass ALLOW_HTTP_ALL.
70
+ function _canonicalOrigin(input) {
71
+ if (!input || typeof input !== "string") return null;
72
+ try {
73
+ var parsed = safeUrl.parse(input, { allowedProtocols: safeUrl.ALLOW_HTTP_ALL });
74
+ var proto = parsed.protocol; // "http:" or "https:"
75
+ var host = parsed.hostname.toLowerCase();
76
+ var port = parsed.port; // "" when default
77
+ return proto + "//" + host + (port ? ":" + port : "");
78
+ } catch (_e) {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ // Build the request's own origin from req when opts.siteOrigin isn't
84
+ // supplied. Works for direct deployments (no proxy); operators behind
85
+ // a TLS-terminating proxy that doesn't forward correct Host should set
86
+ // opts.siteOrigin explicitly.
87
+ function _inferRequestOrigin(req) {
88
+ if (!req || !req.headers) return null;
89
+ var host = req.headers.host;
90
+ if (!host) return null;
91
+ // X-Forwarded-Proto wins when present (operator behind a TLS-
92
+ // terminator, intermediate set the header). Otherwise infer from
93
+ // the socket — req.socket.encrypted is set by node:tls.
94
+ var fwdProto = req.headers["x-forwarded-proto"];
95
+ var proto;
96
+ if (typeof fwdProto === "string" && fwdProto.length > 0) {
97
+ proto = fwdProto.split(",")[0].trim().toLowerCase();
98
+ } else if (req.socket && req.socket.encrypted) {
99
+ proto = "https";
100
+ } else {
101
+ proto = "http";
102
+ }
103
+ return _canonicalOrigin(proto + "://" + host);
104
+ }
105
+
106
+ function _isSameOrigin(req, originHeader, configuredSiteOrigins) {
107
+ // Origin: null + Sec-Fetch-Site: same-origin|none — browser opaqued
108
+ // the Origin (typically because of Referrer-Policy: no-referrer on the
109
+ // page) but is also explicitly telling us the request is same-origin.
110
+ // Trust the Fetch-metadata signal in that case.
111
+ if (originHeader === "null") {
112
+ var sfs = req && req.headers && req.headers["sec-fetch-site"];
113
+ if (sfs === "same-origin" || sfs === "none") return true;
114
+ return false;
115
+ }
116
+ var canonOrigin = _canonicalOrigin(originHeader);
117
+ if (!canonOrigin) return false;
118
+ // Operator-supplied site origins take priority — they're the
119
+ // authoritative source for "this request is one of mine".
120
+ if (configuredSiteOrigins && configuredSiteOrigins.length > 0) {
121
+ for (var i = 0; i < configuredSiteOrigins.length; i++) {
122
+ if (configuredSiteOrigins[i] === canonOrigin) return true;
123
+ }
124
+ return false;
125
+ }
126
+ // Fall back to inferring from the request itself.
127
+ var reqOrigin = _inferRequestOrigin(req);
128
+ return reqOrigin !== null && reqOrigin === canonOrigin;
129
+ }
130
+
131
+ function create(opts) {
132
+ opts = opts || {};
133
+
134
+ validateOpts(opts, [
135
+ "origins", "siteOrigin", "methods", "headers", "exposeHeaders",
136
+ "credentials", "maxAgeSeconds", "refuseUnknown",
137
+ ], "middleware.cors");
138
+
139
+ var origins = opts.origins || [];
140
+
141
+ // Tier A validation on opts.origins — strings or RegExp only.
142
+ for (var oi = 0; oi < origins.length; oi++) {
143
+ var entry = origins[oi];
144
+ if (typeof entry !== "string" && !(entry instanceof RegExp)) {
145
+ throw new CorsError("cors/bad-origin",
146
+ "origins[" + oi + "] must be a string or RegExp (got " + typeof entry + ")");
147
+ }
148
+ }
149
+
150
+ // Tier A validation on opts.siteOrigin — must parse as http(s) URL.
151
+ // Accept string OR array of strings.
152
+ var siteOrigins = [];
153
+ if (opts.siteOrigin !== undefined && opts.siteOrigin !== null) {
154
+ var rawList = Array.isArray(opts.siteOrigin) ? opts.siteOrigin : [opts.siteOrigin];
155
+ for (var si = 0; si < rawList.length; si++) {
156
+ var raw = rawList[si];
157
+ if (typeof raw !== "string" || raw.length === 0) {
158
+ throw new CorsError("cors/bad-site-origin",
159
+ "siteOrigin[" + si + "] must be a non-empty string (got " + typeof raw + ")");
160
+ }
161
+ var canon = _canonicalOrigin(raw);
162
+ if (!canon) {
163
+ throw new CorsError("cors/bad-site-origin",
164
+ "siteOrigin[" + si + "]='" + raw + "' is not a parseable http(s) URL");
165
+ }
166
+ siteOrigins.push(canon);
167
+ }
168
+ }
169
+
170
+ var methods = (opts.methods || ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).join(", ");
171
+ var headers = (opts.headers || ["Content-Type", "Authorization", "X-Request-Id"]).join(", ");
172
+ var exposeHeaders = (opts.exposeHeaders || ["X-Request-Id"]).join(", ");
173
+ var credentials = !!opts.credentials;
174
+ var maxAge = String(opts.maxAgeSeconds || 600);
175
+ var refuseUnknown = opts.refuseUnknown !== false;
176
+
177
+ return function cors(req, res, next) {
178
+ var origin = req.headers && req.headers.origin;
179
+ if (!origin) return next(); // not a cross-origin request
180
+
181
+ // Same-origin POST/PUT/etc. carry an Origin header per the Fetch
182
+ // spec but should not be subject to CORS allow-listing — they're
183
+ // the operator's own site talking to itself.
184
+ if (_isSameOrigin(req, origin, siteOrigins)) return next();
185
+
186
+ var matched = _matchOrigin(origin, origins);
187
+ if (!matched) {
188
+ if (refuseUnknown) {
189
+ try {
190
+ audit().emit({
191
+ actor: { ip: (req.headers && req.headers["x-forwarded-for"]) || (req.socket && req.socket.remoteAddress) },
192
+ action: "system.cors.block",
193
+ outcome: "denied",
194
+ reason: "origin not in allow-list",
195
+ metadata: { origin: origin, method: req.method, path: req.pathname || req.url, requestId: req.requestId },
196
+ requestId: req.requestId,
197
+ });
198
+ } catch (_e) {}
199
+ if (typeof res.writeHead === "function") {
200
+ res.writeHead(403, { "Content-Type": "text/plain" });
201
+ res.end("CORS: origin not allowed");
202
+ return;
203
+ }
204
+ }
205
+ return next(); // permissive mode: just don't set CORS headers
206
+ }
207
+
208
+ if (typeof res.setHeader === "function") {
209
+ res.setHeader("Access-Control-Allow-Origin", matched);
210
+ res.setHeader("Vary", "Origin");
211
+ if (credentials) res.setHeader("Access-Control-Allow-Credentials", "true");
212
+ res.setHeader("Access-Control-Expose-Headers", exposeHeaders);
213
+ }
214
+
215
+ if (req.method === "OPTIONS" && req.headers["access-control-request-method"]) {
216
+ // Preflight
217
+ if (typeof res.setHeader === "function") {
218
+ res.setHeader("Access-Control-Allow-Methods", methods);
219
+ res.setHeader("Access-Control-Allow-Headers", headers);
220
+ res.setHeader("Access-Control-Max-Age", maxAge);
221
+ }
222
+ if (typeof res.writeHead === "function") {
223
+ res.writeHead(204);
224
+ res.end();
225
+ }
226
+ return;
227
+ }
228
+
229
+ next();
230
+ };
231
+ }
232
+
233
+ module.exports = {
234
+ create: create,
235
+ CorsError: CorsError,
236
+ };
@@ -0,0 +1,332 @@
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 crypto = require("../crypto");
116
+ var validateOpts = require("../validate-opts");
117
+ var { defineClass } = require("../framework-error");
118
+
119
+ var CspNonceError = defineClass("CspNonceError", { alwaysPermanent: true });
120
+
121
+ var DEFAULT_DIRECTIVES = Object.freeze(["script-src", "style-src"]);
122
+ var DEFAULT_NONCE_BYTES = 16;
123
+ var MIN_NONCE_BYTES = 16;
124
+ var PLACEHOLDER_PREFIX = "__BLAMEJS_CSP_NONCE_";
125
+ var PLACEHOLDER_SUFFIX = "__";
126
+ // 16 bytes / 128 bits — matches the default nonce strength so the
127
+ // placeholder is no weaker than the value it stands in for.
128
+ var PLACEHOLDER_RAND_BYTES = 16;
129
+
130
+ // Build the substitute helper for a specific placeholder + property.
131
+ // Each cspNonce instance has its own placeholder (random by default,
132
+ // stable per process) so multiple middleware instances in the same app
133
+ // don't share state, and operator content can't accidentally match a
134
+ // hardcoded string that lives in source.
135
+ function _buildSubstitute(placeholder, property) {
136
+ return function substitute(html, reqOrNonce) {
137
+ if (typeof html !== "string" || html.length === 0) return html;
138
+ if (html.indexOf(placeholder) === -1) return html;
139
+ var nonce;
140
+ if (typeof reqOrNonce === "string") {
141
+ nonce = reqOrNonce;
142
+ } else if (reqOrNonce && typeof reqOrNonce === "object") {
143
+ nonce = reqOrNonce[property] ||
144
+ (reqOrNonce.res && reqOrNonce.res.locals && reqOrNonce.res.locals[property]) ||
145
+ "";
146
+ } else {
147
+ nonce = "";
148
+ }
149
+ return html.split(placeholder).join(nonce);
150
+ };
151
+ }
152
+
153
+ // Build a fresh CSP from scratch when none is set. Conservative defaults
154
+ // — the nonced directive replaces what 'unsafe-inline' would have done.
155
+ function _defaultCsp(nonceToken) {
156
+ return "default-src 'self'; " +
157
+ "script-src 'self' " + nonceToken + "; " +
158
+ "style-src 'self' " + nonceToken + "; " +
159
+ "img-src 'self' data:; " +
160
+ "frame-ancestors 'none'; " +
161
+ "base-uri 'self'; " +
162
+ "form-action 'self'; " +
163
+ "object-src 'none'";
164
+ }
165
+
166
+ // Parse the CSP header into [{ name, valueParts }] preserving operator
167
+ // ordering. Each entry is `directive-name [value...]`.
168
+ function _parseCsp(headerValue) {
169
+ var parts = String(headerValue).split(";");
170
+ var out = [];
171
+ for (var i = 0; i < parts.length; i++) {
172
+ var p = parts[i].trim();
173
+ if (p.length === 0) continue;
174
+ // Split on whitespace runs.
175
+ var tokens = p.split(/\s+/);
176
+ var name = tokens.shift().toLowerCase();
177
+ out.push({ name: name, values: tokens });
178
+ }
179
+ return out;
180
+ }
181
+
182
+ function _serializeCsp(parts) {
183
+ return parts.map(function (p) {
184
+ if (p.values.length === 0) return p.name;
185
+ return p.name + " " + p.values.join(" ");
186
+ }).join("; ");
187
+ }
188
+
189
+ function _injectNonce(cspHeader, nonce, directives, strictDynamic) {
190
+ var nonceToken = "'nonce-" + nonce + "'";
191
+ if (!cspHeader) {
192
+ // Build a minimal CSP from scratch. strictDynamic isn't applied
193
+ // to a fresh CSP because the operator hasn't told us their script
194
+ // load pattern yet — they can opt in by combining their own CSP
195
+ // with cspNonce.
196
+ return _defaultCsp(nonceToken);
197
+ }
198
+ var parts = _parseCsp(cspHeader);
199
+ var seen = Object.create(null);
200
+ for (var i = 0; i < parts.length; i++) {
201
+ var name = parts[i].name;
202
+ seen[name] = i;
203
+ if (directives.indexOf(name) !== -1) {
204
+ // Avoid duplicate nonce tokens if the middleware ever runs twice.
205
+ if (parts[i].values.indexOf(nonceToken) === -1) {
206
+ parts[i].values.push(nonceToken);
207
+ }
208
+ // strict-dynamic only meaningful for script-src.
209
+ if (strictDynamic && name === "script-src" && parts[i].values.indexOf("'strict-dynamic'") === -1) {
210
+ parts[i].values.push("'strict-dynamic'");
211
+ }
212
+ }
213
+ }
214
+ // Add target directives that were missing from the original CSP.
215
+ for (var j = 0; j < directives.length; j++) {
216
+ var d = directives[j].toLowerCase();
217
+ if (Object.prototype.hasOwnProperty.call(seen, d)) continue;
218
+ var values = [nonceToken];
219
+ if (strictDynamic && d === "script-src") values.push("'strict-dynamic'");
220
+ parts.push({ name: d, values: values });
221
+ }
222
+ return _serializeCsp(parts);
223
+ }
224
+
225
+ function create(opts) {
226
+ opts = opts || {};
227
+ validateOpts(opts, [
228
+ "directives", "nonceBytes", "strictDynamic", "headerName",
229
+ "property", "always", "placeholder",
230
+ ], "middleware.cspNonce");
231
+ var directives = Array.isArray(opts.directives) && opts.directives.length > 0
232
+ ? opts.directives.slice() : DEFAULT_DIRECTIVES.slice();
233
+ for (var i = 0; i < directives.length; i++) {
234
+ if (typeof directives[i] !== "string" || directives[i].length === 0) {
235
+ throw new CspNonceError("csp-nonce/bad-directive",
236
+ "directives must be non-empty strings (e.g. 'script-src')");
237
+ }
238
+ directives[i] = directives[i].toLowerCase();
239
+ }
240
+ var nonceBytes = typeof opts.nonceBytes === "number" ? opts.nonceBytes : DEFAULT_NONCE_BYTES;
241
+ if (nonceBytes < MIN_NONCE_BYTES) {
242
+ throw new CspNonceError("csp-nonce/bad-nonce-bytes",
243
+ "nonceBytes must be >= " + MIN_NONCE_BYTES + " (got " + nonceBytes + "). " +
244
+ "CSP nonces below 128 bits weaken the security boundary.");
245
+ }
246
+ var strictDynamic = !!opts.strictDynamic;
247
+ var headerName = opts.headerName || "Content-Security-Policy";
248
+ var property = (typeof opts.property === "string" && opts.property.length > 0) ? opts.property : "cspNonce";
249
+ var always = !!opts.always;
250
+
251
+ // Placeholder for the cacheable-render pattern. Per-instance random
252
+ // by default — multiple cspNonce instances in the same process get
253
+ // different placeholders, and the literal string never appears in
254
+ // source so operator content can't accidentally collide.
255
+ //
256
+ // Operators with caches that persist across process restarts (Redis,
257
+ // cluster backend) pass `opts.placeholder` to pin a stable token —
258
+ // otherwise cached HTML rendered before restart still contains the
259
+ // old placeholder, and substitute() finds nothing to replace.
260
+ //
261
+ // Validation tier: A (config-time throw). A typo'd placeholder type
262
+ // is the kind of bug that surfaces three days later as "scripts
263
+ // intermittently broken in production"; throwing at create() catches
264
+ // it at app boot.
265
+ var placeholder;
266
+ if (opts.placeholder === undefined) {
267
+ // OS-RNG → SHAKE256 → hex via the framework random helper.
268
+ placeholder = PLACEHOLDER_PREFIX +
269
+ crypto.generateToken(PLACEHOLDER_RAND_BYTES) +
270
+ PLACEHOLDER_SUFFIX;
271
+ } else if (typeof opts.placeholder !== "string" || opts.placeholder.length === 0) {
272
+ throw new CspNonceError("csp-nonce/bad-placeholder",
273
+ "placeholder must be a non-empty string (got " + typeof opts.placeholder + " " +
274
+ JSON.stringify(opts.placeholder) + "). Pass nothing to use the default per-instance random token.");
275
+ } else {
276
+ placeholder = opts.placeholder;
277
+ }
278
+
279
+ function cspNonce(req, res, next) {
280
+ // Generate the nonce. Cheap (16 bytes from getrandom → SHAKE256 →
281
+ // base64 encode); do it always for consistency unless `always:
282
+ // false` was set explicitly.
283
+ var nonce = crypto.generateBytes(nonceBytes).toString("base64");
284
+
285
+ // Attach to req for handler access.
286
+ req[property] = nonce;
287
+ // Attach to res.locals for template-data auto-merge (render.js).
288
+ if (!res.locals || typeof res.locals !== "object") res.locals = {};
289
+ res.locals[property] = nonce;
290
+
291
+ if (typeof res.setHeader !== "function" || typeof res.getHeader !== "function") {
292
+ // Plain object response (test mock without setHeader). Skip header
293
+ // patching; the operator's still got req.cspNonce.
294
+ return next();
295
+ }
296
+
297
+ // Patch the CSP header. If security-headers already set one, mutate
298
+ // it; otherwise build a fresh minimal CSP. Operators who DON'T want
299
+ // a CSP header set when none exists pass `always: false` (default
300
+ // behavior is to set one).
301
+ var existing = res.getHeader(headerName);
302
+ if (!existing && !always) {
303
+ // No existing CSP and operator didn't ask for always — leave
304
+ // alone. The req.cspNonce is still available for templates that
305
+ // want to use it.
306
+ return next();
307
+ }
308
+ var patched = _injectNonce(existing, nonce, directives, strictDynamic);
309
+ res.setHeader(headerName, patched);
310
+ return next();
311
+ }
312
+
313
+ // Cacheable-render API on the returned middleware. The PLACEHOLDER
314
+ // is per-instance random (or operator-pinned via opts.placeholder).
315
+ // Templates render with `cspNonce: nonceMw.PLACEHOLDER` and the
316
+ // rendered HTML is safe to cache; at serve time, call
317
+ // `nonceMw.substitute(html, req)` on the cache hit so the script
318
+ // tag's nonce attribute matches the response's per-request CSP nonce.
319
+ cspNonce.PLACEHOLDER = placeholder;
320
+ cspNonce.substitute = _buildSubstitute(placeholder, property);
321
+ return cspNonce;
322
+ }
323
+
324
+ module.exports = {
325
+ create: create,
326
+ CspNonceError: CspNonceError,
327
+ DEFAULT_DIRECTIVES: DEFAULT_DIRECTIVES,
328
+ // Internal helpers exposed for tests
329
+ _injectNonce: _injectNonce,
330
+ _parseCsp: _parseCsp,
331
+ _serializeCsp: _serializeCsp,
332
+ };