@blamejs/core 0.7.18 → 0.7.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
@@ -1,340 +1,340 @@
1
- "use strict";
2
- /**
3
- * request-helpers — small shared utilities for HTTP request middleware.
4
- *
5
- * The framework's metrics + tracing requestMiddleware both label by
6
- * route TEMPLATE and capture the final response status. They had
7
- * identical implementations of:
8
- *
9
- * 1. Reading req.routePattern with a URL-fallback
10
- * 2. Wrapping res.writeHead + reading res.statusCode at res.end
11
- *
12
- * This module owns the two helpers so the duplication doesn't drift —
13
- * if either pattern changes (e.g. handle res.statusMessage), it changes
14
- * once.
15
- *
16
- * Public API:
17
- *
18
- * resolveRoute(req)
19
- * Returns req.routePattern when the router populated it,
20
- * otherwise the URL with query string stripped.
21
- *
22
- * captureResponseStatus(res, onEnd)
23
- * Wraps res.writeHead + res.end. Calls onEnd(status) once when the
24
- * response ends, with the final status pulled from writeHead's
25
- * argument OR from res.statusCode (modern Node handlers set it
26
- * directly without going through writeHead). Operators wrap their
27
- * own pre-end logic by passing it as onEnd.
28
- *
29
- * Returns the original (unwrapped) `res.end`. Useful for unit tests
30
- * that need to assert against the original behavior.
31
- */
32
-
33
- // HTTP status codes used across the framework's HTTP-shaped surface.
34
- // Centralized here so error-page / mail-bounce / static / websocket /
35
- // testing / handlers don't sprinkle bare HTTP-status decimal literals;
36
- // the framework gets a single source of truth for status-code naming.
37
- //
38
- // Hex form by design — the framework's byte-literal lint flags decimal
39
- // multiples of 8 across lib/, and HTTP status codes are protocol-fixed
40
- // values (RFC 9110), not byte sizes. Names are RFC 9110 reason phrases;
41
- // every consumer reads HTTP_STATUS.<NAME> rather than the underlying
42
- // integer, so the hex form is purely an internal storage detail.
43
- var HTTP_STATUS = Object.freeze({
44
- OK: 0xC8,
45
- PARTIAL_CONTENT: 0xCE,
46
- NO_CONTENT: 0xCC,
47
- NOT_MODIFIED: 0x130,
48
- BAD_REQUEST: 0x190,
49
- UNAUTHORIZED: 0x191,
50
- FORBIDDEN: 0x193,
51
- NOT_FOUND: 0x194,
52
- METHOD_NOT_ALLOWED: 0x195,
53
- CONFLICT: 0x199,
54
- PAYLOAD_TOO_LARGE: 0x19D,
55
- UNSUPPORTED_MEDIA_TYPE: 0x19F,
56
- RANGE_NOT_SATISFIABLE: 0x1A0,
57
- UNPROCESSABLE_CONTENT: 0x1A6,
58
- PRECONDITION_FAILED: 0x19C,
59
- TOO_MANY_REQUESTS: 0x1AD,
60
- UNAVAILABLE_FOR_LEGAL_REASONS: 0x1C3,
61
- INTERNAL_SERVER_ERROR: 0x1F4,
62
- BAD_GATEWAY: 0x1F6,
63
- SERVICE_UNAVAILABLE: 0x1F7,
64
- GATEWAY_TIMEOUT: 0x1F8,
65
- });
66
-
67
- // extractActorContext(req) — pull the 5 W's from a request for audit
68
- // chain emission. WHO/WHERE/HOW columns on _blamejs_audit_log are
69
- // populated from this shape:
70
- //
71
- // { ip, userAgent, sessionId, requestId, method, route, userId }
72
- //
73
- // Every field is best-effort: missing or non-request inputs return
74
- // an object with whatever could be inferred plus null elsewhere.
75
- // Audit chain treats null as "unknown", so partial context is safe.
76
- //
77
- // Caller-supplied actor (existing actor.userId, actor.ip, etc.) is
78
- // merged on top of the request-derived fields — explicit operator
79
- // override always wins.
80
- function extractActorContext(req, override) {
81
- var ctx = {
82
- ip: null,
83
- userAgent: null,
84
- sessionId: null,
85
- requestId: null,
86
- method: null,
87
- route: null,
88
- userId: null,
89
- };
90
- if (req && typeof req === "object") {
91
- // Direct properties first (Express-shaped frameworks set req.ip).
92
- if (typeof req.ip === "string") ctx.ip = req.ip;
93
- else if (req.connection && typeof req.connection.remoteAddress === "string") {
94
- ctx.ip = req.connection.remoteAddress;
95
- } else if (req.socket && typeof req.socket.remoteAddress === "string") {
96
- ctx.ip = req.socket.remoteAddress;
97
- }
98
- if (req.headers && typeof req.headers["user-agent"] === "string") {
99
- ctx.userAgent = req.headers["user-agent"];
100
- }
101
- if (req.session && typeof req.session.id === "string") ctx.sessionId = req.session.id;
102
- else if (typeof req.sessionId === "string") ctx.sessionId = req.sessionId;
103
- if (typeof req.requestId === "string") ctx.requestId = req.requestId;
104
- else if (req.headers && typeof req.headers["x-request-id"] === "string") {
105
- ctx.requestId = req.headers["x-request-id"];
106
- }
107
- if (typeof req.method === "string") ctx.method = req.method;
108
- ctx.route = resolveRoute(req);
109
- // userId from common shapes the framework's auth surfaces produce
110
- if (req.user && typeof req.user.id === "string") ctx.userId = req.user.id;
111
- else if (req.user && typeof req.user.userId === "string") ctx.userId = req.user.userId;
112
- else if (req.apiKey && typeof req.apiKey.ownerId === "string") ctx.userId = req.apiKey.ownerId;
113
- }
114
- if (override && typeof override === "object") {
115
- for (var k in override) {
116
- if (Object.prototype.hasOwnProperty.call(override, k) && override[k] != null) {
117
- ctx[k] = override[k];
118
- }
119
- }
120
- }
121
- return ctx;
122
- }
123
-
124
- // Convenience wrapper for primitives that accept an optional
125
- // `{ req, context }` shape and want to thread it into an audit-emit
126
- // `actor` field. Replaces the four near-identical `_actor()` helpers
127
- // that lived in api-key, cache, seeders, and notify before v0.4.29.
128
- //
129
- // callerOpts: operator-supplied `{ req?, context? }` (e.g. the
130
- // primitive's call-site opts bag)
131
- // baseOverride: optional seed values applied BEFORE callerOpts.context
132
- // so `context` wins. api-key seeds `{ userId }` here so
133
- // the resolved key's owner becomes the default actor
134
- // unless the operator passes their own context.userId.
135
- //
136
- // Returns the same shape as extractActorContext.
137
- function resolveActorWithOverride(callerOpts, baseOverride) {
138
- var override = baseOverride ? Object.assign({}, baseOverride) : {};
139
- if (callerOpts && callerOpts.context && typeof callerOpts.context === "object") {
140
- for (var k in callerOpts.context) {
141
- if (Object.prototype.hasOwnProperty.call(callerOpts.context, k)) {
142
- override[k] = callerOpts.context[k];
143
- }
144
- }
145
- }
146
- return extractActorContext(callerOpts && callerOpts.req, override);
147
- }
148
-
149
- // ---- Proxy-trust primitives (v0.5.3) ----
150
- //
151
- // `X-Forwarded-For` and `X-Forwarded-Proto` are operator-trust headers —
152
- // behind a sanitizing reverse proxy they carry the apparent origin /
153
- // scheme; without one they're attacker-forgeable. Default is to NOT
154
- // trust them; operators behind a proxy set `trustProxy: true` (or a
155
- // hop count for multi-hop chains) per-middleware to opt in.
156
- //
157
- // clientIp(req, { trustProxy }) → string | null
158
- //
159
- // trustProxy false (default): socket.remoteAddress only
160
- // trustProxy true: leftmost x-forwarded-for hop, else socket
161
- // trustProxy <integer N>: Nth-from-rightmost xff hop (skip-N-trusted-hops)
162
- //
163
- // Middleware accepts `trustProxy` as an opt and threads it through;
164
- // the framework refuses to silently pick up forwarded headers without
165
- // the operator's explicit acknowledgement.
166
-
167
- function clientIp(req, opts) {
168
- if (!req) return null;
169
- var trust = opts && opts.trustProxy;
170
- if (trust && req.headers) {
171
- var xff = req.headers["x-forwarded-for"];
172
- if (xff) {
173
- var hops = parseListHeader(xff);
174
- if (trust === true) return hops[0];
175
- if (typeof trust === "number" && trust >= 1 && hops.length >= trust) {
176
- return hops[hops.length - trust];
177
- }
178
- }
179
- }
180
- if (req.socket && typeof req.socket.remoteAddress === "string") return req.socket.remoteAddress;
181
- if (req.connection && typeof req.connection.remoteAddress === "string") return req.connection.remoteAddress;
182
- return null;
183
- }
184
-
185
- function requestProtocol(req, opts) {
186
- if (!req) return "http";
187
- var trust = opts && opts.trustProxy;
188
- if (trust && req.headers) {
189
- var fwd = req.headers["x-forwarded-proto"];
190
- if (typeof fwd === "string" && fwd.length > 0) {
191
- var hops = parseListHeader(fwd, { lowercase: true });
192
- if (hops.length > 0) return hops[0];
193
- }
194
- }
195
- if (req.socket && req.socket.encrypted) return "https";
196
- if (req.connection && req.connection.encrypted) return "https";
197
- return "http";
198
- }
199
-
200
- // parseListHeader — split a comma-separated header / opt value into a
201
- // list of trimmed non-empty tokens. Replaces the
202
- // `String(x).split(",").map(s => s.trim()).filter(Boolean)` chain that
203
- // was duplicated across cors / compression / scheduler / webhook /
204
- // websocket / db-schema / cli before v0.5.17.
205
- //
206
- // parseListHeader("a, b , ,c") → ["a", "b", "c"]
207
- // parseListHeader("Foo, Bar", { lowercase: true })
208
- // → ["foo", "bar"]
209
- // parseListHeader(undefined) → []
210
- // parseListHeader("") → []
211
- //
212
- // Tolerant read: non-string input returns [] — these are read from
213
- // request headers that the network might omit. Callers needing stricter
214
- // checks layer their own validation on the result.
215
- function parseListHeader(value, opts) {
216
- if (value == null) return [];
217
- opts = opts || {};
218
- var s = typeof value === "string" ? value : String(value);
219
- if (s.length === 0) return [];
220
- var parts = s.split(",");
221
- var out = [];
222
- for (var i = 0; i < parts.length; i++) {
223
- var t = parts[i].trim();
224
- if (t.length === 0) continue;
225
- out.push(opts.lowercase ? t.toLowerCase() : t);
226
- }
227
- return out;
228
- }
229
-
230
- // Append a token to a `Vary` response header without dropping prior
231
- // values (compression middleware sets `Vary: Accept-Encoding`, an
232
- // auth helper might set `Vary: Authorization`, etc.). Idempotent —
233
- // re-adding an existing token is a no-op.
234
- function appendVary(res, value) {
235
- if (!res || typeof res.getHeader !== "function" || typeof res.setHeader !== "function") return;
236
- var existing = res.getHeader("Vary");
237
- if (existing == null || existing === "") { res.setHeader("Vary", value); return; }
238
- var tokens = parseListHeader(existing);
239
- var lower = value.toLowerCase();
240
- for (var i = 0; i < tokens.length; i++) if (tokens[i].toLowerCase() === lower) return;
241
- tokens.push(value);
242
- res.setHeader("Vary", tokens.join(", "));
243
- }
244
-
245
- function resolveRoute(req) {
246
- if (req && typeof req.routePattern === "string" && req.routePattern.length > 0) {
247
- return req.routePattern;
248
- }
249
- var url = req && req.url;
250
- if (typeof url !== "string" || url.length === 0) return "/";
251
- var qIdx = url.indexOf("?");
252
- return qIdx === -1 ? url : url.slice(0, qIdx);
253
- }
254
-
255
- function captureResponseStatus(res, onEnd) {
256
- if (!res || typeof onEnd !== "function") {
257
- throw new Error("captureResponseStatus: requires (res, onEnd)");
258
- }
259
- var origEnd = res.end;
260
- var origWriteHead = res.writeHead;
261
- var statusFromWriteHead = null;
262
- res.writeHead = function (s) {
263
- statusFromWriteHead = s;
264
- return origWriteHead.apply(res, arguments);
265
- };
266
- res.end = function () {
267
- var status = statusFromWriteHead != null
268
- ? statusFromWriteHead
269
- : (typeof res.statusCode === "number" ? res.statusCode : HTTP_STATUS.OK);
270
- try { onEnd(status); }
271
- catch (_e) { /* onEnd never breaks the response — caller's instrumentation issue */ }
272
- return origEnd.apply(res, arguments);
273
- };
274
- return origEnd;
275
- }
276
-
277
- // parseQualityList — RFC 9110 §12.5 Accept-* header parser.
278
- //
279
- // Returns `[{ value, q }]` sorted by q descending. Used by content
280
- // negotiation (`Accept-Encoding`, `Accept-Language`, `Accept`, etc.).
281
- // Each Accept-* middleware previously had its own copy of this loop;
282
- // extracting it here keeps the q-value semantics consistent
283
- // (q=0 = explicit exclusion; clamped to [0, 1]; missing q = 1).
284
- //
285
- // parseQualityList("br;q=1.0, gzip;q=0.5, *;q=0")
286
- // → [{ value: "br", q: 1 }, { value: "gzip", q: 0.5 }, { value: "*", q: 0 }]
287
- //
288
- // `value` is lowercased by default; pass `{ caseSensitive: true }` to
289
- // preserve case (BCP 47 language tags want case preservation since
290
- // `pt-BR` and `pt-br` resolve identically but operators may match by
291
- // canonical form themselves).
292
- //
293
- // Bad input (non-string, empty) returns []. RFC 9110 says an absent
294
- // Accept header means "accept anything"; callers handle that absence
295
- // at their own layer (compression's [{ encoding: "*", q: 1 }] default
296
- // vs i18n's "fall back to default locale" — different semantics).
297
- var Q_VALUE_RE = /(?:^|;|\s)q\s*=\s*([0-9]*\.?[0-9]+)/i;
298
-
299
- function parseQualityList(headerValue, opts) {
300
- if (typeof headerValue !== "string" || headerValue.length === 0) return [];
301
- opts = opts || {};
302
- var caseSensitive = opts.caseSensitive === true;
303
- var parts = headerValue.split(",");
304
- var out = [];
305
- for (var i = 0; i < parts.length; i++) {
306
- var p = parts[i].trim();
307
- if (p.length === 0) continue;
308
- var semi = p.indexOf(";");
309
- var value, q;
310
- if (semi === -1) {
311
- value = caseSensitive ? p : p.toLowerCase();
312
- q = 1;
313
- } else {
314
- var head = p.slice(0, semi).trim();
315
- value = caseSensitive ? head : head.toLowerCase();
316
- var rest = p.slice(semi + 1).trim();
317
- var qm = rest.match(Q_VALUE_RE);
318
- q = qm ? parseFloat(qm[1]) : 1;
319
- if (isNaN(q) || q < 0) q = 0;
320
- if (q > 1) q = 1;
321
- }
322
- out.push({ value: value, q: q });
323
- }
324
- out.sort(function (a, b) { return b.q - a.q; });
325
- return out;
326
- }
327
-
328
- module.exports = {
329
- resolveRoute: resolveRoute,
330
- captureResponseStatus: captureResponseStatus,
331
- extractActorContext: extractActorContext,
332
- resolveActorWithOverride: resolveActorWithOverride,
333
- parseQualityList: parseQualityList,
334
- parseListHeader: parseListHeader,
335
- // proxy-trust primitives (default refuses forwarded headers)
336
- clientIp: clientIp,
337
- requestProtocol: requestProtocol,
338
- appendVary: appendVary,
339
- HTTP_STATUS: HTTP_STATUS,
340
- };
1
+ "use strict";
2
+ /**
3
+ * request-helpers — small shared utilities for HTTP request middleware.
4
+ *
5
+ * The framework's metrics + tracing requestMiddleware both label by
6
+ * route TEMPLATE and capture the final response status. They had
7
+ * identical implementations of:
8
+ *
9
+ * 1. Reading req.routePattern with a URL-fallback
10
+ * 2. Wrapping res.writeHead + reading res.statusCode at res.end
11
+ *
12
+ * This module owns the two helpers so the duplication doesn't drift —
13
+ * if either pattern changes (e.g. handle res.statusMessage), it changes
14
+ * once.
15
+ *
16
+ * Public API:
17
+ *
18
+ * resolveRoute(req)
19
+ * Returns req.routePattern when the router populated it,
20
+ * otherwise the URL with query string stripped.
21
+ *
22
+ * captureResponseStatus(res, onEnd)
23
+ * Wraps res.writeHead + res.end. Calls onEnd(status) once when the
24
+ * response ends, with the final status pulled from writeHead's
25
+ * argument OR from res.statusCode (modern Node handlers set it
26
+ * directly without going through writeHead). Operators wrap their
27
+ * own pre-end logic by passing it as onEnd.
28
+ *
29
+ * Returns the original (unwrapped) `res.end`. Useful for unit tests
30
+ * that need to assert against the original behavior.
31
+ */
32
+
33
+ // HTTP status codes used across the framework's HTTP-shaped surface.
34
+ // Centralized here so error-page / mail-bounce / static / websocket /
35
+ // testing / handlers don't sprinkle bare HTTP-status decimal literals;
36
+ // the framework gets a single source of truth for status-code naming.
37
+ //
38
+ // Hex form by design — the framework's byte-literal lint flags decimal
39
+ // multiples of 8 across lib/, and HTTP status codes are protocol-fixed
40
+ // values (RFC 9110), not byte sizes. Names are RFC 9110 reason phrases;
41
+ // every consumer reads HTTP_STATUS.<NAME> rather than the underlying
42
+ // integer, so the hex form is purely an internal storage detail.
43
+ var HTTP_STATUS = Object.freeze({
44
+ OK: 0xC8,
45
+ PARTIAL_CONTENT: 0xCE,
46
+ NO_CONTENT: 0xCC,
47
+ NOT_MODIFIED: 0x130,
48
+ BAD_REQUEST: 0x190,
49
+ UNAUTHORIZED: 0x191,
50
+ FORBIDDEN: 0x193,
51
+ NOT_FOUND: 0x194,
52
+ METHOD_NOT_ALLOWED: 0x195,
53
+ CONFLICT: 0x199,
54
+ PAYLOAD_TOO_LARGE: 0x19D,
55
+ UNSUPPORTED_MEDIA_TYPE: 0x19F,
56
+ RANGE_NOT_SATISFIABLE: 0x1A0,
57
+ UNPROCESSABLE_CONTENT: 0x1A6,
58
+ PRECONDITION_FAILED: 0x19C,
59
+ TOO_MANY_REQUESTS: 0x1AD,
60
+ UNAVAILABLE_FOR_LEGAL_REASONS: 0x1C3,
61
+ INTERNAL_SERVER_ERROR: 0x1F4,
62
+ BAD_GATEWAY: 0x1F6,
63
+ SERVICE_UNAVAILABLE: 0x1F7,
64
+ GATEWAY_TIMEOUT: 0x1F8,
65
+ });
66
+
67
+ // extractActorContext(req) — pull the 5 W's from a request for audit
68
+ // chain emission. WHO/WHERE/HOW columns on _blamejs_audit_log are
69
+ // populated from this shape:
70
+ //
71
+ // { ip, userAgent, sessionId, requestId, method, route, userId }
72
+ //
73
+ // Every field is best-effort: missing or non-request inputs return
74
+ // an object with whatever could be inferred plus null elsewhere.
75
+ // Audit chain treats null as "unknown", so partial context is safe.
76
+ //
77
+ // Caller-supplied actor (existing actor.userId, actor.ip, etc.) is
78
+ // merged on top of the request-derived fields — explicit operator
79
+ // override always wins.
80
+ function extractActorContext(req, override) {
81
+ var ctx = {
82
+ ip: null,
83
+ userAgent: null,
84
+ sessionId: null,
85
+ requestId: null,
86
+ method: null,
87
+ route: null,
88
+ userId: null,
89
+ };
90
+ if (req && typeof req === "object") {
91
+ // Direct properties first (Express-shaped frameworks set req.ip).
92
+ if (typeof req.ip === "string") ctx.ip = req.ip;
93
+ else if (req.connection && typeof req.connection.remoteAddress === "string") {
94
+ ctx.ip = req.connection.remoteAddress;
95
+ } else if (req.socket && typeof req.socket.remoteAddress === "string") {
96
+ ctx.ip = req.socket.remoteAddress;
97
+ }
98
+ if (req.headers && typeof req.headers["user-agent"] === "string") {
99
+ ctx.userAgent = req.headers["user-agent"];
100
+ }
101
+ if (req.session && typeof req.session.id === "string") ctx.sessionId = req.session.id;
102
+ else if (typeof req.sessionId === "string") ctx.sessionId = req.sessionId;
103
+ if (typeof req.requestId === "string") ctx.requestId = req.requestId;
104
+ else if (req.headers && typeof req.headers["x-request-id"] === "string") {
105
+ ctx.requestId = req.headers["x-request-id"];
106
+ }
107
+ if (typeof req.method === "string") ctx.method = req.method;
108
+ ctx.route = resolveRoute(req);
109
+ // userId from common shapes the framework's auth surfaces produce
110
+ if (req.user && typeof req.user.id === "string") ctx.userId = req.user.id;
111
+ else if (req.user && typeof req.user.userId === "string") ctx.userId = req.user.userId;
112
+ else if (req.apiKey && typeof req.apiKey.ownerId === "string") ctx.userId = req.apiKey.ownerId;
113
+ }
114
+ if (override && typeof override === "object") {
115
+ for (var k in override) {
116
+ if (Object.prototype.hasOwnProperty.call(override, k) && override[k] != null) {
117
+ ctx[k] = override[k];
118
+ }
119
+ }
120
+ }
121
+ return ctx;
122
+ }
123
+
124
+ // Convenience wrapper for primitives that accept an optional
125
+ // `{ req, context }` shape and want to thread it into an audit-emit
126
+ // `actor` field. Replaces the four near-identical `_actor()` helpers
127
+ // that lived in api-key, cache, seeders, and notify before v0.4.29.
128
+ //
129
+ // callerOpts: operator-supplied `{ req?, context? }` (e.g. the
130
+ // primitive's call-site opts bag)
131
+ // baseOverride: optional seed values applied BEFORE callerOpts.context
132
+ // so `context` wins. api-key seeds `{ userId }` here so
133
+ // the resolved key's owner becomes the default actor
134
+ // unless the operator passes their own context.userId.
135
+ //
136
+ // Returns the same shape as extractActorContext.
137
+ function resolveActorWithOverride(callerOpts, baseOverride) {
138
+ var override = baseOverride ? Object.assign({}, baseOverride) : {};
139
+ if (callerOpts && callerOpts.context && typeof callerOpts.context === "object") {
140
+ for (var k in callerOpts.context) {
141
+ if (Object.prototype.hasOwnProperty.call(callerOpts.context, k)) {
142
+ override[k] = callerOpts.context[k];
143
+ }
144
+ }
145
+ }
146
+ return extractActorContext(callerOpts && callerOpts.req, override);
147
+ }
148
+
149
+ // ---- Proxy-trust primitives (v0.5.3) ----
150
+ //
151
+ // `X-Forwarded-For` and `X-Forwarded-Proto` are operator-trust headers —
152
+ // behind a sanitizing reverse proxy they carry the apparent origin /
153
+ // scheme; without one they're attacker-forgeable. Default is to NOT
154
+ // trust them; operators behind a proxy set `trustProxy: true` (or a
155
+ // hop count for multi-hop chains) per-middleware to opt in.
156
+ //
157
+ // clientIp(req, { trustProxy }) → string | null
158
+ //
159
+ // trustProxy false (default): socket.remoteAddress only
160
+ // trustProxy true: leftmost x-forwarded-for hop, else socket
161
+ // trustProxy <integer N>: Nth-from-rightmost xff hop (skip-N-trusted-hops)
162
+ //
163
+ // Middleware accepts `trustProxy` as an opt and threads it through;
164
+ // the framework refuses to silently pick up forwarded headers without
165
+ // the operator's explicit acknowledgement.
166
+
167
+ function clientIp(req, opts) {
168
+ if (!req) return null;
169
+ var trust = opts && opts.trustProxy;
170
+ if (trust && req.headers) {
171
+ var xff = req.headers["x-forwarded-for"];
172
+ if (xff) {
173
+ var hops = parseListHeader(xff);
174
+ if (trust === true) return hops[0];
175
+ if (typeof trust === "number" && trust >= 1 && hops.length >= trust) {
176
+ return hops[hops.length - trust];
177
+ }
178
+ }
179
+ }
180
+ if (req.socket && typeof req.socket.remoteAddress === "string") return req.socket.remoteAddress;
181
+ if (req.connection && typeof req.connection.remoteAddress === "string") return req.connection.remoteAddress;
182
+ return null;
183
+ }
184
+
185
+ function requestProtocol(req, opts) {
186
+ if (!req) return "http";
187
+ var trust = opts && opts.trustProxy;
188
+ if (trust && req.headers) {
189
+ var fwd = req.headers["x-forwarded-proto"];
190
+ if (typeof fwd === "string" && fwd.length > 0) {
191
+ var hops = parseListHeader(fwd, { lowercase: true });
192
+ if (hops.length > 0) return hops[0];
193
+ }
194
+ }
195
+ if (req.socket && req.socket.encrypted) return "https";
196
+ if (req.connection && req.connection.encrypted) return "https";
197
+ return "http";
198
+ }
199
+
200
+ // parseListHeader — split a comma-separated header / opt value into a
201
+ // list of trimmed non-empty tokens. Replaces the
202
+ // `String(x).split(",").map(s => s.trim()).filter(Boolean)` chain that
203
+ // was duplicated across cors / compression / scheduler / webhook /
204
+ // websocket / db-schema / cli before v0.5.17.
205
+ //
206
+ // parseListHeader("a, b , ,c") → ["a", "b", "c"]
207
+ // parseListHeader("Foo, Bar", { lowercase: true })
208
+ // → ["foo", "bar"]
209
+ // parseListHeader(undefined) → []
210
+ // parseListHeader("") → []
211
+ //
212
+ // Tolerant read: non-string input returns [] — these are read from
213
+ // request headers that the network might omit. Callers needing stricter
214
+ // checks layer their own validation on the result.
215
+ function parseListHeader(value, opts) {
216
+ if (value == null) return [];
217
+ opts = opts || {};
218
+ var s = typeof value === "string" ? value : String(value);
219
+ if (s.length === 0) return [];
220
+ var parts = s.split(",");
221
+ var out = [];
222
+ for (var i = 0; i < parts.length; i++) {
223
+ var t = parts[i].trim();
224
+ if (t.length === 0) continue;
225
+ out.push(opts.lowercase ? t.toLowerCase() : t);
226
+ }
227
+ return out;
228
+ }
229
+
230
+ // Append a token to a `Vary` response header without dropping prior
231
+ // values (compression middleware sets `Vary: Accept-Encoding`, an
232
+ // auth helper might set `Vary: Authorization`, etc.). Idempotent —
233
+ // re-adding an existing token is a no-op.
234
+ function appendVary(res, value) {
235
+ if (!res || typeof res.getHeader !== "function" || typeof res.setHeader !== "function") return;
236
+ var existing = res.getHeader("Vary");
237
+ if (existing == null || existing === "") { res.setHeader("Vary", value); return; }
238
+ var tokens = parseListHeader(existing);
239
+ var lower = value.toLowerCase();
240
+ for (var i = 0; i < tokens.length; i++) if (tokens[i].toLowerCase() === lower) return;
241
+ tokens.push(value);
242
+ res.setHeader("Vary", tokens.join(", "));
243
+ }
244
+
245
+ function resolveRoute(req) {
246
+ if (req && typeof req.routePattern === "string" && req.routePattern.length > 0) {
247
+ return req.routePattern;
248
+ }
249
+ var url = req && req.url;
250
+ if (typeof url !== "string" || url.length === 0) return "/";
251
+ var qIdx = url.indexOf("?");
252
+ return qIdx === -1 ? url : url.slice(0, qIdx);
253
+ }
254
+
255
+ function captureResponseStatus(res, onEnd) {
256
+ if (!res || typeof onEnd !== "function") {
257
+ throw new Error("captureResponseStatus: requires (res, onEnd)");
258
+ }
259
+ var origEnd = res.end;
260
+ var origWriteHead = res.writeHead;
261
+ var statusFromWriteHead = null;
262
+ res.writeHead = function (s) {
263
+ statusFromWriteHead = s;
264
+ return origWriteHead.apply(res, arguments);
265
+ };
266
+ res.end = function () {
267
+ var status = statusFromWriteHead != null
268
+ ? statusFromWriteHead
269
+ : (typeof res.statusCode === "number" ? res.statusCode : HTTP_STATUS.OK);
270
+ try { onEnd(status); }
271
+ catch (_e) { /* onEnd never breaks the response — caller's instrumentation issue */ }
272
+ return origEnd.apply(res, arguments);
273
+ };
274
+ return origEnd;
275
+ }
276
+
277
+ // parseQualityList — RFC 9110 §12.5 Accept-* header parser.
278
+ //
279
+ // Returns `[{ value, q }]` sorted by q descending. Used by content
280
+ // negotiation (`Accept-Encoding`, `Accept-Language`, `Accept`, etc.).
281
+ // Each Accept-* middleware previously had its own copy of this loop;
282
+ // extracting it here keeps the q-value semantics consistent
283
+ // (q=0 = explicit exclusion; clamped to [0, 1]; missing q = 1).
284
+ //
285
+ // parseQualityList("br;q=1.0, gzip;q=0.5, *;q=0")
286
+ // → [{ value: "br", q: 1 }, { value: "gzip", q: 0.5 }, { value: "*", q: 0 }]
287
+ //
288
+ // `value` is lowercased by default; pass `{ caseSensitive: true }` to
289
+ // preserve case (BCP 47 language tags want case preservation since
290
+ // `pt-BR` and `pt-br` resolve identically but operators may match by
291
+ // canonical form themselves).
292
+ //
293
+ // Bad input (non-string, empty) returns []. RFC 9110 says an absent
294
+ // Accept header means "accept anything"; callers handle that absence
295
+ // at their own layer (compression's [{ encoding: "*", q: 1 }] default
296
+ // vs i18n's "fall back to default locale" — different semantics).
297
+ var Q_VALUE_RE = /(?:^|;|\s)q\s*=\s*([0-9]*\.?[0-9]+)/i;
298
+
299
+ function parseQualityList(headerValue, opts) {
300
+ if (typeof headerValue !== "string" || headerValue.length === 0) return [];
301
+ opts = opts || {};
302
+ var caseSensitive = opts.caseSensitive === true;
303
+ var parts = headerValue.split(",");
304
+ var out = [];
305
+ for (var i = 0; i < parts.length; i++) {
306
+ var p = parts[i].trim();
307
+ if (p.length === 0) continue;
308
+ var semi = p.indexOf(";");
309
+ var value, q;
310
+ if (semi === -1) {
311
+ value = caseSensitive ? p : p.toLowerCase();
312
+ q = 1;
313
+ } else {
314
+ var head = p.slice(0, semi).trim();
315
+ value = caseSensitive ? head : head.toLowerCase();
316
+ var rest = p.slice(semi + 1).trim();
317
+ var qm = rest.match(Q_VALUE_RE);
318
+ q = qm ? parseFloat(qm[1]) : 1;
319
+ if (isNaN(q) || q < 0) q = 0;
320
+ if (q > 1) q = 1;
321
+ }
322
+ out.push({ value: value, q: q });
323
+ }
324
+ out.sort(function (a, b) { return b.q - a.q; });
325
+ return out;
326
+ }
327
+
328
+ module.exports = {
329
+ resolveRoute: resolveRoute,
330
+ captureResponseStatus: captureResponseStatus,
331
+ extractActorContext: extractActorContext,
332
+ resolveActorWithOverride: resolveActorWithOverride,
333
+ parseQualityList: parseQualityList,
334
+ parseListHeader: parseListHeader,
335
+ // proxy-trust primitives (default refuses forwarded headers)
336
+ clientIp: clientIp,
337
+ requestProtocol: requestProtocol,
338
+ appendVary: appendVary,
339
+ HTTP_STATUS: HTTP_STATUS,
340
+ };