@blamejs/core 0.7.18 → 0.7.20

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 (169) hide show
  1. package/CHANGELOG.md +427 -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 +350 -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 +399 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/fetch-metadata.js +129 -0
  86. package/lib/middleware/health.js +392 -392
  87. package/lib/middleware/index.js +85 -79
  88. package/lib/middleware/rate-limit.js +358 -358
  89. package/lib/middleware/request-id.js +61 -61
  90. package/lib/middleware/request-log.js +168 -168
  91. package/lib/middleware/require-auth.js +104 -104
  92. package/lib/middleware/security-headers.js +121 -116
  93. package/lib/middleware/sse.js +166 -166
  94. package/lib/migrations.js +383 -383
  95. package/lib/mtls-ca.js +518 -518
  96. package/lib/mtls-engine-default.js +481 -481
  97. package/lib/network-dns.js +632 -632
  98. package/lib/network-heartbeat.js +290 -290
  99. package/lib/network-nts.js +574 -574
  100. package/lib/network-proxy.js +265 -265
  101. package/lib/network-tls.js +328 -328
  102. package/lib/network.js +233 -233
  103. package/lib/notify.js +612 -612
  104. package/lib/ntp-check.js +229 -229
  105. package/lib/numeric-bounds.js +111 -111
  106. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  107. package/lib/object-store/azure-blob.js +488 -488
  108. package/lib/object-store/gcs-bucket-ops.js +351 -351
  109. package/lib/object-store/gcs.js +519 -519
  110. package/lib/object-store/http-put.js +153 -153
  111. package/lib/object-store/index.js +197 -197
  112. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  113. package/lib/object-store/sigv4.js +903 -903
  114. package/lib/observability.js +151 -151
  115. package/lib/otel-export.js +269 -269
  116. package/lib/pagination.js +464 -464
  117. package/lib/parsers/index.js +80 -80
  118. package/lib/parsers/safe-env.js +642 -642
  119. package/lib/parsers/safe-ini.js +292 -292
  120. package/lib/parsers/safe-toml.js +784 -784
  121. package/lib/parsers/safe-xml.js +390 -390
  122. package/lib/parsers/safe-yaml.js +1015 -1015
  123. package/lib/permissions.js +708 -708
  124. package/lib/pqc-agent.js +87 -87
  125. package/lib/pqc-gate.js +279 -279
  126. package/lib/protobuf-encoder.js +190 -190
  127. package/lib/protocol-dispatcher.js +161 -161
  128. package/lib/pubsub-redis.js +167 -167
  129. package/lib/pubsub.js +429 -429
  130. package/lib/queue-local.js +476 -476
  131. package/lib/queue-redis.js +745 -745
  132. package/lib/queue-sqs.js +319 -319
  133. package/lib/queue.js +695 -695
  134. package/lib/redis-client.js +519 -519
  135. package/lib/request-helpers.js +340 -340
  136. package/lib/restore-bundle.js +237 -237
  137. package/lib/restore-rollback.js +259 -259
  138. package/lib/restore.js +409 -409
  139. package/lib/retry.js +376 -376
  140. package/lib/router.js +748 -748
  141. package/lib/safe-async.js +735 -735
  142. package/lib/safe-buffer.js +237 -237
  143. package/lib/safe-json.js +541 -541
  144. package/lib/safe-schema.js +1266 -1266
  145. package/lib/safe-url.js +159 -159
  146. package/lib/scheduler.js +706 -706
  147. package/lib/security-assert.js +373 -373
  148. package/lib/seeders.js +618 -618
  149. package/lib/session.js +535 -478
  150. package/lib/slug.js +269 -269
  151. package/lib/ssrf-guard.js +401 -401
  152. package/lib/static.js +7 -5
  153. package/lib/storage.js +471 -471
  154. package/lib/subject.js +281 -281
  155. package/lib/template.js +791 -791
  156. package/lib/testing.js +798 -798
  157. package/lib/time.js +310 -310
  158. package/lib/totp.js +302 -302
  159. package/lib/tracing.js +494 -494
  160. package/lib/uuid.js +132 -132
  161. package/lib/validate-opts.js +340 -340
  162. package/lib/vault/index.js +308 -308
  163. package/lib/vault/rotate.js +784 -784
  164. package/lib/vault/wrap.js +296 -296
  165. package/lib/vendor/noble-ciphers.cjs +9 -9
  166. package/lib/webhook.js +595 -595
  167. package/lib/websocket.js +1048 -1048
  168. package/package.json +77 -77
  169. package/sbom.cyclonedx.json +7 -7
@@ -1,316 +1,399 @@
1
- "use strict";
2
- /**
3
- * csrf-protect — middleware that issues CSRF tokens to safe-method
4
- * requests AND rejects state-changing requests whose submitted token
5
- * doesn't match.
6
- *
7
- * Mount AFTER attachUser (when using session-stored tokens) and AFTER
8
- * bodyParser (when reading the token from a form field). Safe methods
9
- * (GET / HEAD / OPTIONS) pass through; the gate fires on POST / PUT /
10
- * DELETE / PATCH (configurable via opts.methods).
11
- *
12
- * Token storage — pick ONE:
13
- *
14
- * A. Cookie-stored ("double-submit cookie", default)
15
- * opts.cookie = true | { name, sameSite, secure, path, httpOnly }
16
- *
17
- * The middleware reads the token from the configured cookie. On
18
- * safe-method requests with no token cookie, it generates one and
19
- * sets the cookie on the response. The same value is exposed on
20
- * `req.csrfToken` for templates to render into a hidden form field.
21
- * State-changing requests verify the submitted token matches the
22
- * cookie value. SameSite=Lax (default) blocks cross-site form
23
- * POSTs from carrying the cookie.
24
- *
25
- * httpOnly defaults to FALSE — JavaScript needs to read it for AJAX
26
- * requests. Operators relying solely on server-rendered forms can
27
- * flip it to true.
28
- *
29
- * B. Operator-supplied tokenLookup (session-stored, etc.)
30
- * opts.tokenLookup = (req) => string|null
31
- *
32
- * The middleware calls tokenLookup(req) to fetch the expected
33
- * token. Use this when CSRF tokens live in your session store
34
- * (e.g. req.session.data.csrfToken). Issuance + req.csrfToken
35
- * exposure are the operator's responsibility in this mode.
36
- *
37
- * If neither is supplied, the middleware throws at create() —
38
- * config-time validation, no silent passthrough.
39
- *
40
- * Submitted-token sources tried in order on state-changing requests:
41
- * 1. Header `X-CSRF-Token` (or opts.headerName)
42
- * 2. Body field `_csrf` (or opts.fieldName) — requires bodyParser
43
- * mounted before csrfProtect
44
- *
45
- * On mismatch:
46
- * - Audit emit (auth.csrf.denied) with method + path + IP + reason
47
- * - 403 application/json: { error: "CSRF token mismatch." }
48
- * - next() NOT called
49
- *
50
- * Full options:
51
- * {
52
- * cookie: true | { EITHER this...
53
- * name: auto: "__Host-csrf" over HTTPS, "csrf" over HTTP.
54
- * Operators with a custom name override here; the framework
55
- * validates that __Host-* names carry path="/" and Secure.
56
- * sameSite: "Lax" | "Strict" | "None",
57
- * secure: auto-detected from request scheme,
58
- * path: "/",
59
- * httpOnly: false,
60
- * },
61
- * tokenLookup: (req) => string|null ...OR this
62
- *
63
- * fieldName: "_csrf" form-body field name
64
- * headerName: "X-CSRF-Token" header name
65
- * methods: ["POST", "PUT", "DELETE", "PATCH"]
66
- * audit: true
67
- * }
68
- */
69
- var lazyRequire = require("../lazy-require");
70
- var forms = require("../forms");
71
- var requestHelpers = require("../request-helpers");
72
- var validateOpts = require("../validate-opts");
73
- var audit = lazyRequire(function () { return require("../audit"); });
74
-
75
- var DEFAULT_FIELD_NAME = "_csrf";
76
- var DEFAULT_HEADER_NAME = "X-CSRF-Token";
77
- var DEFAULT_METHODS = Object.freeze(["POST", "PUT", "DELETE", "PATCH"]);
78
-
79
- // Default cookie name uses the RFC 6265bis __Host- prefix when the request
80
- // is over HTTPS. The prefix forces browsers to refuse the cookie unless
81
- // it carries Secure + Path=/ + no Domain attribute — closing the
82
- // "malicious sibling subdomain sets a cookie on the parent domain to
83
- // subvert double-submit verification" attack class. On plain HTTP (dev),
84
- // browsers reject __Host- entirely, so we fall back to the bare name.
85
- var DEFAULT_COOKIE_NAME_SECURE = "__Host-csrf";
86
- var DEFAULT_COOKIE_NAME_INSECURE = "csrf";
87
-
88
- function _parseCookieHeader(header) {
89
- // Minimal cookie-header parser — RFC 6265 §5.2 form. Ignores attributes,
90
- // just splits the name=value pairs. Keys that appear multiple times
91
- // resolve to the FIRST occurrence (browsers send pairs left-to-right
92
- // by registration order; the first is the most-specific path).
93
- var out = {};
94
- if (typeof header !== "string" || header.length === 0) return out;
95
- var parts = header.split(/;\s*/);
96
- for (var i = 0; i < parts.length; i++) {
97
- var p = parts[i];
98
- var eq = p.indexOf("=");
99
- if (eq === -1) continue;
100
- var k = p.slice(0, eq).trim();
101
- if (k.length === 0 || Object.prototype.hasOwnProperty.call(out, k)) continue;
102
- var v = p.slice(eq + 1).trim();
103
- if (v.length >= 2 && v.charCodeAt(0) === 0x22 && v.charCodeAt(v.length - 1) === 0x22) {
104
- v = v.slice(1, -1);
105
- }
106
- out[k] = v;
107
- }
108
- return out;
109
- }
110
-
111
- // `_isHttps` defers to `requestHelpers.requestProtocol` so the
112
- // per-middleware `trustProxy` opt gates whether X-Forwarded-Proto is
113
- // consulted. Without trustProxy, an attacker could otherwise forge
114
- // the header to force the Secure cookie attribute (and inversely,
115
- // suppress it) on direct-to-server connections.
116
- function _isHttpsFor(trustProxy) {
117
- return function (req) {
118
- return requestHelpers.requestProtocol(req, { trustProxy: trustProxy }) === "https";
119
- };
120
- }
121
-
122
- function _formatSetCookie(name, value, opts) {
123
- var parts = [name + "=" + value];
124
- parts.push("Path=" + (opts.path || "/"));
125
- parts.push("SameSite=" + (opts.sameSite || "Lax"));
126
- if (opts.httpOnly) parts.push("HttpOnly");
127
- if (opts.secure) parts.push("Secure");
128
- if (opts.maxAge != null) parts.push("Max-Age=" + opts.maxAge);
129
- return parts.join("; ");
130
- }
131
-
132
- function _appendSetCookie(res, value) {
133
- // Don't clobber other Set-Cookie headers the route may have already
134
- // queued (login session cookie, etc.). Use res.appendHeader when
135
- // available; else array-merge manually.
136
- if (typeof res.appendHeader === "function") {
137
- res.appendHeader("Set-Cookie", value);
138
- return;
139
- }
140
- var existing = typeof res.getHeader === "function" ? res.getHeader("Set-Cookie") : undefined;
141
- if (existing == null) {
142
- res.setHeader("Set-Cookie", value);
143
- } else if (Array.isArray(existing)) {
144
- res.setHeader("Set-Cookie", existing.concat(value));
145
- } else {
146
- res.setHeader("Set-Cookie", [existing, value]);
147
- }
148
- }
149
-
150
- // csrf-protect does NOT buffer or parse the request body itself.
151
- // Operators who use form-urlencoded POSTs MUST register
152
- // `b.middleware.bodyParser()` before csrf-protect so that
153
- // `req.body[fieldName]` is populated. Header-token submissions
154
- // (X-CSRF-Token) work without bodyParser. The body-parser primitive
155
- // owns size caps, content-type dispatch, and prototype-pollution
156
- // defense; csrf-protect just reads the validated value.
157
-
158
- function _writeReject(res, message) {
159
- if (typeof res.writeHead === "function") {
160
- var body = JSON.stringify({ error: message });
161
- res.writeHead(requestHelpers.HTTP_STATUS.FORBIDDEN, {
162
- "Content-Type": "application/json; charset=utf-8",
163
- "Content-Length": Buffer.byteLength(body),
164
- });
165
- res.end(body);
166
- }
167
- }
168
-
169
- function create(opts) {
170
- opts = opts || {};
171
-
172
- validateOpts(opts, [
173
- "cookie", "tokenLookup", "fieldName", "headerName", "methods", "audit",
174
- "trustProxy",
175
- ], "middleware.csrfProtect");
176
- var trustProxy = opts.trustProxy === true || typeof opts.trustProxy === "number"
177
- ? opts.trustProxy : false;
178
- var _isHttps = _isHttpsFor(trustProxy);
179
-
180
- // Throw at create() — exactly one issuance source allowed.
181
- var hasCookie = opts.cookie != null && opts.cookie !== false;
182
- var hasLookup = typeof opts.tokenLookup === "function";
183
- if (hasCookie && hasLookup) {
184
- throw new Error("middleware.csrfProtect: opts.cookie and opts.tokenLookup are " +
185
- "mutually exclusive — pick one (cookie = double-submit, tokenLookup = session-stored)");
186
- }
187
- if (!hasCookie && !hasLookup) {
188
- throw new Error("middleware.csrfProtect: opts.cookie or opts.tokenLookup is required");
189
- }
190
-
191
- var fieldName = opts.fieldName || DEFAULT_FIELD_NAME;
192
- var headerName = (opts.headerName || DEFAULT_HEADER_NAME).toLowerCase();
193
- var methods = (opts.methods || DEFAULT_METHODS).map(function (m) { return m.toUpperCase(); });
194
- var auditOn = opts.audit !== false;
195
-
196
- // Cookie issuance config (only when opts.cookie is set).
197
- var cookieCfg = null;
198
- if (hasCookie) {
199
- var raw = opts.cookie === true ? {} : opts.cookie;
200
- if (typeof raw !== "object") {
201
- throw new Error("middleware.csrfProtect: opts.cookie must be true or an object");
202
- }
203
- cookieCfg = {
204
- // name: explicit operator override wins; otherwise auto-resolved
205
- // per-request based on whether the cookie is being issued Secure.
206
- name: raw.name || null,
207
- sameSite: raw.sameSite || "Lax",
208
- // secure: undefined means auto-detect from request scheme; explicit
209
- // true/false overrides.
210
- secure: raw.secure,
211
- path: raw.path || "/",
212
- httpOnly: !!raw.httpOnly,
213
- maxAge: raw.maxAge != null ? raw.maxAge : null,
214
- };
215
- if (["Lax", "Strict", "None"].indexOf(cookieCfg.sameSite) === -1) {
216
- throw new Error("middleware.csrfProtect: opts.cookie.sameSite must be Lax|Strict|None");
217
- }
218
- // __Host- prefix safety: if operator picks a __Host- name, the
219
- // Path/Domain/Secure constraints must be compatible. Path must be "/",
220
- // no Domain (we never set one), Secure resolved per-request. Catch
221
- // operator-side typos (e.g. __Host-csrf with a custom path) at boot.
222
- if (cookieCfg.name && /^__Host-/.test(cookieCfg.name)) {
223
- if (cookieCfg.path !== "/") {
224
- throw new Error("middleware.csrfProtect: __Host-* cookie name requires path='/'");
225
- }
226
- if (cookieCfg.secure === false) {
227
- throw new Error("middleware.csrfProtect: __Host-* cookie name requires secure (cannot be explicit false)");
228
- }
229
- }
230
- }
231
-
232
- // Resolve the cookie name for a specific request — operator override
233
- // wins; otherwise __Host-csrf when the cookie will be Secure, plain
234
- // csrf when over HTTP (browsers reject __Host- without Secure).
235
- function _resolveCookieName(req) {
236
- if (cookieCfg.name) return cookieCfg.name;
237
- var willBeSecure = cookieCfg.secure == null ? _isHttps(req) : !!cookieCfg.secure;
238
- return willBeSecure ? DEFAULT_COOKIE_NAME_SECURE : DEFAULT_COOKIE_NAME_INSECURE;
239
- }
240
-
241
- function _emitDenied(req, reason) {
242
- if (!auditOn) return;
243
- audit().safeEmit({
244
- action: "auth.csrf.denied",
245
- outcome: "denied",
246
- actor: requestHelpers.extractActorContext(req),
247
- reason: reason,
248
- metadata: { method: req.method, path: (req.url || "").split("?")[0] },
249
- });
250
- }
251
-
252
- // Issuance path (cookie mode): on safe-method requests with no cookie,
253
- // generate a token and queue it for the response. Always populate
254
- // req.csrfToken so templates have something to render.
255
- function _issueIfNeeded(req, res) {
256
- if (!cookieCfg) return null;
257
- var cookieName = _resolveCookieName(req);
258
- var cookies = _parseCookieHeader(req.headers && req.headers.cookie);
259
- var existing = cookies[cookieName];
260
- if (existing && /^[a-f0-9]{2,}$/.test(existing)) {
261
- req.csrfToken = existing;
262
- return existing;
263
- }
264
- var fresh = forms.generateCsrfToken();
265
- var setCookie = _formatSetCookie(cookieName, fresh, {
266
- path: cookieCfg.path,
267
- sameSite: cookieCfg.sameSite,
268
- secure: cookieCfg.secure == null ? _isHttps(req) : !!cookieCfg.secure,
269
- httpOnly: cookieCfg.httpOnly,
270
- maxAge: cookieCfg.maxAge,
271
- });
272
- _appendSetCookie(res, setCookie);
273
- req.csrfToken = fresh;
274
- return fresh;
275
- }
276
-
277
- return function csrfProtect(req, res, next) {
278
- // Issue/refresh the token on EVERY request (safe + state-changing)
279
- // when running in cookie mode templates rendered after a POST
280
- // (e.g. error response) still need req.csrfToken populated.
281
- var expected = _issueIfNeeded(req, res);
282
-
283
- if (methods.indexOf(req.method) === -1) return next();
284
-
285
- if (!cookieCfg) {
286
- // Session-stored mode operator's tokenLookup is the source.
287
- expected = opts.tokenLookup(req);
288
- }
289
- if (!expected) {
290
- _emitDenied(req, cookieCfg ? "no token cookie issued yet" : "no expected token in session");
291
- return _writeReject(res, "CSRF token mismatch.");
292
- }
293
-
294
- // Header path first — covers JSON / AJAX / multipart cases.
295
- var submitted = req.headers && req.headers[headerName];
296
- if (typeof submitted !== "string" || submitted.length === 0) {
297
- // Fall back to body field if bodyParser already populated req.body.
298
- // Operators with form-urlencoded POSTs are expected to register
299
- // bodyParser before csrf-protect; body buffering / parsing lives
300
- // in bodyParser, not here.
301
- if (req.body && typeof req.body === "object") {
302
- var v = req.body[fieldName];
303
- if (typeof v === "string") submitted = v;
304
- }
305
- }
306
-
307
- if (!forms.verifyCsrfToken(submitted || "", expected)) {
308
- _emitDenied(req, "submitted token does not match expected");
309
- return _writeReject(res, "CSRF token mismatch.");
310
- }
311
-
312
- return next();
313
- };
314
- }
315
-
316
- module.exports = { create: create };
1
+ "use strict";
2
+ /**
3
+ * csrf-protect — middleware that issues CSRF tokens to safe-method
4
+ * requests AND rejects state-changing requests whose submitted token
5
+ * doesn't match.
6
+ *
7
+ * Mount AFTER attachUser (when using session-stored tokens) and AFTER
8
+ * bodyParser (when reading the token from a form field). Safe methods
9
+ * (GET / HEAD / OPTIONS) pass through; the gate fires on POST / PUT /
10
+ * DELETE / PATCH (configurable via opts.methods).
11
+ *
12
+ * Token storage — pick ONE:
13
+ *
14
+ * A. Cookie-stored ("double-submit cookie", default)
15
+ * opts.cookie = true | { name, sameSite, secure, path, httpOnly }
16
+ *
17
+ * The middleware reads the token from the configured cookie. On
18
+ * safe-method requests with no token cookie, it generates one and
19
+ * sets the cookie on the response. The same value is exposed on
20
+ * `req.csrfToken` for templates to render into a hidden form field.
21
+ * State-changing requests verify the submitted token matches the
22
+ * cookie value. SameSite=Lax (default) blocks cross-site form
23
+ * POSTs from carrying the cookie.
24
+ *
25
+ * httpOnly defaults to FALSE — JavaScript needs to read it for AJAX
26
+ * requests. Operators relying solely on server-rendered forms can
27
+ * flip it to true.
28
+ *
29
+ * B. Operator-supplied tokenLookup (session-stored, etc.)
30
+ * opts.tokenLookup = (req) => string|null
31
+ *
32
+ * The middleware calls tokenLookup(req) to fetch the expected
33
+ * token. Use this when CSRF tokens live in your session store
34
+ * (e.g. req.session.data.csrfToken). Issuance + req.csrfToken
35
+ * exposure are the operator's responsibility in this mode.
36
+ *
37
+ * If neither is supplied, the middleware throws at create() —
38
+ * config-time validation, no silent passthrough.
39
+ *
40
+ * Submitted-token sources tried in order on state-changing requests:
41
+ * 1. Header `X-CSRF-Token` (or opts.headerName)
42
+ * 2. Body field `_csrf` (or opts.fieldName) — requires bodyParser
43
+ * mounted before csrfProtect
44
+ *
45
+ * On mismatch:
46
+ * - Audit emit (auth.csrf.denied) with method + path + IP + reason
47
+ * - 403 application/json: { error: "CSRF token mismatch." }
48
+ * - next() NOT called
49
+ *
50
+ * Full options:
51
+ * {
52
+ * cookie: true | { EITHER this...
53
+ * name: auto: "__Host-csrf" over HTTPS, "csrf" over HTTP.
54
+ * Operators with a custom name override here; the framework
55
+ * validates that __Host-* names carry path="/" and Secure.
56
+ * sameSite: "Lax" | "Strict" | "None",
57
+ * secure: auto-detected from request scheme,
58
+ * path: "/",
59
+ * httpOnly: false,
60
+ * },
61
+ * tokenLookup: (req) => string|null ...OR this
62
+ *
63
+ * fieldName: "_csrf" form-body field name
64
+ * headerName: "X-CSRF-Token" header name
65
+ * methods: ["POST", "PUT", "DELETE", "PATCH"]
66
+ * audit: true
67
+ * }
68
+ */
69
+ var lazyRequire = require("../lazy-require");
70
+ var forms = require("../forms");
71
+ var requestHelpers = require("../request-helpers");
72
+ var validateOpts = require("../validate-opts");
73
+ var audit = lazyRequire(function () { return require("../audit"); });
74
+
75
+ var DEFAULT_FIELD_NAME = "_csrf";
76
+ var DEFAULT_HEADER_NAME = "X-CSRF-Token";
77
+ var DEFAULT_METHODS = Object.freeze(["POST", "PUT", "DELETE", "PATCH"]);
78
+
79
+ // Default cookie name uses the RFC 6265bis __Host- prefix when the request
80
+ // is over HTTPS. The prefix forces browsers to refuse the cookie unless
81
+ // it carries Secure + Path=/ + no Domain attribute — closing the
82
+ // "malicious sibling subdomain sets a cookie on the parent domain to
83
+ // subvert double-submit verification" attack class. On plain HTTP (dev),
84
+ // browsers reject __Host- entirely, so we fall back to the bare name.
85
+ var DEFAULT_COOKIE_NAME_SECURE = "__Host-csrf";
86
+ var DEFAULT_COOKIE_NAME_INSECURE = "csrf";
87
+
88
+ function _parseCookieHeader(header) {
89
+ // Minimal cookie-header parser — RFC 6265 §5.2 form. Ignores attributes,
90
+ // just splits the name=value pairs. Keys that appear multiple times
91
+ // resolve to the FIRST occurrence (browsers send pairs left-to-right
92
+ // by registration order; the first is the most-specific path).
93
+ var out = {};
94
+ if (typeof header !== "string" || header.length === 0) return out;
95
+ var parts = header.split(/;\s*/);
96
+ for (var i = 0; i < parts.length; i++) {
97
+ var p = parts[i];
98
+ var eq = p.indexOf("=");
99
+ if (eq === -1) continue;
100
+ var k = p.slice(0, eq).trim();
101
+ if (k.length === 0 || Object.prototype.hasOwnProperty.call(out, k)) continue;
102
+ var v = p.slice(eq + 1).trim();
103
+ if (v.length >= 2 && v.charCodeAt(0) === 0x22 && v.charCodeAt(v.length - 1) === 0x22) {
104
+ v = v.slice(1, -1);
105
+ }
106
+ out[k] = v;
107
+ }
108
+ return out;
109
+ }
110
+
111
+ // `_isHttps` defers to `requestHelpers.requestProtocol` so the
112
+ // per-middleware `trustProxy` opt gates whether X-Forwarded-Proto is
113
+ // consulted. Without trustProxy, an attacker could otherwise forge
114
+ // the header to force the Secure cookie attribute (and inversely,
115
+ // suppress it) on direct-to-server connections.
116
+ function _isHttpsFor(trustProxy) {
117
+ return function (req) {
118
+ return requestHelpers.requestProtocol(req, { trustProxy: trustProxy }) === "https";
119
+ };
120
+ }
121
+
122
+ function _formatSetCookie(name, value, opts) {
123
+ var parts = [name + "=" + value];
124
+ parts.push("Path=" + (opts.path || "/"));
125
+ parts.push("SameSite=" + (opts.sameSite || "Lax"));
126
+ if (opts.httpOnly) parts.push("HttpOnly");
127
+ if (opts.secure) parts.push("Secure");
128
+ if (opts.maxAge != null) parts.push("Max-Age=" + opts.maxAge);
129
+ return parts.join("; ");
130
+ }
131
+
132
+ function _appendSetCookie(res, value) {
133
+ // Don't clobber other Set-Cookie headers the route may have already
134
+ // queued (login session cookie, etc.). Use res.appendHeader when
135
+ // available; else array-merge manually.
136
+ if (typeof res.appendHeader === "function") {
137
+ res.appendHeader("Set-Cookie", value);
138
+ return;
139
+ }
140
+ var existing = typeof res.getHeader === "function" ? res.getHeader("Set-Cookie") : undefined;
141
+ if (existing == null) {
142
+ res.setHeader("Set-Cookie", value);
143
+ } else if (Array.isArray(existing)) {
144
+ res.setHeader("Set-Cookie", existing.concat(value));
145
+ } else {
146
+ res.setHeader("Set-Cookie", [existing, value]);
147
+ }
148
+ }
149
+
150
+ // csrf-protect does NOT buffer or parse the request body itself.
151
+ // Operators who use form-urlencoded POSTs MUST register
152
+ // `b.middleware.bodyParser()` before csrf-protect so that
153
+ // `req.body[fieldName]` is populated. Header-token submissions
154
+ // (X-CSRF-Token) work without bodyParser. The body-parser primitive
155
+ // owns size caps, content-type dispatch, and prototype-pollution
156
+ // defense; csrf-protect just reads the validated value.
157
+
158
+ // Origin / Referer cross-check helper. Returns null when the request's
159
+ // origin is acceptable, or a short reason string ("origin-mismatch" /
160
+ // "referer-mismatch" / "no-origin-or-referer" / "malformed-url") when
161
+ // it should be refused. Compares against opts.allowedOrigins (when
162
+ // supplied) OR same-origin (the request's own Host header).
163
+ //
164
+ // Implementation note — we deliberately don't run safeUrl here; safeUrl
165
+ // throws on file:// / data:// schemes which would crash the middleware
166
+ // instead of refusing the request. URL constructor + try/catch is the
167
+ // right shape for "is this URL well-formed and what's its origin?".
168
+ function _checkOriginAllowed(req, allowedOrigins, isHttpsFn) {
169
+ var headers = req.headers || {};
170
+ var origin = headers.origin;
171
+ var referer = headers.referer;
172
+ if (typeof origin !== "string" && typeof referer !== "string") {
173
+ // No Origin/Referer at all — common for non-browser clients
174
+ // (curl, server-to-server). The token check still applies; this
175
+ // gate doesn't add to it. Defense-in-depth against a stolen
176
+ // cookie via a browser-rendered cross-origin fetch IS the value;
177
+ // headless clients carry their own auth threat model.
178
+ return null;
179
+ }
180
+
181
+ var requestOrigin = (isHttpsFn && isHttpsFn(req) ? "https://" : "http://") +
182
+ (headers.host || "");
183
+
184
+ function _originOf(rawUrl) {
185
+ try {
186
+ var u = new URL(rawUrl); // allow:raw-new-url — origin-shape inspection (NOT outbound). Intentionally tolerates file:// / data: which safeUrl.parse refuses.
187
+ return u.origin; // "https://host:port" no path / query / fragment
188
+ } catch (_e) { return null; }
189
+ }
190
+
191
+ function _isAllowed(candidateOrigin) {
192
+ if (!candidateOrigin) return false;
193
+ if (candidateOrigin === requestOrigin) return true;
194
+ if (Array.isArray(allowedOrigins)) {
195
+ for (var i = 0; i < allowedOrigins.length; i += 1) {
196
+ if (candidateOrigin === allowedOrigins[i]) return true;
197
+ }
198
+ }
199
+ return false;
200
+ }
201
+
202
+ if (typeof origin === "string" && origin.length > 0) {
203
+ var oo = _originOf(origin);
204
+ if (oo === null) return "malformed-origin";
205
+ if (!_isAllowed(oo)) return "origin-mismatch (" + oo + " vs " + requestOrigin + ")";
206
+ return null;
207
+ }
208
+ // Origin absent fall back to Referer.
209
+ var ro = _originOf(referer);
210
+ if (ro === null) return "malformed-referer";
211
+ if (!_isAllowed(ro)) return "referer-mismatch (" + ro + " vs " + requestOrigin + ")";
212
+ return null;
213
+ }
214
+
215
+ function _writeReject(res, message) {
216
+ if (typeof res.writeHead === "function") {
217
+ var body = JSON.stringify({ error: message });
218
+ res.writeHead(requestHelpers.HTTP_STATUS.FORBIDDEN, {
219
+ "Content-Type": "application/json; charset=utf-8",
220
+ "Content-Length": Buffer.byteLength(body),
221
+ });
222
+ res.end(body);
223
+ }
224
+ }
225
+
226
+ function create(opts) {
227
+ opts = opts || {};
228
+
229
+ validateOpts(opts, [
230
+ "cookie", "tokenLookup", "fieldName", "headerName", "methods", "audit",
231
+ "trustProxy", "checkOrigin", "allowedOrigins",
232
+ ], "middleware.csrfProtect");
233
+ var trustProxy = opts.trustProxy === true || typeof opts.trustProxy === "number"
234
+ ? opts.trustProxy : false;
235
+ var _isHttps = _isHttpsFor(trustProxy);
236
+
237
+ // Throw at create() exactly one issuance source allowed.
238
+ var hasCookie = opts.cookie != null && opts.cookie !== false;
239
+ var hasLookup = typeof opts.tokenLookup === "function";
240
+ if (hasCookie && hasLookup) {
241
+ throw new Error("middleware.csrfProtect: opts.cookie and opts.tokenLookup are " +
242
+ "mutually exclusive — pick one (cookie = double-submit, tokenLookup = session-stored)");
243
+ }
244
+ if (!hasCookie && !hasLookup) {
245
+ throw new Error("middleware.csrfProtect: opts.cookie or opts.tokenLookup is required");
246
+ }
247
+
248
+ var fieldName = opts.fieldName || DEFAULT_FIELD_NAME;
249
+ var headerName = (opts.headerName || DEFAULT_HEADER_NAME).toLowerCase();
250
+ var methods = (opts.methods || DEFAULT_METHODS).map(function (m) { return m.toUpperCase(); });
251
+ var auditOn = opts.audit !== false;
252
+
253
+ // Origin / Referer cross-check second-line defense alongside the
254
+ // double-submit token. If the request's Origin (or Referer when
255
+ // Origin is absent — Safari pre-12, certain CORS mode requests)
256
+ // doesn't resolve to a same-origin or operator-allowlisted origin,
257
+ // refuse before the token check.
258
+ //
259
+ // Default: enabled (defense-in-depth — same shape as bot-guard /
260
+ // rate-limit / CSP nonce — every default ON per Core Rule §3).
261
+ // Operator opt-out: opts.checkOrigin = false.
262
+ // Operator allowlist: opts.allowedOrigins = ["https://app.example.com"].
263
+ var checkOrigin = opts.checkOrigin !== false;
264
+ var allowedOrigins = Array.isArray(opts.allowedOrigins)
265
+ ? opts.allowedOrigins.slice() : null;
266
+
267
+ // Cookie issuance config (only when opts.cookie is set).
268
+ var cookieCfg = null;
269
+ if (hasCookie) {
270
+ var raw = opts.cookie === true ? {} : opts.cookie;
271
+ if (typeof raw !== "object") {
272
+ throw new Error("middleware.csrfProtect: opts.cookie must be true or an object");
273
+ }
274
+ cookieCfg = {
275
+ // name: explicit operator override wins; otherwise auto-resolved
276
+ // per-request based on whether the cookie is being issued Secure.
277
+ name: raw.name || null,
278
+ sameSite: raw.sameSite || "Lax",
279
+ // secure: undefined means auto-detect from request scheme; explicit
280
+ // true/false overrides.
281
+ secure: raw.secure,
282
+ path: raw.path || "/",
283
+ httpOnly: !!raw.httpOnly,
284
+ maxAge: raw.maxAge != null ? raw.maxAge : null,
285
+ };
286
+ if (["Lax", "Strict", "None"].indexOf(cookieCfg.sameSite) === -1) {
287
+ throw new Error("middleware.csrfProtect: opts.cookie.sameSite must be Lax|Strict|None");
288
+ }
289
+ // __Host- prefix safety: if operator picks a __Host- name, the
290
+ // Path/Domain/Secure constraints must be compatible. Path must be "/",
291
+ // no Domain (we never set one), Secure resolved per-request. Catch
292
+ // operator-side typos (e.g. __Host-csrf with a custom path) at boot.
293
+ if (cookieCfg.name && /^__Host-/.test(cookieCfg.name)) {
294
+ if (cookieCfg.path !== "/") {
295
+ throw new Error("middleware.csrfProtect: __Host-* cookie name requires path='/'");
296
+ }
297
+ if (cookieCfg.secure === false) {
298
+ throw new Error("middleware.csrfProtect: __Host-* cookie name requires secure (cannot be explicit false)");
299
+ }
300
+ }
301
+ }
302
+
303
+ // Resolve the cookie name for a specific request — operator override
304
+ // wins; otherwise __Host-csrf when the cookie will be Secure, plain
305
+ // csrf when over HTTP (browsers reject __Host- without Secure).
306
+ function _resolveCookieName(req) {
307
+ if (cookieCfg.name) return cookieCfg.name;
308
+ var willBeSecure = cookieCfg.secure == null ? _isHttps(req) : !!cookieCfg.secure;
309
+ return willBeSecure ? DEFAULT_COOKIE_NAME_SECURE : DEFAULT_COOKIE_NAME_INSECURE;
310
+ }
311
+
312
+ function _emitDenied(req, reason) {
313
+ if (!auditOn) return;
314
+ audit().safeEmit({
315
+ action: "auth.csrf.denied",
316
+ outcome: "denied",
317
+ actor: requestHelpers.extractActorContext(req),
318
+ reason: reason,
319
+ metadata: { method: req.method, path: (req.url || "").split("?")[0] },
320
+ });
321
+ }
322
+
323
+ // Issuance path (cookie mode): on safe-method requests with no cookie,
324
+ // generate a token and queue it for the response. Always populate
325
+ // req.csrfToken so templates have something to render.
326
+ function _issueIfNeeded(req, res) {
327
+ if (!cookieCfg) return null;
328
+ var cookieName = _resolveCookieName(req);
329
+ var cookies = _parseCookieHeader(req.headers && req.headers.cookie);
330
+ var existing = cookies[cookieName];
331
+ if (existing && /^[a-f0-9]{2,}$/.test(existing)) {
332
+ req.csrfToken = existing;
333
+ return existing;
334
+ }
335
+ var fresh = forms.generateCsrfToken();
336
+ var setCookie = _formatSetCookie(cookieName, fresh, {
337
+ path: cookieCfg.path,
338
+ sameSite: cookieCfg.sameSite,
339
+ secure: cookieCfg.secure == null ? _isHttps(req) : !!cookieCfg.secure,
340
+ httpOnly: cookieCfg.httpOnly,
341
+ maxAge: cookieCfg.maxAge,
342
+ });
343
+ _appendSetCookie(res, setCookie);
344
+ req.csrfToken = fresh;
345
+ return fresh;
346
+ }
347
+
348
+ return function csrfProtect(req, res, next) {
349
+ // Issue/refresh the token on EVERY request (safe + state-changing)
350
+ // when running in cookie mode — templates rendered after a POST
351
+ // (e.g. error response) still need req.csrfToken populated.
352
+ var expected = _issueIfNeeded(req, res);
353
+
354
+ if (methods.indexOf(req.method) === -1) return next();
355
+
356
+ // Origin / Referer cross-check (defense-in-depth alongside the
357
+ // double-submit token). Refuses cross-origin state-changing
358
+ // requests even when the token is valid (e.g. operator-mistaken
359
+ // CORS configuration that exposes the cookie).
360
+ if (checkOrigin) {
361
+ var originReason = _checkOriginAllowed(req, allowedOrigins, _isHttps);
362
+ if (originReason !== null) {
363
+ _emitDenied(req, "origin/referer: " + originReason);
364
+ return _writeReject(res, "CSRF cross-origin request refused.");
365
+ }
366
+ }
367
+
368
+ if (!cookieCfg) {
369
+ // Session-stored mode — operator's tokenLookup is the source.
370
+ expected = opts.tokenLookup(req);
371
+ }
372
+ if (!expected) {
373
+ _emitDenied(req, cookieCfg ? "no token cookie issued yet" : "no expected token in session");
374
+ return _writeReject(res, "CSRF token mismatch.");
375
+ }
376
+
377
+ // Header path first — covers JSON / AJAX / multipart cases.
378
+ var submitted = req.headers && req.headers[headerName];
379
+ if (typeof submitted !== "string" || submitted.length === 0) {
380
+ // Fall back to body field if bodyParser already populated req.body.
381
+ // Operators with form-urlencoded POSTs are expected to register
382
+ // bodyParser before csrf-protect; body buffering / parsing lives
383
+ // in bodyParser, not here.
384
+ if (req.body && typeof req.body === "object") {
385
+ var v = req.body[fieldName];
386
+ if (typeof v === "string") submitted = v;
387
+ }
388
+ }
389
+
390
+ if (!forms.verifyCsrfToken(submitted || "", expected)) {
391
+ _emitDenied(req, "submitted token does not match expected");
392
+ return _writeReject(res, "CSRF token mismatch.");
393
+ }
394
+
395
+ return next();
396
+ };
397
+ }
398
+
399
+ module.exports = { create: create };