@blamejs/core 0.7.1 → 0.7.18

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 (180) hide show
  1. package/CHANGELOG.md +423 -389
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -282
  5. package/lib/api-key.js +660 -672
  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.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -266
  27. package/lib/cache.js +1206 -1211
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  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 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  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/file-upload.js +1136 -0
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -202
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -573
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -269
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -614
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -451
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -479
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -855
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -177
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -752
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -489
  146. package/lib/request-helpers.js +340 -336
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -630
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +879 -114
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -270
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -598
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -1,316 +1,316 @@
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
+ 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 };