@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
package/lib/error-page.js CHANGED
@@ -1,420 +1,420 @@
1
- "use strict";
2
- /**
3
- * errors-page — router error handler with rich dev page + safe prod page.
4
- *
5
- * Registered on a router via `router.onError(handler)`. Catches
6
- * everything middleware or route handlers throw, classifies it, logs
7
- * it, and writes a response in the format the client wants (HTML or
8
- * JSON). The same handler covers both modes — operator sets opts.mode
9
- * (or omits it and it auto-detects from NODE_ENV).
10
- *
11
- * var handler = b.errorPage.create({
12
- * mode: "dev", // "dev" | "prod"; default: auto from NODE_ENV
13
- * log: logInstance, // optional structured logger
14
- * audit: true, // emit audit events for 401/403/429
15
- * brand: "myapp", // shown on the page
16
- * contact: "ops@app", // optional, shown in prod mode
17
- * // dev-mode toggles (ignored in prod):
18
- * showStack: true, // default true in dev
19
- * showRequestInfo: true, // default true in dev
20
- * showEnvVars: false, // default false (env can carry secrets)
21
- * // optional override — return true to take over the response
22
- * onError: function (err, req, res, ctx) { … },
23
- * });
24
- * router.onError(handler);
25
- *
26
- * Classification:
27
- * - err.isAppError or err.statusCode (number) → use that status + message
28
- * - err.isFrameworkError with a known mapping → infer status (401, 403, …)
29
- * - anything else → 500, generic "Internal Server Error" to client
30
- *
31
- * Stack traces are NEVER sent to the client in prod mode. Even in dev,
32
- * binding to a non-loopback interface is gated — operators who serve
33
- * the dev page on a public address get prod-style responses with a
34
- * one-line warning logged at boot. (Implemented as a hint flag on the
35
- * handler that opts in to that gate; default off.)
36
- *
37
- * Content negotiation: `Accept: application/json` (or absence of html
38
- * in Accept) → JSON `{ error, code? }`. Otherwise HTML.
39
- */
40
-
41
- var lazyRequire = require("./lazy-require");
42
- var logModule = require("./log");
43
- var requestHelpers = require("./request-helpers");
44
- var safeEnv = require("./parsers/safe-env");
45
- var template = require("./template");
46
- var audit = lazyRequire(function () { return require("./audit"); });
47
-
48
- var bootLog = logModule.boot("errors-page");
49
-
50
- var _esc = template.escapeHtml;
51
- var H = requestHelpers.HTTP_STATUS;
52
-
53
- // Status code → default short reason. Used when the error doesn't carry
54
- // its own message (e.g. a generic Error thrown from a route). Keyed by
55
- // the framework's centralized HTTP_STATUS hex IDs (RFC 9110 reason
56
- // phrases). JS coerces numeric keys to strings, so STATUS_REASONS[404]
57
- // == STATUS_REASONS[H.NOT_FOUND].
58
- var STATUS_REASONS = {};
59
- STATUS_REASONS[H.BAD_REQUEST] = "Bad Request";
60
- STATUS_REASONS[H.UNAUTHORIZED] = "Unauthorized";
61
- STATUS_REASONS[H.FORBIDDEN] = "Forbidden";
62
- STATUS_REASONS[H.NOT_FOUND] = "Not Found";
63
- STATUS_REASONS[H.METHOD_NOT_ALLOWED] = "Method Not Allowed";
64
- STATUS_REASONS[H.CONFLICT] = "Conflict";
65
- STATUS_REASONS[H.PAYLOAD_TOO_LARGE] = "Payload Too Large";
66
- STATUS_REASONS[H.UNSUPPORTED_MEDIA_TYPE] = "Unsupported Media Type";
67
- STATUS_REASONS[H.UNPROCESSABLE_CONTENT] = "Unprocessable Content";
68
- STATUS_REASONS[H.TOO_MANY_REQUESTS] = "Too Many Requests";
69
- STATUS_REASONS[H.INTERNAL_SERVER_ERROR] = "Internal Server Error";
70
- STATUS_REASONS[H.BAD_GATEWAY] = "Bad Gateway";
71
- STATUS_REASONS[H.SERVICE_UNAVAILABLE] = "Service Unavailable";
72
- STATUS_REASONS[H.GATEWAY_TIMEOUT] = "Gateway Timeout";
73
-
74
- // Map common framework error classes → HTTP status. Operators who
75
- // throw their own AppError-like classes set isAppError + statusCode
76
- // and bypass this map entirely.
77
- function _classify(err) {
78
- if (!err || typeof err !== "object") {
79
- return { status: H.INTERNAL_SERVER_ERROR, code: "INTERNAL_ERROR", message: "Internal Server Error", classified: false };
80
- }
81
- // Apps that follow the standard convention: { isAppError, statusCode, code, message }
82
- if (err.isAppError) {
83
- return {
84
- status: err.statusCode || H.INTERNAL_SERVER_ERROR,
85
- code: err.code || "APP_ERROR",
86
- message: err.message || STATUS_REASONS[err.statusCode || H.INTERNAL_SERVER_ERROR] || "Error",
87
- classified: true,
88
- };
89
- }
90
- // Framework error subclasses we know map to specific HTTP statuses.
91
- if (err.isAuthError) {
92
- return { status: H.UNAUTHORIZED, code: err.code || "AUTH_FAILED", message: err.message || "Unauthorized", classified: true };
93
- }
94
- if (err.code === "VALIDATION_ERROR" || err.name === "ValidationError") {
95
- return { status: H.BAD_REQUEST, code: err.code || "VALIDATION_ERROR", message: err.message || "Bad Request", classified: true };
96
- }
97
- if (err.isSafeJsonError) {
98
- return { status: H.BAD_REQUEST, code: err.code || "json/invalid", message: err.message || "Bad Request", path: err.path || null, classified: true };
99
- }
100
- // Permanent framework errors that map cleanly to 4xx
101
- if ((err.isStorageError || err.isQueueError || err.isExternalDbError) && err.permanent) {
102
- return { status: H.BAD_REQUEST, code: err.code || "ERROR", message: err.message || "Bad Request", classified: true };
103
- }
104
- if (typeof err.statusCode === "number") {
105
- return {
106
- status: err.statusCode,
107
- code: err.code || "ERROR",
108
- message: err.message || STATUS_REASONS[err.statusCode] || "Error",
109
- classified: true,
110
- };
111
- }
112
- return { status: H.INTERNAL_SERVER_ERROR, code: err.code || "INTERNAL_ERROR", message: err.message || "Internal Server Error", classified: false };
113
- }
114
-
115
- function _wantsJson(req, defaultFormat) {
116
- if (defaultFormat === "json") return true;
117
- if (defaultFormat === "html") return false;
118
- var accept = (req && req.headers && req.headers.accept) || "";
119
- // Default to JSON only when Accept makes it explicit. Browsers send
120
- // text/html, programmatic clients usually send application/json.
121
- if (accept.indexOf("application/json") !== -1) return true;
122
- if (accept.indexOf("text/html") !== -1) return false;
123
- // Heuristic: APIs typically don't ask for html; treat empty Accept
124
- // on non-GET as JSON, GET as HTML.
125
- return req && req.method && req.method.toUpperCase() !== "GET";
126
- }
127
-
128
- function _redactHeaders(headers) {
129
- if (!headers || typeof headers !== "object") return {};
130
- var out = {};
131
- var keys = Object.keys(headers);
132
- for (var i = 0; i < keys.length; i++) {
133
- var k = keys[i];
134
- var lk = k.toLowerCase();
135
- // Strip auth-bearing headers from the dev page so opening a stack
136
- // trace doesn't put a session cookie or bearer token in front of
137
- // anyone who can see the screen.
138
- if (lk === "cookie" || lk === "authorization" ||
139
- lk === "x-api-key" || lk === "x-csrf-token" ||
140
- lk.indexOf("token") !== -1) {
141
- out[k] = "[REDACTED]";
142
- } else {
143
- out[k] = headers[k];
144
- }
145
- }
146
- return out;
147
- }
148
-
149
- function _renderProdHtml(info, opts) {
150
- var brand = opts.brand ? _esc(opts.brand) : "blamejs";
151
- var contact = opts.contact ? _esc(opts.contact) : null;
152
- return [
153
- "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",
154
- "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
155
- "<title>", _esc(STATUS_REASONS[info.status] || "Error"), " — ", brand, "</title>",
156
- "<style>",
157
- "html,body{height:100%;margin:0;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0d1117;color:#c9d1d9}",
158
- ".wrap{display:flex;align-items:center;justify-content:center;min-height:100%;padding:2rem}",
159
- ".card{max-width:520px;text-align:center;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:48px 32px}",
160
- ".status{font-size:64px;font-weight:700;color:#58a6ff;margin:0;line-height:1}",
161
- ".title{font-size:18px;font-weight:600;color:#e6edf3;margin:18px 0 6px}",
162
- ".msg{font-size:14px;color:#8b949e;margin:0 0 24px;line-height:1.5}",
163
- ".contact{font-size:13px;color:#6e7681}",
164
- ".brand{font-size:12px;color:#484f58;margin-top:32px;letter-spacing:.05em;text-transform:uppercase}",
165
- "a{color:#58a6ff;text-decoration:none}a:hover{text-decoration:underline}",
166
- "</style></head><body><div class=\"wrap\"><div class=\"card\">",
167
- "<p class=\"status\">", String(info.status), "</p>",
168
- "<p class=\"title\">", _esc(STATUS_REASONS[info.status] || "Error"), "</p>",
169
- "<p class=\"msg\">", _esc(info.publicMessage), "</p>",
170
- contact ? "<p class=\"contact\">Contact <a href=\"mailto:" + contact + "\">" + contact + "</a> if this persists.</p>" : "",
171
- "<p class=\"brand\">", brand, "</p>",
172
- "</div></div></body></html>",
173
- ].join("");
174
- }
175
-
176
- function _renderDevHtml(info, opts, ctx) {
177
- var brand = opts.brand ? _esc(opts.brand) : "blamejs";
178
- var stackHtml = "";
179
- if (opts.showStack && info.stack) {
180
- stackHtml = "<pre class=\"stack\">" + _esc(info.stack) + "</pre>";
181
- }
182
- var requestHtml = "";
183
- if (opts.showRequestInfo && ctx && ctx.req) {
184
- var req = ctx.req;
185
- var headers = _redactHeaders(req.headers);
186
- var headerRows = Object.keys(headers).map(function (k) {
187
- return "<tr><th>" + _esc(k) + "</th><td>" + _esc(headers[k]) + "</td></tr>";
188
- }).join("");
189
- requestHtml = [
190
- "<section><h2>Request</h2>",
191
- "<table class=\"kv\">",
192
- "<tr><th>method</th><td>", _esc(req.method || ""), "</td></tr>",
193
- "<tr><th>url</th><td>", _esc(req.url || ""), "</td></tr>",
194
- ctx.requestId ? ("<tr><th>requestId</th><td>" + _esc(ctx.requestId) + "</td></tr>") : "",
195
- "</table>",
196
- headerRows ? ("<h3>Headers</h3><table class=\"kv\">" + headerRows + "</table>") : "",
197
- "</section>",
198
- ].join("");
199
- }
200
- var envHtml = "";
201
- if (opts.showEnvVars) {
202
- var envKeys = Object.keys(process.env).filter(function (k) {
203
- // Even with showEnvVars=true, keep secret-shaped keys redacted —
204
- // turning the dev page on shouldn't leak production credentials
205
- // when an operator forgets to switch modes.
206
- return !/SECRET|TOKEN|KEY|PASS|CRED/i.test(k);
207
- }).sort();
208
- var envRows = envKeys.map(function (k) {
209
- return "<tr><th>" + _esc(k) + "</th><td>" + _esc(process.env[k]) + "</td></tr>";
210
- }).join("");
211
- envHtml = "<section><h2>Environment</h2><table class=\"kv\">" + envRows + "</table></section>";
212
- }
213
- return [
214
- "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",
215
- "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
216
- "<title>", String(info.status), " ", _esc(STATUS_REASONS[info.status] || "Error"),
217
- " — ", brand, " (dev)</title>",
218
- "<style>",
219
- "*{box-sizing:border-box}",
220
- "body{margin:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#0d1117;color:#c9d1d9;font-size:13px;line-height:1.55}",
221
- "header{background:#21262d;padding:24px 32px;border-bottom:3px solid #f85149}",
222
- "header .status{display:inline-block;background:#f85149;color:#fff;padding:4px 10px;border-radius:6px;font-weight:700;margin-right:12px}",
223
- "header h1{display:inline;font-size:18px;color:#e6edf3;font-weight:600}",
224
- "header .err-code{margin-top:8px;font-size:12px;color:#8b949e}",
225
- "main{padding:24px 32px;max-width:1200px}",
226
- "section{margin-bottom:32px}",
227
- "h2{font-size:13px;color:#8b949e;text-transform:uppercase;letter-spacing:.08em;margin:0 0 12px;font-weight:600}",
228
- "h3{font-size:12px;color:#8b949e;text-transform:uppercase;letter-spacing:.05em;margin:18px 0 8px;font-weight:600}",
229
- ".stack{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:16px;margin:0;white-space:pre-wrap;word-break:break-word;color:#ffa657;font-size:12px;overflow-x:auto}",
230
- "table.kv{width:100%;border-collapse:collapse;background:#161b22;border:1px solid #30363d;border-radius:8px;overflow:hidden}",
231
- "table.kv th{text-align:left;padding:8px 12px;color:#8b949e;font-weight:500;width:200px;background:#0d1117;border-bottom:1px solid #21262d;border-right:1px solid #21262d;vertical-align:top}",
232
- "table.kv td{padding:8px 12px;color:#c9d1d9;word-break:break-word;border-bottom:1px solid #21262d}",
233
- "table.kv tr:last-child th,table.kv tr:last-child td{border-bottom:none}",
234
- "footer{padding:16px 32px;color:#484f58;font-size:11px;letter-spacing:.05em;text-transform:uppercase;border-top:1px solid #21262d}",
235
- "</style></head><body>",
236
- "<header>",
237
- "<span class=\"status\">", String(info.status), "</span>",
238
- "<h1>", _esc(STATUS_REASONS[info.status] || "Error"), " — ", _esc(info.devMessage), "</h1>",
239
- info.code ? ("<div class=\"err-code\">code: " + _esc(info.code) + "</div>") : "",
240
- "</header>",
241
- "<main>",
242
- stackHtml ? ("<section><h2>Stack</h2>" + stackHtml + "</section>") : "",
243
- requestHtml,
244
- envHtml,
245
- "</main>",
246
- "<footer>", brand, " · dev mode · stack/headers redacted in prod</footer>",
247
- "</body></html>",
248
- ].join("");
249
- }
250
-
251
- function _writeResponse(res, status, contentType, body) {
252
- if (res.writableEnded) return;
253
- try {
254
- var headers = { "Content-Type": contentType, "Cache-Control": "no-store" };
255
- // Prefer writeHead so the status survives under both real Node
256
- // ServerResponse and lighter mock objects that only track status
257
- // via writeHead's first arg. setHeader fallback covers shims that
258
- // expose only that surface.
259
- if (typeof res.writeHead === "function") {
260
- res.writeHead(status, headers);
261
- } else {
262
- res.statusCode = status;
263
- if (typeof res.setHeader === "function") {
264
- res.setHeader("Content-Type", contentType);
265
- res.setHeader("Cache-Control", "no-store");
266
- }
267
- }
268
- res.end(body);
269
- } catch (_e) {
270
- // Last-resort plain text. If even this fails, the connection is
271
- // already gone; nothing to do.
272
- try { res.end("Internal Server Error"); } catch (_e2) { /* socket gone */ }
273
- }
274
- }
275
-
276
- function create(opts) {
277
- opts = opts || {};
278
- var modeOpt = opts.mode;
279
- var mode;
280
- if (modeOpt === "dev" || modeOpt === "prod") {
281
- mode = modeOpt;
282
- } else {
283
- var nodeEnv = safeEnv.readVar("NODE_ENV");
284
- mode = (nodeEnv === "production") ? "prod" : "dev";
285
- }
286
-
287
- var auditOn = opts.audit !== false;
288
- var auditAction = typeof opts.auditAction === "string" && opts.auditAction.length > 0
289
- ? opts.auditAction
290
- : "request.error";
291
- // Same proxy-trust boundary as the rest of the framework — without
292
- // trustProxy, X-Forwarded-For is ignored as attacker-forgeable.
293
- var trustProxy = opts.trustProxy === true || typeof opts.trustProxy === "number"
294
- ? opts.trustProxy : false;
295
- // defaultFormat:
296
- // "auto" (default) — negotiate via Accept header
297
- // "json" — always JSON (API-style middleware default)
298
- // "html" — always HTML (page-style middleware default)
299
- var defaultFormat = opts.defaultFormat;
300
- if (defaultFormat !== undefined &&
301
- defaultFormat !== "auto" && defaultFormat !== "json" && defaultFormat !== "html") {
302
- throw new Error("errors-page: opts.defaultFormat must be 'auto', 'json', or 'html'");
303
- }
304
- var log = opts.log || null; // structured logger if supplied
305
- var brand = opts.brand || null;
306
- var contact = opts.contact || null;
307
- var showStack = mode === "dev" && opts.showStack !== false;
308
- var showRequestInfo = mode === "dev" && opts.showRequestInfo !== false;
309
- var showEnvVars = mode === "dev" && opts.showEnvVars === true;
310
- var onErrorHook = typeof opts.onError === "function" ? opts.onError : null;
311
-
312
- var _log = logModule.makeViaOrFallback(log, bootLog);
313
-
314
- function handler(err, req, res) {
315
- var info = _classify(err);
316
- info.stack = (err && err.stack) ? err.stack : null;
317
- // The message we show to the client depends on whether we recognize
318
- // the error class. Generic 500s never leak the original message.
319
- info.publicMessage = (info.status >= 500 && !info.classified)
320
- ? (STATUS_REASONS[info.status] || "Internal Server Error")
321
- : info.message;
322
- info.devMessage = info.message;
323
-
324
- // Custom hook: operator can take over the response entirely.
325
- if (onErrorHook) {
326
- var handled = false;
327
- try { handled = !!onErrorHook(err, req, res, info); }
328
- catch (e) {
329
- _log("error", "errors-page onError hook threw", { error: (e && e.message) || String(e) });
330
- }
331
- if (handled || (res && res.writableEnded)) return;
332
- }
333
-
334
- // Logging: 5xx always with stack; 4xx as warn without stack noise
335
- var logFields = {
336
- status: info.status,
337
- code: info.code,
338
- method: req && req.method,
339
- url: req && req.url,
340
- requestId: req && req.id,
341
- };
342
- if (info.status >= 500) {
343
- logFields.stack = info.stack || String(err);
344
- _log("error", "unhandled error", logFields);
345
- } else {
346
- _log("warn", "request error", logFields);
347
- }
348
-
349
- // Audit every error. Best-effort — never let an audit-write failure
350
- // mask the original error. Outcome differentiates 5xx (failure) vs
351
- // 4xx (denied) so consumers can filter without re-classifying status.
352
- if (auditOn) {
353
- try {
354
- audit().emit({
355
- action: auditAction,
356
- outcome: info.status >= 500 ? "failure" : "denied",
357
- actor: requestHelpers.extractActorContext(req, {
358
- // Honor the framework's trustProxy boundary — extractActorContext
359
- // reads from req.socket.remoteAddress, but we want X-Forwarded-For
360
- // resolution gated by the operator's opt.
361
- ip: requestHelpers.clientIp(req, { trustProxy: trustProxy }),
362
- // sessionId from session.sid for back-compat with the
363
- // pre-extractActorContext shape (extractActorContext also
364
- // checks session.id; passing both via override is safe).
365
- sessionId: req && req.session && (req.session.sid || req.session.id),
366
- }),
367
- metadata: {
368
- status: info.status,
369
- code: info.code,
370
- method: req && req.method,
371
- url: req && req.url,
372
- requestId: (req && req.id) || (req && req.requestId),
373
- stack: info.status >= 500 ? info.stack : null,
374
- },
375
- reason: info.message,
376
- requestId: (req && req.id) || (req && req.requestId) || null,
377
- });
378
- } catch (_e) { /* audit best-effort */ }
379
- }
380
-
381
- if (res && res.writableEnded) return;
382
-
383
- var ctx = {
384
- req: req,
385
- requestId: req && req.id,
386
- };
387
-
388
- if (_wantsJson(req, defaultFormat)) {
389
- var errorObj = {
390
- code: info.code || (info.status >= 500 ? "internal_error" : "error"),
391
- message: info.publicMessage,
392
- };
393
- if (info.path) errorObj.path = info.path;
394
- if (mode === "dev" && info.stack && showStack && info.status >= 500) {
395
- errorObj.stack = info.stack;
396
- }
397
- _writeResponse(res, info.status, "application/json; charset=utf-8",
398
- JSON.stringify({ error: errorObj }));
399
- return;
400
- }
401
-
402
- var html = (mode === "dev")
403
- ? _renderDevHtml(info, {
404
- brand: brand,
405
- showStack: showStack,
406
- showRequestInfo: showRequestInfo,
407
- showEnvVars: showEnvVars,
408
- }, ctx)
409
- : _renderProdHtml(info, { brand: brand, contact: contact });
410
- _writeResponse(res, info.status, "text/html; charset=utf-8", html);
411
- }
412
-
413
- handler.mode = mode;
414
- return handler;
415
- }
416
-
417
- module.exports = {
418
- create: create,
419
- STATUS_REASONS: STATUS_REASONS,
420
- };
1
+ "use strict";
2
+ /**
3
+ * errors-page — router error handler with rich dev page + safe prod page.
4
+ *
5
+ * Registered on a router via `router.onError(handler)`. Catches
6
+ * everything middleware or route handlers throw, classifies it, logs
7
+ * it, and writes a response in the format the client wants (HTML or
8
+ * JSON). The same handler covers both modes — operator sets opts.mode
9
+ * (or omits it and it auto-detects from NODE_ENV).
10
+ *
11
+ * var handler = b.errorPage.create({
12
+ * mode: "dev", // "dev" | "prod"; default: auto from NODE_ENV
13
+ * log: logInstance, // optional structured logger
14
+ * audit: true, // emit audit events for 401/403/429
15
+ * brand: "myapp", // shown on the page
16
+ * contact: "ops@app", // optional, shown in prod mode
17
+ * // dev-mode toggles (ignored in prod):
18
+ * showStack: true, // default true in dev
19
+ * showRequestInfo: true, // default true in dev
20
+ * showEnvVars: false, // default false (env can carry secrets)
21
+ * // optional override — return true to take over the response
22
+ * onError: function (err, req, res, ctx) { … },
23
+ * });
24
+ * router.onError(handler);
25
+ *
26
+ * Classification:
27
+ * - err.isAppError or err.statusCode (number) → use that status + message
28
+ * - err.isFrameworkError with a known mapping → infer status (401, 403, …)
29
+ * - anything else → 500, generic "Internal Server Error" to client
30
+ *
31
+ * Stack traces are NEVER sent to the client in prod mode. Even in dev,
32
+ * binding to a non-loopback interface is gated — operators who serve
33
+ * the dev page on a public address get prod-style responses with a
34
+ * one-line warning logged at boot. (Implemented as a hint flag on the
35
+ * handler that opts in to that gate; default off.)
36
+ *
37
+ * Content negotiation: `Accept: application/json` (or absence of html
38
+ * in Accept) → JSON `{ error, code? }`. Otherwise HTML.
39
+ */
40
+
41
+ var lazyRequire = require("./lazy-require");
42
+ var logModule = require("./log");
43
+ var requestHelpers = require("./request-helpers");
44
+ var safeEnv = require("./parsers/safe-env");
45
+ var template = require("./template");
46
+ var audit = lazyRequire(function () { return require("./audit"); });
47
+
48
+ var bootLog = logModule.boot("errors-page");
49
+
50
+ var _esc = template.escapeHtml;
51
+ var H = requestHelpers.HTTP_STATUS;
52
+
53
+ // Status code → default short reason. Used when the error doesn't carry
54
+ // its own message (e.g. a generic Error thrown from a route). Keyed by
55
+ // the framework's centralized HTTP_STATUS hex IDs (RFC 9110 reason
56
+ // phrases). JS coerces numeric keys to strings, so STATUS_REASONS[404]
57
+ // == STATUS_REASONS[H.NOT_FOUND].
58
+ var STATUS_REASONS = {};
59
+ STATUS_REASONS[H.BAD_REQUEST] = "Bad Request";
60
+ STATUS_REASONS[H.UNAUTHORIZED] = "Unauthorized";
61
+ STATUS_REASONS[H.FORBIDDEN] = "Forbidden";
62
+ STATUS_REASONS[H.NOT_FOUND] = "Not Found";
63
+ STATUS_REASONS[H.METHOD_NOT_ALLOWED] = "Method Not Allowed";
64
+ STATUS_REASONS[H.CONFLICT] = "Conflict";
65
+ STATUS_REASONS[H.PAYLOAD_TOO_LARGE] = "Payload Too Large";
66
+ STATUS_REASONS[H.UNSUPPORTED_MEDIA_TYPE] = "Unsupported Media Type";
67
+ STATUS_REASONS[H.UNPROCESSABLE_CONTENT] = "Unprocessable Content";
68
+ STATUS_REASONS[H.TOO_MANY_REQUESTS] = "Too Many Requests";
69
+ STATUS_REASONS[H.INTERNAL_SERVER_ERROR] = "Internal Server Error";
70
+ STATUS_REASONS[H.BAD_GATEWAY] = "Bad Gateway";
71
+ STATUS_REASONS[H.SERVICE_UNAVAILABLE] = "Service Unavailable";
72
+ STATUS_REASONS[H.GATEWAY_TIMEOUT] = "Gateway Timeout";
73
+
74
+ // Map common framework error classes → HTTP status. Operators who
75
+ // throw their own AppError-like classes set isAppError + statusCode
76
+ // and bypass this map entirely.
77
+ function _classify(err) {
78
+ if (!err || typeof err !== "object") {
79
+ return { status: H.INTERNAL_SERVER_ERROR, code: "INTERNAL_ERROR", message: "Internal Server Error", classified: false };
80
+ }
81
+ // Apps that follow the standard convention: { isAppError, statusCode, code, message }
82
+ if (err.isAppError) {
83
+ return {
84
+ status: err.statusCode || H.INTERNAL_SERVER_ERROR,
85
+ code: err.code || "APP_ERROR",
86
+ message: err.message || STATUS_REASONS[err.statusCode || H.INTERNAL_SERVER_ERROR] || "Error",
87
+ classified: true,
88
+ };
89
+ }
90
+ // Framework error subclasses we know map to specific HTTP statuses.
91
+ if (err.isAuthError) {
92
+ return { status: H.UNAUTHORIZED, code: err.code || "AUTH_FAILED", message: err.message || "Unauthorized", classified: true };
93
+ }
94
+ if (err.code === "VALIDATION_ERROR" || err.name === "ValidationError") {
95
+ return { status: H.BAD_REQUEST, code: err.code || "VALIDATION_ERROR", message: err.message || "Bad Request", classified: true };
96
+ }
97
+ if (err.isSafeJsonError) {
98
+ return { status: H.BAD_REQUEST, code: err.code || "json/invalid", message: err.message || "Bad Request", path: err.path || null, classified: true };
99
+ }
100
+ // Permanent framework errors that map cleanly to 4xx
101
+ if ((err.isStorageError || err.isQueueError || err.isExternalDbError) && err.permanent) {
102
+ return { status: H.BAD_REQUEST, code: err.code || "ERROR", message: err.message || "Bad Request", classified: true };
103
+ }
104
+ if (typeof err.statusCode === "number") {
105
+ return {
106
+ status: err.statusCode,
107
+ code: err.code || "ERROR",
108
+ message: err.message || STATUS_REASONS[err.statusCode] || "Error",
109
+ classified: true,
110
+ };
111
+ }
112
+ return { status: H.INTERNAL_SERVER_ERROR, code: err.code || "INTERNAL_ERROR", message: err.message || "Internal Server Error", classified: false };
113
+ }
114
+
115
+ function _wantsJson(req, defaultFormat) {
116
+ if (defaultFormat === "json") return true;
117
+ if (defaultFormat === "html") return false;
118
+ var accept = (req && req.headers && req.headers.accept) || "";
119
+ // Default to JSON only when Accept makes it explicit. Browsers send
120
+ // text/html, programmatic clients usually send application/json.
121
+ if (accept.indexOf("application/json") !== -1) return true;
122
+ if (accept.indexOf("text/html") !== -1) return false;
123
+ // Heuristic: APIs typically don't ask for html; treat empty Accept
124
+ // on non-GET as JSON, GET as HTML.
125
+ return req && req.method && req.method.toUpperCase() !== "GET";
126
+ }
127
+
128
+ function _redactHeaders(headers) {
129
+ if (!headers || typeof headers !== "object") return {};
130
+ var out = {};
131
+ var keys = Object.keys(headers);
132
+ for (var i = 0; i < keys.length; i++) {
133
+ var k = keys[i];
134
+ var lk = k.toLowerCase();
135
+ // Strip auth-bearing headers from the dev page so opening a stack
136
+ // trace doesn't put a session cookie or bearer token in front of
137
+ // anyone who can see the screen.
138
+ if (lk === "cookie" || lk === "authorization" ||
139
+ lk === "x-api-key" || lk === "x-csrf-token" ||
140
+ lk.indexOf("token") !== -1) {
141
+ out[k] = "[REDACTED]";
142
+ } else {
143
+ out[k] = headers[k];
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+
149
+ function _renderProdHtml(info, opts) {
150
+ var brand = opts.brand ? _esc(opts.brand) : "blamejs";
151
+ var contact = opts.contact ? _esc(opts.contact) : null;
152
+ return [
153
+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",
154
+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
155
+ "<title>", _esc(STATUS_REASONS[info.status] || "Error"), " — ", brand, "</title>",
156
+ "<style>",
157
+ "html,body{height:100%;margin:0;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0d1117;color:#c9d1d9}",
158
+ ".wrap{display:flex;align-items:center;justify-content:center;min-height:100%;padding:2rem}",
159
+ ".card{max-width:520px;text-align:center;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:48px 32px}",
160
+ ".status{font-size:64px;font-weight:700;color:#58a6ff;margin:0;line-height:1}",
161
+ ".title{font-size:18px;font-weight:600;color:#e6edf3;margin:18px 0 6px}",
162
+ ".msg{font-size:14px;color:#8b949e;margin:0 0 24px;line-height:1.5}",
163
+ ".contact{font-size:13px;color:#6e7681}",
164
+ ".brand{font-size:12px;color:#484f58;margin-top:32px;letter-spacing:.05em;text-transform:uppercase}",
165
+ "a{color:#58a6ff;text-decoration:none}a:hover{text-decoration:underline}",
166
+ "</style></head><body><div class=\"wrap\"><div class=\"card\">",
167
+ "<p class=\"status\">", String(info.status), "</p>",
168
+ "<p class=\"title\">", _esc(STATUS_REASONS[info.status] || "Error"), "</p>",
169
+ "<p class=\"msg\">", _esc(info.publicMessage), "</p>",
170
+ contact ? "<p class=\"contact\">Contact <a href=\"mailto:" + contact + "\">" + contact + "</a> if this persists.</p>" : "",
171
+ "<p class=\"brand\">", brand, "</p>",
172
+ "</div></div></body></html>",
173
+ ].join("");
174
+ }
175
+
176
+ function _renderDevHtml(info, opts, ctx) {
177
+ var brand = opts.brand ? _esc(opts.brand) : "blamejs";
178
+ var stackHtml = "";
179
+ if (opts.showStack && info.stack) {
180
+ stackHtml = "<pre class=\"stack\">" + _esc(info.stack) + "</pre>";
181
+ }
182
+ var requestHtml = "";
183
+ if (opts.showRequestInfo && ctx && ctx.req) {
184
+ var req = ctx.req;
185
+ var headers = _redactHeaders(req.headers);
186
+ var headerRows = Object.keys(headers).map(function (k) {
187
+ return "<tr><th>" + _esc(k) + "</th><td>" + _esc(headers[k]) + "</td></tr>";
188
+ }).join("");
189
+ requestHtml = [
190
+ "<section><h2>Request</h2>",
191
+ "<table class=\"kv\">",
192
+ "<tr><th>method</th><td>", _esc(req.method || ""), "</td></tr>",
193
+ "<tr><th>url</th><td>", _esc(req.url || ""), "</td></tr>",
194
+ ctx.requestId ? ("<tr><th>requestId</th><td>" + _esc(ctx.requestId) + "</td></tr>") : "",
195
+ "</table>",
196
+ headerRows ? ("<h3>Headers</h3><table class=\"kv\">" + headerRows + "</table>") : "",
197
+ "</section>",
198
+ ].join("");
199
+ }
200
+ var envHtml = "";
201
+ if (opts.showEnvVars) {
202
+ var envKeys = Object.keys(process.env).filter(function (k) {
203
+ // Even with showEnvVars=true, keep secret-shaped keys redacted —
204
+ // turning the dev page on shouldn't leak production credentials
205
+ // when an operator forgets to switch modes.
206
+ return !/SECRET|TOKEN|KEY|PASS|CRED/i.test(k);
207
+ }).sort();
208
+ var envRows = envKeys.map(function (k) {
209
+ return "<tr><th>" + _esc(k) + "</th><td>" + _esc(process.env[k]) + "</td></tr>";
210
+ }).join("");
211
+ envHtml = "<section><h2>Environment</h2><table class=\"kv\">" + envRows + "</table></section>";
212
+ }
213
+ return [
214
+ "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",
215
+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
216
+ "<title>", String(info.status), " ", _esc(STATUS_REASONS[info.status] || "Error"),
217
+ " — ", brand, " (dev)</title>",
218
+ "<style>",
219
+ "*{box-sizing:border-box}",
220
+ "body{margin:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#0d1117;color:#c9d1d9;font-size:13px;line-height:1.55}",
221
+ "header{background:#21262d;padding:24px 32px;border-bottom:3px solid #f85149}",
222
+ "header .status{display:inline-block;background:#f85149;color:#fff;padding:4px 10px;border-radius:6px;font-weight:700;margin-right:12px}",
223
+ "header h1{display:inline;font-size:18px;color:#e6edf3;font-weight:600}",
224
+ "header .err-code{margin-top:8px;font-size:12px;color:#8b949e}",
225
+ "main{padding:24px 32px;max-width:1200px}",
226
+ "section{margin-bottom:32px}",
227
+ "h2{font-size:13px;color:#8b949e;text-transform:uppercase;letter-spacing:.08em;margin:0 0 12px;font-weight:600}",
228
+ "h3{font-size:12px;color:#8b949e;text-transform:uppercase;letter-spacing:.05em;margin:18px 0 8px;font-weight:600}",
229
+ ".stack{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:16px;margin:0;white-space:pre-wrap;word-break:break-word;color:#ffa657;font-size:12px;overflow-x:auto}",
230
+ "table.kv{width:100%;border-collapse:collapse;background:#161b22;border:1px solid #30363d;border-radius:8px;overflow:hidden}",
231
+ "table.kv th{text-align:left;padding:8px 12px;color:#8b949e;font-weight:500;width:200px;background:#0d1117;border-bottom:1px solid #21262d;border-right:1px solid #21262d;vertical-align:top}",
232
+ "table.kv td{padding:8px 12px;color:#c9d1d9;word-break:break-word;border-bottom:1px solid #21262d}",
233
+ "table.kv tr:last-child th,table.kv tr:last-child td{border-bottom:none}",
234
+ "footer{padding:16px 32px;color:#484f58;font-size:11px;letter-spacing:.05em;text-transform:uppercase;border-top:1px solid #21262d}",
235
+ "</style></head><body>",
236
+ "<header>",
237
+ "<span class=\"status\">", String(info.status), "</span>",
238
+ "<h1>", _esc(STATUS_REASONS[info.status] || "Error"), " — ", _esc(info.devMessage), "</h1>",
239
+ info.code ? ("<div class=\"err-code\">code: " + _esc(info.code) + "</div>") : "",
240
+ "</header>",
241
+ "<main>",
242
+ stackHtml ? ("<section><h2>Stack</h2>" + stackHtml + "</section>") : "",
243
+ requestHtml,
244
+ envHtml,
245
+ "</main>",
246
+ "<footer>", brand, " · dev mode · stack/headers redacted in prod</footer>",
247
+ "</body></html>",
248
+ ].join("");
249
+ }
250
+
251
+ function _writeResponse(res, status, contentType, body) {
252
+ if (res.writableEnded) return;
253
+ try {
254
+ var headers = { "Content-Type": contentType, "Cache-Control": "no-store" };
255
+ // Prefer writeHead so the status survives under both real Node
256
+ // ServerResponse and lighter mock objects that only track status
257
+ // via writeHead's first arg. setHeader fallback covers shims that
258
+ // expose only that surface.
259
+ if (typeof res.writeHead === "function") {
260
+ res.writeHead(status, headers);
261
+ } else {
262
+ res.statusCode = status;
263
+ if (typeof res.setHeader === "function") {
264
+ res.setHeader("Content-Type", contentType);
265
+ res.setHeader("Cache-Control", "no-store");
266
+ }
267
+ }
268
+ res.end(body);
269
+ } catch (_e) {
270
+ // Last-resort plain text. If even this fails, the connection is
271
+ // already gone; nothing to do.
272
+ try { res.end("Internal Server Error"); } catch (_e2) { /* socket gone */ }
273
+ }
274
+ }
275
+
276
+ function create(opts) {
277
+ opts = opts || {};
278
+ var modeOpt = opts.mode;
279
+ var mode;
280
+ if (modeOpt === "dev" || modeOpt === "prod") {
281
+ mode = modeOpt;
282
+ } else {
283
+ var nodeEnv = safeEnv.readVar("NODE_ENV");
284
+ mode = (nodeEnv === "production") ? "prod" : "dev";
285
+ }
286
+
287
+ var auditOn = opts.audit !== false;
288
+ var auditAction = typeof opts.auditAction === "string" && opts.auditAction.length > 0
289
+ ? opts.auditAction
290
+ : "request.error";
291
+ // Same proxy-trust boundary as the rest of the framework — without
292
+ // trustProxy, X-Forwarded-For is ignored as attacker-forgeable.
293
+ var trustProxy = opts.trustProxy === true || typeof opts.trustProxy === "number"
294
+ ? opts.trustProxy : false;
295
+ // defaultFormat:
296
+ // "auto" (default) — negotiate via Accept header
297
+ // "json" — always JSON (API-style middleware default)
298
+ // "html" — always HTML (page-style middleware default)
299
+ var defaultFormat = opts.defaultFormat;
300
+ if (defaultFormat !== undefined &&
301
+ defaultFormat !== "auto" && defaultFormat !== "json" && defaultFormat !== "html") {
302
+ throw new Error("errors-page: opts.defaultFormat must be 'auto', 'json', or 'html'");
303
+ }
304
+ var log = opts.log || null; // structured logger if supplied
305
+ var brand = opts.brand || null;
306
+ var contact = opts.contact || null;
307
+ var showStack = mode === "dev" && opts.showStack !== false;
308
+ var showRequestInfo = mode === "dev" && opts.showRequestInfo !== false;
309
+ var showEnvVars = mode === "dev" && opts.showEnvVars === true;
310
+ var onErrorHook = typeof opts.onError === "function" ? opts.onError : null;
311
+
312
+ var _log = logModule.makeViaOrFallback(log, bootLog);
313
+
314
+ function handler(err, req, res) {
315
+ var info = _classify(err);
316
+ info.stack = (err && err.stack) ? err.stack : null;
317
+ // The message we show to the client depends on whether we recognize
318
+ // the error class. Generic 500s never leak the original message.
319
+ info.publicMessage = (info.status >= 500 && !info.classified)
320
+ ? (STATUS_REASONS[info.status] || "Internal Server Error")
321
+ : info.message;
322
+ info.devMessage = info.message;
323
+
324
+ // Custom hook: operator can take over the response entirely.
325
+ if (onErrorHook) {
326
+ var handled = false;
327
+ try { handled = !!onErrorHook(err, req, res, info); }
328
+ catch (e) {
329
+ _log("error", "errors-page onError hook threw", { error: (e && e.message) || String(e) });
330
+ }
331
+ if (handled || (res && res.writableEnded)) return;
332
+ }
333
+
334
+ // Logging: 5xx always with stack; 4xx as warn without stack noise
335
+ var logFields = {
336
+ status: info.status,
337
+ code: info.code,
338
+ method: req && req.method,
339
+ url: req && req.url,
340
+ requestId: req && req.id,
341
+ };
342
+ if (info.status >= 500) {
343
+ logFields.stack = info.stack || String(err);
344
+ _log("error", "unhandled error", logFields);
345
+ } else {
346
+ _log("warn", "request error", logFields);
347
+ }
348
+
349
+ // Audit every error. Best-effort — never let an audit-write failure
350
+ // mask the original error. Outcome differentiates 5xx (failure) vs
351
+ // 4xx (denied) so consumers can filter without re-classifying status.
352
+ if (auditOn) {
353
+ try {
354
+ audit().emit({
355
+ action: auditAction,
356
+ outcome: info.status >= 500 ? "failure" : "denied",
357
+ actor: requestHelpers.extractActorContext(req, {
358
+ // Honor the framework's trustProxy boundary — extractActorContext
359
+ // reads from req.socket.remoteAddress, but we want X-Forwarded-For
360
+ // resolution gated by the operator's opt.
361
+ ip: requestHelpers.clientIp(req, { trustProxy: trustProxy }),
362
+ // sessionId from session.sid for back-compat with the
363
+ // pre-extractActorContext shape (extractActorContext also
364
+ // checks session.id; passing both via override is safe).
365
+ sessionId: req && req.session && (req.session.sid || req.session.id),
366
+ }),
367
+ metadata: {
368
+ status: info.status,
369
+ code: info.code,
370
+ method: req && req.method,
371
+ url: req && req.url,
372
+ requestId: (req && req.id) || (req && req.requestId),
373
+ stack: info.status >= 500 ? info.stack : null,
374
+ },
375
+ reason: info.message,
376
+ requestId: (req && req.id) || (req && req.requestId) || null,
377
+ });
378
+ } catch (_e) { /* audit best-effort */ }
379
+ }
380
+
381
+ if (res && res.writableEnded) return;
382
+
383
+ var ctx = {
384
+ req: req,
385
+ requestId: req && req.id,
386
+ };
387
+
388
+ if (_wantsJson(req, defaultFormat)) {
389
+ var errorObj = {
390
+ code: info.code || (info.status >= 500 ? "internal_error" : "error"),
391
+ message: info.publicMessage,
392
+ };
393
+ if (info.path) errorObj.path = info.path;
394
+ if (mode === "dev" && info.stack && showStack && info.status >= 500) {
395
+ errorObj.stack = info.stack;
396
+ }
397
+ _writeResponse(res, info.status, "application/json; charset=utf-8",
398
+ JSON.stringify({ error: errorObj }));
399
+ return;
400
+ }
401
+
402
+ var html = (mode === "dev")
403
+ ? _renderDevHtml(info, {
404
+ brand: brand,
405
+ showStack: showStack,
406
+ showRequestInfo: showRequestInfo,
407
+ showEnvVars: showEnvVars,
408
+ }, ctx)
409
+ : _renderProdHtml(info, { brand: brand, contact: contact });
410
+ _writeResponse(res, info.status, "text/html; charset=utf-8", html);
411
+ }
412
+
413
+ handler.mode = mode;
414
+ return handler;
415
+ }
416
+
417
+ module.exports = {
418
+ create: create,
419
+ STATUS_REASONS: STATUS_REASONS,
420
+ };