@blamejs/core 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +230 -0
- package/LICENSE +201 -0
- package/LTS-CALENDAR.md +29 -0
- package/MIGRATING.md +7 -0
- package/NOTICE +59 -0
- package/README.md +100 -0
- package/bin/blamejs.js +13 -0
- package/index.js +253 -0
- package/lib/api-key.js +705 -0
- package/lib/api-snapshot.js +335 -0
- package/lib/app-shutdown.js +381 -0
- package/lib/app.js +364 -0
- package/lib/atomic-file.js +525 -0
- package/lib/audit-chain.js +168 -0
- package/lib/audit-sign.js +319 -0
- package/lib/audit-tools.js +682 -0
- package/lib/audit.js +753 -0
- package/lib/auth/jwt.js +280 -0
- package/lib/auth/oauth.js +691 -0
- package/lib/auth/passkey.js +185 -0
- package/lib/auth/password.js +139 -0
- package/lib/auth/totp.js +17 -0
- package/lib/auth-header.js +81 -0
- package/lib/backup/bundle.js +219 -0
- package/lib/backup/crypto.js +174 -0
- package/lib/backup/index.js +490 -0
- package/lib/backup/manifest.js +275 -0
- package/lib/bundler.js +295 -0
- package/lib/cache.js +819 -0
- package/lib/chain-writer.js +234 -0
- package/lib/cli-helpers.js +201 -0
- package/lib/cli.js +1377 -0
- package/lib/cluster-provider-db.js +245 -0
- package/lib/cluster-storage.js +166 -0
- package/lib/cluster.js +691 -0
- package/lib/consent.js +222 -0
- package/lib/constants.js +186 -0
- package/lib/cookies.js +293 -0
- package/lib/credential-hash.js +303 -0
- package/lib/crypto-field.js +159 -0
- package/lib/crypto.js +250 -0
- package/lib/db-query.js +297 -0
- package/lib/db-schema.js +250 -0
- package/lib/db.js +1054 -0
- package/lib/deprecate.js +226 -0
- package/lib/dev.js +324 -0
- package/lib/error-page.js +424 -0
- package/lib/events.js +135 -0
- package/lib/external-db.js +422 -0
- package/lib/forms.js +378 -0
- package/lib/framework-error.js +189 -0
- package/lib/framework-schema.js +604 -0
- package/lib/handlers.js +350 -0
- package/lib/html-balance.js +227 -0
- package/lib/http-client.js +615 -0
- package/lib/i18n.js +780 -0
- package/lib/jobs.js +181 -0
- package/lib/lazy-require.js +48 -0
- package/lib/log-stream-local.js +137 -0
- package/lib/log-stream-webhook.js +170 -0
- package/lib/log-stream.js +211 -0
- package/lib/log.js +355 -0
- package/lib/mail-bounce.js +507 -0
- package/lib/mail.js +701 -0
- package/lib/metrics.js +647 -0
- package/lib/middleware/api-encrypt.js +553 -0
- package/lib/middleware/attach-user.js +156 -0
- package/lib/middleware/body-parser.js +883 -0
- package/lib/middleware/bot-guard.js +148 -0
- package/lib/middleware/compression.js +436 -0
- package/lib/middleware/cors.js +236 -0
- package/lib/middleware/csp-nonce.js +332 -0
- package/lib/middleware/csrf-protect.js +275 -0
- package/lib/middleware/error-handler.js +46 -0
- package/lib/middleware/health.js +358 -0
- package/lib/middleware/index.js +52 -0
- package/lib/middleware/rate-limit.js +319 -0
- package/lib/middleware/request-id.js +53 -0
- package/lib/middleware/require-auth.js +95 -0
- package/lib/middleware/security-headers.js +91 -0
- package/lib/migrations.js +353 -0
- package/lib/mtls-ca.js +333 -0
- package/lib/mtls-engine-default.js +285 -0
- package/lib/nonce-store.js +177 -0
- package/lib/notify.js +643 -0
- package/lib/ntp-check.js +178 -0
- package/lib/object-store/azure-blob.js +467 -0
- package/lib/object-store/gcs.js +469 -0
- package/lib/object-store/http-put.js +153 -0
- package/lib/object-store/index.js +140 -0
- package/lib/object-store/local.js +163 -0
- package/lib/object-store/retry.js +15 -0
- package/lib/object-store/sigv4.js +535 -0
- package/lib/observability.js +114 -0
- package/lib/pagination.js +371 -0
- package/lib/parsers/index.js +64 -0
- package/lib/parsers/safe-csv.js +224 -0
- package/lib/parsers/safe-env.js +614 -0
- package/lib/parsers/safe-toml.js +745 -0
- package/lib/parsers/safe-xml.js +379 -0
- package/lib/parsers/safe-yaml.js +977 -0
- package/lib/permissions.js +430 -0
- package/lib/pqc-agent.js +85 -0
- package/lib/pqc-gate.js +266 -0
- package/lib/protocol-dispatcher.js +144 -0
- package/lib/queue-local.js +327 -0
- package/lib/queue.js +430 -0
- package/lib/redact.js +192 -0
- package/lib/render.js +193 -0
- package/lib/request-helpers.js +178 -0
- package/lib/restore-bundle.js +239 -0
- package/lib/restore-rollback.js +254 -0
- package/lib/restore.js +301 -0
- package/lib/retry.js +329 -0
- package/lib/router.js +437 -0
- package/lib/safe-async.js +520 -0
- package/lib/safe-buffer.js +162 -0
- package/lib/safe-json.js +532 -0
- package/lib/safe-schema.js +1176 -0
- package/lib/safe-sql.js +157 -0
- package/lib/safe-url.js +109 -0
- package/lib/scheduler.js +680 -0
- package/lib/seeders.js +622 -0
- package/lib/session.js +304 -0
- package/lib/slug.js +243 -0
- package/lib/static.js +268 -0
- package/lib/storage.js +470 -0
- package/lib/subject.js +281 -0
- package/lib/template.js +781 -0
- package/lib/testing.js +621 -0
- package/lib/totp.js +285 -0
- package/lib/tracing.js +484 -0
- package/lib/validate-opts.js +56 -0
- package/lib/vault/index.js +299 -0
- package/lib/vault/passphrase-ops.js +311 -0
- package/lib/vault/passphrase-source.js +198 -0
- package/lib/vault/rotate.js +761 -0
- package/lib/vault/wrap.js +289 -0
- package/lib/vendor/MANIFEST.json +84 -0
- package/lib/vendor/argon2/argon2.cjs +466 -0
- package/lib/vendor/argon2/argon2.d.cts +62 -0
- package/lib/vendor/argon2/package.json +1 -0
- package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
- package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
- package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
- package/lib/vendor/noble-ciphers.cjs +9 -0
- package/lib/vendor/pki.cjs +181 -0
- package/lib/vendor/simplewebauthn-server.cjs +328 -0
- package/lib/webhook.js +632 -0
- package/lib/websocket-channels.js +413 -0
- package/lib/websocket.js +833 -0
- package/package.json +39 -0
|
@@ -0,0 +1,424 @@
|
|
|
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 audit = lazyRequire(function () { return require("./audit"); });
|
|
43
|
+
|
|
44
|
+
// Status code → default short reason. Used when the error doesn't carry
|
|
45
|
+
// its own message (e.g. a generic Error thrown from a route).
|
|
46
|
+
var STATUS_REASONS = {
|
|
47
|
+
400: "Bad Request",
|
|
48
|
+
401: "Unauthorized",
|
|
49
|
+
403: "Forbidden",
|
|
50
|
+
404: "Not Found",
|
|
51
|
+
405: "Method Not Allowed",
|
|
52
|
+
409: "Conflict",
|
|
53
|
+
413: "Payload Too Large",
|
|
54
|
+
415: "Unsupported Media Type",
|
|
55
|
+
422: "Unprocessable Content",
|
|
56
|
+
429: "Too Many Requests",
|
|
57
|
+
500: "Internal Server Error",
|
|
58
|
+
502: "Bad Gateway",
|
|
59
|
+
503: "Service Unavailable",
|
|
60
|
+
504: "Gateway Timeout",
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// Map common framework error classes → HTTP status. Operators who
|
|
64
|
+
// throw their own AppError-like classes set isAppError + statusCode
|
|
65
|
+
// and bypass this map entirely.
|
|
66
|
+
function _classify(err) {
|
|
67
|
+
if (!err || typeof err !== "object") {
|
|
68
|
+
return { status: 500, code: "INTERNAL_ERROR", message: "Internal Server Error", classified: false };
|
|
69
|
+
}
|
|
70
|
+
// Apps that follow the standard convention: { isAppError, statusCode, code, message }
|
|
71
|
+
if (err.isAppError) {
|
|
72
|
+
return {
|
|
73
|
+
status: err.statusCode || 500,
|
|
74
|
+
code: err.code || "APP_ERROR",
|
|
75
|
+
message: err.message || STATUS_REASONS[err.statusCode || 500] || "Error",
|
|
76
|
+
classified: true,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
// Framework error subclasses we know map to specific HTTP statuses.
|
|
80
|
+
if (err.isAuthError) {
|
|
81
|
+
return { status: 401, code: err.code || "AUTH_FAILED", message: err.message || "Unauthorized", classified: true };
|
|
82
|
+
}
|
|
83
|
+
if (err.code === "VALIDATION_ERROR" || err.name === "ValidationError") {
|
|
84
|
+
return { status: 400, code: err.code || "VALIDATION_ERROR", message: err.message || "Bad Request", classified: true };
|
|
85
|
+
}
|
|
86
|
+
if (err.isSafeJsonError) {
|
|
87
|
+
return { status: 400, code: err.code || "json/invalid", message: err.message || "Bad Request", path: err.path || null, classified: true };
|
|
88
|
+
}
|
|
89
|
+
// Permanent framework errors that map cleanly to 4xx
|
|
90
|
+
if ((err.isStorageError || err.isQueueError || err.isExternalDbError) && err.permanent) {
|
|
91
|
+
return { status: 400, code: err.code || "ERROR", message: err.message || "Bad Request", classified: true };
|
|
92
|
+
}
|
|
93
|
+
if (typeof err.statusCode === "number") {
|
|
94
|
+
return {
|
|
95
|
+
status: err.statusCode,
|
|
96
|
+
code: err.code || "ERROR",
|
|
97
|
+
message: err.message || STATUS_REASONS[err.statusCode] || "Error",
|
|
98
|
+
classified: true,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return { status: 500, code: err.code || "INTERNAL_ERROR", message: err.message || "Internal Server Error", classified: false };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function _wantsJson(req, defaultFormat) {
|
|
105
|
+
if (defaultFormat === "json") return true;
|
|
106
|
+
if (defaultFormat === "html") return false;
|
|
107
|
+
var accept = (req && req.headers && req.headers.accept) || "";
|
|
108
|
+
// Default to JSON only when Accept makes it explicit. Browsers send
|
|
109
|
+
// text/html, programmatic clients usually send application/json.
|
|
110
|
+
if (accept.indexOf("application/json") !== -1) return true;
|
|
111
|
+
if (accept.indexOf("text/html") !== -1) return false;
|
|
112
|
+
// Heuristic: APIs typically don't ask for html; treat empty Accept
|
|
113
|
+
// on non-GET as JSON, GET as HTML.
|
|
114
|
+
return req && req.method && req.method.toUpperCase() !== "GET";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function _esc(s) {
|
|
118
|
+
if (s === undefined || s === null) return "";
|
|
119
|
+
return String(s)
|
|
120
|
+
.replace(/&/g, "&")
|
|
121
|
+
.replace(/</g, "<")
|
|
122
|
+
.replace(/>/g, ">")
|
|
123
|
+
.replace(/"/g, """)
|
|
124
|
+
.replace(/'/g, "'");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function _redactHeaders(headers) {
|
|
128
|
+
if (!headers || typeof headers !== "object") return {};
|
|
129
|
+
var out = {};
|
|
130
|
+
var keys = Object.keys(headers);
|
|
131
|
+
for (var i = 0; i < keys.length; i++) {
|
|
132
|
+
var k = keys[i];
|
|
133
|
+
var lk = k.toLowerCase();
|
|
134
|
+
// Strip auth-bearing headers from the dev page so opening a stack
|
|
135
|
+
// trace doesn't put a session cookie or bearer token in front of
|
|
136
|
+
// anyone who can see the screen.
|
|
137
|
+
if (lk === "cookie" || lk === "authorization" ||
|
|
138
|
+
lk === "x-api-key" || lk === "x-csrf-token" ||
|
|
139
|
+
lk.indexOf("token") !== -1) {
|
|
140
|
+
out[k] = "[REDACTED]";
|
|
141
|
+
} else {
|
|
142
|
+
out[k] = headers[k];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function _renderProdHtml(info, opts) {
|
|
149
|
+
var brand = opts.brand ? _esc(opts.brand) : "blamejs";
|
|
150
|
+
var contact = opts.contact ? _esc(opts.contact) : null;
|
|
151
|
+
return [
|
|
152
|
+
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",
|
|
153
|
+
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
|
|
154
|
+
"<title>", _esc(STATUS_REASONS[info.status] || "Error"), " — ", brand, "</title>",
|
|
155
|
+
"<style>",
|
|
156
|
+
"html,body{height:100%;margin:0;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0d1117;color:#c9d1d9}",
|
|
157
|
+
".wrap{display:flex;align-items:center;justify-content:center;min-height:100%;padding:2rem}",
|
|
158
|
+
".card{max-width:520px;text-align:center;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:48px 32px}",
|
|
159
|
+
".status{font-size:64px;font-weight:700;color:#58a6ff;margin:0;line-height:1}",
|
|
160
|
+
".title{font-size:18px;font-weight:600;color:#e6edf3;margin:18px 0 6px}",
|
|
161
|
+
".msg{font-size:14px;color:#8b949e;margin:0 0 24px;line-height:1.5}",
|
|
162
|
+
".contact{font-size:13px;color:#6e7681}",
|
|
163
|
+
".brand{font-size:12px;color:#484f58;margin-top:32px;letter-spacing:.05em;text-transform:uppercase}",
|
|
164
|
+
"a{color:#58a6ff;text-decoration:none}a:hover{text-decoration:underline}",
|
|
165
|
+
"</style></head><body><div class=\"wrap\"><div class=\"card\">",
|
|
166
|
+
"<p class=\"status\">", String(info.status), "</p>",
|
|
167
|
+
"<p class=\"title\">", _esc(STATUS_REASONS[info.status] || "Error"), "</p>",
|
|
168
|
+
"<p class=\"msg\">", _esc(info.publicMessage), "</p>",
|
|
169
|
+
contact ? "<p class=\"contact\">Contact <a href=\"mailto:" + contact + "\">" + contact + "</a> if this persists.</p>" : "",
|
|
170
|
+
"<p class=\"brand\">", brand, "</p>",
|
|
171
|
+
"</div></div></body></html>",
|
|
172
|
+
].join("");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function _renderDevHtml(info, opts, ctx) {
|
|
176
|
+
var brand = opts.brand ? _esc(opts.brand) : "blamejs";
|
|
177
|
+
var stackHtml = "";
|
|
178
|
+
if (opts.showStack && info.stack) {
|
|
179
|
+
stackHtml = "<pre class=\"stack\">" + _esc(info.stack) + "</pre>";
|
|
180
|
+
}
|
|
181
|
+
var requestHtml = "";
|
|
182
|
+
if (opts.showRequestInfo && ctx && ctx.req) {
|
|
183
|
+
var req = ctx.req;
|
|
184
|
+
var headers = _redactHeaders(req.headers);
|
|
185
|
+
var headerRows = Object.keys(headers).map(function (k) {
|
|
186
|
+
return "<tr><th>" + _esc(k) + "</th><td>" + _esc(headers[k]) + "</td></tr>";
|
|
187
|
+
}).join("");
|
|
188
|
+
requestHtml = [
|
|
189
|
+
"<section><h2>Request</h2>",
|
|
190
|
+
"<table class=\"kv\">",
|
|
191
|
+
"<tr><th>method</th><td>", _esc(req.method || ""), "</td></tr>",
|
|
192
|
+
"<tr><th>url</th><td>", _esc(req.url || ""), "</td></tr>",
|
|
193
|
+
ctx.requestId ? ("<tr><th>requestId</th><td>" + _esc(ctx.requestId) + "</td></tr>") : "",
|
|
194
|
+
"</table>",
|
|
195
|
+
headerRows ? ("<h3>Headers</h3><table class=\"kv\">" + headerRows + "</table>") : "",
|
|
196
|
+
"</section>",
|
|
197
|
+
].join("");
|
|
198
|
+
}
|
|
199
|
+
var envHtml = "";
|
|
200
|
+
if (opts.showEnvVars) {
|
|
201
|
+
var envKeys = Object.keys(process.env).filter(function (k) {
|
|
202
|
+
// Even with showEnvVars=true, keep secret-shaped keys redacted —
|
|
203
|
+
// turning the dev page on shouldn't leak production credentials
|
|
204
|
+
// when an operator forgets to switch modes.
|
|
205
|
+
return !/SECRET|TOKEN|KEY|PASS|CRED/i.test(k);
|
|
206
|
+
}).sort();
|
|
207
|
+
var envRows = envKeys.map(function (k) {
|
|
208
|
+
return "<tr><th>" + _esc(k) + "</th><td>" + _esc(process.env[k]) + "</td></tr>";
|
|
209
|
+
}).join("");
|
|
210
|
+
envHtml = "<section><h2>Environment</h2><table class=\"kv\">" + envRows + "</table></section>";
|
|
211
|
+
}
|
|
212
|
+
return [
|
|
213
|
+
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">",
|
|
214
|
+
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
|
|
215
|
+
"<title>", String(info.status), " ", _esc(STATUS_REASONS[info.status] || "Error"),
|
|
216
|
+
" — ", brand, " (dev)</title>",
|
|
217
|
+
"<style>",
|
|
218
|
+
"*{box-sizing:border-box}",
|
|
219
|
+
"body{margin:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#0d1117;color:#c9d1d9;font-size:13px;line-height:1.55}",
|
|
220
|
+
"header{background:#21262d;padding:24px 32px;border-bottom:3px solid #f85149}",
|
|
221
|
+
"header .status{display:inline-block;background:#f85149;color:#fff;padding:4px 10px;border-radius:6px;font-weight:700;margin-right:12px}",
|
|
222
|
+
"header h1{display:inline;font-size:18px;color:#e6edf3;font-weight:600}",
|
|
223
|
+
"header .err-code{margin-top:8px;font-size:12px;color:#8b949e}",
|
|
224
|
+
"main{padding:24px 32px;max-width:1200px}",
|
|
225
|
+
"section{margin-bottom:32px}",
|
|
226
|
+
"h2{font-size:13px;color:#8b949e;text-transform:uppercase;letter-spacing:.08em;margin:0 0 12px;font-weight:600}",
|
|
227
|
+
"h3{font-size:12px;color:#8b949e;text-transform:uppercase;letter-spacing:.05em;margin:18px 0 8px;font-weight:600}",
|
|
228
|
+
".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}",
|
|
229
|
+
"table.kv{width:100%;border-collapse:collapse;background:#161b22;border:1px solid #30363d;border-radius:8px;overflow:hidden}",
|
|
230
|
+
"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}",
|
|
231
|
+
"table.kv td{padding:8px 12px;color:#c9d1d9;word-break:break-word;border-bottom:1px solid #21262d}",
|
|
232
|
+
"table.kv tr:last-child th,table.kv tr:last-child td{border-bottom:none}",
|
|
233
|
+
"footer{padding:16px 32px;color:#484f58;font-size:11px;letter-spacing:.05em;text-transform:uppercase;border-top:1px solid #21262d}",
|
|
234
|
+
"</style></head><body>",
|
|
235
|
+
"<header>",
|
|
236
|
+
"<span class=\"status\">", String(info.status), "</span>",
|
|
237
|
+
"<h1>", _esc(STATUS_REASONS[info.status] || "Error"), " — ", _esc(info.devMessage), "</h1>",
|
|
238
|
+
info.code ? ("<div class=\"err-code\">code: " + _esc(info.code) + "</div>") : "",
|
|
239
|
+
"</header>",
|
|
240
|
+
"<main>",
|
|
241
|
+
stackHtml ? ("<section><h2>Stack</h2>" + stackHtml + "</section>") : "",
|
|
242
|
+
requestHtml,
|
|
243
|
+
envHtml,
|
|
244
|
+
"</main>",
|
|
245
|
+
"<footer>", brand, " · dev mode · stack/headers redacted in prod</footer>",
|
|
246
|
+
"</body></html>",
|
|
247
|
+
].join("");
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function _writeResponse(res, status, contentType, body) {
|
|
251
|
+
if (res.writableEnded) return;
|
|
252
|
+
try {
|
|
253
|
+
var headers = { "Content-Type": contentType, "Cache-Control": "no-store" };
|
|
254
|
+
// Prefer writeHead so the status survives under both real Node
|
|
255
|
+
// ServerResponse and lighter mock objects that only track status
|
|
256
|
+
// via writeHead's first arg. setHeader fallback covers shims that
|
|
257
|
+
// expose only that surface.
|
|
258
|
+
if (typeof res.writeHead === "function") {
|
|
259
|
+
res.writeHead(status, headers);
|
|
260
|
+
} else {
|
|
261
|
+
res.statusCode = status;
|
|
262
|
+
if (typeof res.setHeader === "function") {
|
|
263
|
+
res.setHeader("Content-Type", contentType);
|
|
264
|
+
res.setHeader("Cache-Control", "no-store");
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
res.end(body);
|
|
268
|
+
} catch (_e) {
|
|
269
|
+
// Last-resort plain text. If even this fails, the connection is
|
|
270
|
+
// already gone; nothing to do.
|
|
271
|
+
try { res.end("Internal Server Error"); } catch (_e2) { /* socket gone */ }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function create(opts) {
|
|
276
|
+
opts = opts || {};
|
|
277
|
+
var modeOpt = opts.mode;
|
|
278
|
+
var mode;
|
|
279
|
+
if (modeOpt === "dev" || modeOpt === "prod") {
|
|
280
|
+
mode = modeOpt;
|
|
281
|
+
} else {
|
|
282
|
+
var nodeEnv = process.env.NODE_ENV;
|
|
283
|
+
mode = (nodeEnv === "production") ? "prod" : "dev";
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
var auditOn = opts.audit !== false;
|
|
287
|
+
var auditAction = typeof opts.auditAction === "string" && opts.auditAction.length > 0
|
|
288
|
+
? opts.auditAction
|
|
289
|
+
: "request.error";
|
|
290
|
+
// defaultFormat:
|
|
291
|
+
// "auto" (default) — negotiate via Accept header
|
|
292
|
+
// "json" — always JSON (API-style middleware default)
|
|
293
|
+
// "html" — always HTML (page-style middleware default)
|
|
294
|
+
var defaultFormat = opts.defaultFormat;
|
|
295
|
+
if (defaultFormat !== undefined &&
|
|
296
|
+
defaultFormat !== "auto" && defaultFormat !== "json" && defaultFormat !== "html") {
|
|
297
|
+
throw new Error("errors-page: opts.defaultFormat must be 'auto', 'json', or 'html'");
|
|
298
|
+
}
|
|
299
|
+
var log = opts.log || null; // structured logger if supplied
|
|
300
|
+
var brand = opts.brand || null;
|
|
301
|
+
var contact = opts.contact || null;
|
|
302
|
+
var showStack = mode === "dev" && opts.showStack !== false;
|
|
303
|
+
var showRequestInfo = mode === "dev" && opts.showRequestInfo !== false;
|
|
304
|
+
var showEnvVars = mode === "dev" && opts.showEnvVars === true;
|
|
305
|
+
var onErrorHook = typeof opts.onError === "function" ? opts.onError : null;
|
|
306
|
+
|
|
307
|
+
function _log(level, message, fields) {
|
|
308
|
+
if (log && typeof log[level] === "function") {
|
|
309
|
+
try { log[level](message, fields); }
|
|
310
|
+
catch (_e) { /* logger best-effort */ }
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
// Fallback: framework console with status-aware severity
|
|
314
|
+
var line = "[blamejs:errors-page] " + message + " " + JSON.stringify(fields || {});
|
|
315
|
+
if (level === "error" || level === "fatal" || level === "warn") {
|
|
316
|
+
console.error(line);
|
|
317
|
+
} else {
|
|
318
|
+
console.log(line);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function handler(err, req, res) {
|
|
323
|
+
var info = _classify(err);
|
|
324
|
+
info.stack = (err && err.stack) ? err.stack : null;
|
|
325
|
+
// The message we show to the client depends on whether we recognize
|
|
326
|
+
// the error class. Generic 500s never leak the original message.
|
|
327
|
+
info.publicMessage = (info.status >= 500 && !info.classified)
|
|
328
|
+
? (STATUS_REASONS[info.status] || "Internal Server Error")
|
|
329
|
+
: info.message;
|
|
330
|
+
info.devMessage = info.message;
|
|
331
|
+
|
|
332
|
+
// Custom hook: operator can take over the response entirely.
|
|
333
|
+
if (onErrorHook) {
|
|
334
|
+
var handled = false;
|
|
335
|
+
try { handled = !!onErrorHook(err, req, res, info); }
|
|
336
|
+
catch (e) {
|
|
337
|
+
_log("error", "errors-page onError hook threw", { error: (e && e.message) || String(e) });
|
|
338
|
+
}
|
|
339
|
+
if (handled || (res && res.writableEnded)) return;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Logging: 5xx always with stack; 4xx as warn without stack noise
|
|
343
|
+
var logFields = {
|
|
344
|
+
status: info.status,
|
|
345
|
+
code: info.code,
|
|
346
|
+
method: req && req.method,
|
|
347
|
+
url: req && req.url,
|
|
348
|
+
requestId: req && req.id,
|
|
349
|
+
};
|
|
350
|
+
if (info.status >= 500) {
|
|
351
|
+
logFields.stack = info.stack || String(err);
|
|
352
|
+
_log("error", "unhandled error", logFields);
|
|
353
|
+
} else {
|
|
354
|
+
_log("warn", "request error", logFields);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Audit every error. Best-effort — never let an audit-write failure
|
|
358
|
+
// mask the original error. Outcome differentiates 5xx (failure) vs
|
|
359
|
+
// 4xx (denied) so consumers can filter without re-classifying status.
|
|
360
|
+
if (auditOn) {
|
|
361
|
+
try {
|
|
362
|
+
audit().emit({
|
|
363
|
+
action: auditAction,
|
|
364
|
+
outcome: info.status >= 500 ? "failure" : "denied",
|
|
365
|
+
actor: {
|
|
366
|
+
ip: req && req.headers && req.headers["x-forwarded-for"] ||
|
|
367
|
+
(req && req.socket && req.socket.remoteAddress),
|
|
368
|
+
userAgent: req && req.headers && req.headers["user-agent"],
|
|
369
|
+
sessionId: req && req.session && req.session.sid,
|
|
370
|
+
},
|
|
371
|
+
metadata: {
|
|
372
|
+
status: info.status,
|
|
373
|
+
code: info.code,
|
|
374
|
+
method: req && req.method,
|
|
375
|
+
url: req && req.url,
|
|
376
|
+
requestId: (req && req.id) || (req && req.requestId),
|
|
377
|
+
stack: info.status >= 500 ? info.stack : null,
|
|
378
|
+
},
|
|
379
|
+
reason: info.message,
|
|
380
|
+
requestId: (req && req.id) || (req && req.requestId) || null,
|
|
381
|
+
});
|
|
382
|
+
} catch (_e) { /* audit best-effort */ }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (res && res.writableEnded) return;
|
|
386
|
+
|
|
387
|
+
var ctx = {
|
|
388
|
+
req: req,
|
|
389
|
+
requestId: req && req.id,
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
if (_wantsJson(req, defaultFormat)) {
|
|
393
|
+
var errorObj = {
|
|
394
|
+
code: info.code || (info.status >= 500 ? "internal_error" : "error"),
|
|
395
|
+
message: info.publicMessage,
|
|
396
|
+
};
|
|
397
|
+
if (info.path) errorObj.path = info.path;
|
|
398
|
+
if (mode === "dev" && info.stack && showStack && info.status >= 500) {
|
|
399
|
+
errorObj.stack = info.stack;
|
|
400
|
+
}
|
|
401
|
+
_writeResponse(res, info.status, "application/json; charset=utf-8",
|
|
402
|
+
JSON.stringify({ error: errorObj }));
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
var html = (mode === "dev")
|
|
407
|
+
? _renderDevHtml(info, {
|
|
408
|
+
brand: brand,
|
|
409
|
+
showStack: showStack,
|
|
410
|
+
showRequestInfo: showRequestInfo,
|
|
411
|
+
showEnvVars: showEnvVars,
|
|
412
|
+
}, ctx)
|
|
413
|
+
: _renderProdHtml(info, { brand: brand, contact: contact });
|
|
414
|
+
_writeResponse(res, info.status, "text/html; charset=utf-8", html);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
handler.mode = mode;
|
|
418
|
+
return handler;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
module.exports = {
|
|
422
|
+
create: create,
|
|
423
|
+
STATUS_REASONS: STATUS_REASONS,
|
|
424
|
+
};
|
package/lib/events.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* events — framework-wide cross-cutting signal bus.
|
|
4
|
+
*
|
|
5
|
+
* A thin wrapper around Node's EventEmitter, exposed as `b.events`,
|
|
6
|
+
* dedicated to framework-emitted breach-detection and integrity signals.
|
|
7
|
+
* Operators wire listeners to PagerDuty / Opsgenie / a Slack webhook /
|
|
8
|
+
* a notification queue and the framework fires them on the specific
|
|
9
|
+
* high-signal conditions documented in `EVENTS` below.
|
|
10
|
+
*
|
|
11
|
+
* Why a separate emitter (not Node's built-in EventEmitter directly):
|
|
12
|
+
* - One bus the framework controls — operators don't have to chase
|
|
13
|
+
* emit calls across modules to know what's available.
|
|
14
|
+
* - Best-effort emit semantics: a listener throwing must NOT break
|
|
15
|
+
* the framework's refuse-to-boot fail-fast. emit() catches and
|
|
16
|
+
* swallows listener errors.
|
|
17
|
+
* - Stable event names exported as constants — operators reference
|
|
18
|
+
* b.events.EVENTS.AUDIT_CHAIN_BREAK rather than typing the string.
|
|
19
|
+
* - _resetForTest() clears listeners between tests without touching
|
|
20
|
+
* consumer state.
|
|
21
|
+
*
|
|
22
|
+
* Public API:
|
|
23
|
+
* b.events.on(name, fn) register listener
|
|
24
|
+
* b.events.off(name, fn) unregister listener
|
|
25
|
+
* b.events.once(name, fn) register single-fire listener
|
|
26
|
+
* b.events.emit(name, payload) fire (best-effort; listener
|
|
27
|
+
* errors logged + swallowed)
|
|
28
|
+
* b.events.listenerCount(name) diagnostic
|
|
29
|
+
* b.events.EVENTS stable name constants
|
|
30
|
+
*
|
|
31
|
+
* Example operator wiring (sync — synchronous I/O only inside the handler
|
|
32
|
+
* since process.exit may follow on certain framework signals):
|
|
33
|
+
*
|
|
34
|
+
* b.events.on(b.events.EVENTS.AUDIT_CHAIN_BREAK, function (info) {
|
|
35
|
+
* fs.writeFileSync("/var/run/blamejs-chain-break.flag",
|
|
36
|
+
* JSON.stringify({ at: Date.now(), info: info }));
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* For async fan-out (PagerDuty webhook, etc.) the listener should hand
|
|
40
|
+
* off to a queue — synchronous I/O in the listener is safe but blocking
|
|
41
|
+
* network calls would delay the framework's fail-fast path on signals
|
|
42
|
+
* that lead to process.exit.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
var nodeEvents = require("node:events");
|
|
46
|
+
var { boot } = require("./log");
|
|
47
|
+
|
|
48
|
+
var log = boot("events");
|
|
49
|
+
|
|
50
|
+
// Stable event names. Adding a new emit point means adding it here so
|
|
51
|
+
// operators discover it via tab-completion / api-snapshot diff.
|
|
52
|
+
var EVENTS = Object.freeze({
|
|
53
|
+
// Audit hash chain failed verification — verify() returned ok=false.
|
|
54
|
+
// Framework refuses to boot on this signal but emits FIRST so the
|
|
55
|
+
// operator's listener gets a chance to log/page before process.exit.
|
|
56
|
+
AUDIT_CHAIN_BREAK: "audit:chain-break",
|
|
57
|
+
// Audit checkpoint signature failed verification (forgery attempt or
|
|
58
|
+
// key rotation without history retention). Same fail-fast pattern.
|
|
59
|
+
AUDIT_CHECKPOINT_BREAK: "audit:checkpoint-break",
|
|
60
|
+
// db.audit.tip sidecar shows a higher monotonic counter than the
|
|
61
|
+
// current audit_log MAX — DB was rolled back to an older snapshot.
|
|
62
|
+
AUDIT_ROLLBACK_DETECTED: "audit:rollback-detected",
|
|
63
|
+
// NTP boot-check found drift outside the configured threshold.
|
|
64
|
+
// Severity is "warning" (5min–1hr) or "fatal" (>=1hr); payload
|
|
65
|
+
// includes the actual drift in ms.
|
|
66
|
+
NTP_DRIFT: "audit:ntp-drift",
|
|
67
|
+
// api-encrypt middleware rejected an inbound request: AEAD failure,
|
|
68
|
+
// stale timestamp, replay, or malformed envelope. Payload carries
|
|
69
|
+
// { reason, ip, path, ts } so operators can wire alerting on the
|
|
70
|
+
// shape of attempted attacks without exposing why-it-failed back
|
|
71
|
+
// to the requester.
|
|
72
|
+
API_ENCRYPT_FAILURE: "audit:api-encrypt-failure",
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
var _emitter = new nodeEvents.EventEmitter();
|
|
76
|
+
// Removing the default 10-listener cap on the framework bus — operators
|
|
77
|
+
// may wire more than ten listeners (notify, structured-log mirror, audit
|
|
78
|
+
// sidecar, file flag writer, etc.) and the warning isn't useful here.
|
|
79
|
+
_emitter.setMaxListeners(0);
|
|
80
|
+
|
|
81
|
+
function on(name, fn) {
|
|
82
|
+
_emitter.on(name, fn);
|
|
83
|
+
return _emitter;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function off(name, fn) {
|
|
87
|
+
_emitter.off(name, fn);
|
|
88
|
+
return _emitter;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function once(name, fn) {
|
|
92
|
+
_emitter.once(name, fn);
|
|
93
|
+
return _emitter;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Best-effort emit. A listener throwing must not propagate — framework
|
|
97
|
+
// callers (e.g. db.init's chain-verify FATAL path) emit immediately
|
|
98
|
+
// before process.exit and can't tolerate a listener crashing the exit
|
|
99
|
+
// path. We log+swallow per-listener errors so the rest of the listeners
|
|
100
|
+
// still fire.
|
|
101
|
+
function emit(name, payload) {
|
|
102
|
+
// rawListeners returns the wrapper functions including the auto-
|
|
103
|
+
// removing wrapper that once() registers. Calling the wrapper triggers
|
|
104
|
+
// its internal removeListener, so once() semantics work even though
|
|
105
|
+
// we don't go through _emitter.emit (which propagates listener throws
|
|
106
|
+
// and would defeat the best-effort contract).
|
|
107
|
+
var listeners = _emitter.rawListeners(name);
|
|
108
|
+
for (var i = 0; i < listeners.length; i++) {
|
|
109
|
+
try {
|
|
110
|
+
listeners[i](payload);
|
|
111
|
+
} catch (e) {
|
|
112
|
+
log.error("listener for event '" + name + "' threw: " +
|
|
113
|
+
((e && e.message) || String(e)));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return listeners.length > 0;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function listenerCount(name) {
|
|
120
|
+
return _emitter.listenerCount(name);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function _resetForTest() {
|
|
124
|
+
_emitter.removeAllListeners();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = {
|
|
128
|
+
on: on,
|
|
129
|
+
off: off,
|
|
130
|
+
once: once,
|
|
131
|
+
emit: emit,
|
|
132
|
+
listenerCount: listenerCount,
|
|
133
|
+
EVENTS: EVENTS,
|
|
134
|
+
_resetForTest: _resetForTest,
|
|
135
|
+
};
|