@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,275 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* csrf-protect — middleware that issues CSRF tokens to safe-method
|
|
4
|
+
* requests AND rejects state-changing requests whose submitted token
|
|
5
|
+
* doesn't match.
|
|
6
|
+
*
|
|
7
|
+
* Mount AFTER attachUser (when using session-stored tokens) and AFTER
|
|
8
|
+
* bodyParser (when reading the token from a form field). Safe methods
|
|
9
|
+
* (GET / HEAD / OPTIONS) pass through; the gate fires on POST / PUT /
|
|
10
|
+
* DELETE / PATCH (configurable via opts.methods).
|
|
11
|
+
*
|
|
12
|
+
* Token storage — pick ONE:
|
|
13
|
+
*
|
|
14
|
+
* A. Cookie-stored ("double-submit cookie", default)
|
|
15
|
+
* opts.cookie = true | { name, sameSite, secure, path, httpOnly }
|
|
16
|
+
*
|
|
17
|
+
* The middleware reads the token from the configured cookie. On
|
|
18
|
+
* safe-method requests with no token cookie, it generates one and
|
|
19
|
+
* sets the cookie on the response. The same value is exposed on
|
|
20
|
+
* `req.csrfToken` for templates to render into a hidden form field.
|
|
21
|
+
* State-changing requests verify the submitted token matches the
|
|
22
|
+
* cookie value. SameSite=Lax (default) blocks cross-site form
|
|
23
|
+
* POSTs from carrying the cookie.
|
|
24
|
+
*
|
|
25
|
+
* httpOnly defaults to FALSE — JavaScript needs to read it for AJAX
|
|
26
|
+
* requests. Operators relying solely on server-rendered forms can
|
|
27
|
+
* flip it to true.
|
|
28
|
+
*
|
|
29
|
+
* B. Operator-supplied tokenLookup (session-stored, etc.)
|
|
30
|
+
* opts.tokenLookup = (req) => string|null
|
|
31
|
+
*
|
|
32
|
+
* The middleware calls tokenLookup(req) to fetch the expected
|
|
33
|
+
* token. Use this when CSRF tokens live in your session store
|
|
34
|
+
* (e.g. req.session.data.csrfToken). Issuance + req.csrfToken
|
|
35
|
+
* exposure are the operator's responsibility in this mode.
|
|
36
|
+
*
|
|
37
|
+
* If neither is supplied, the middleware throws at create() — Tier A
|
|
38
|
+
* config-time validation, no silent passthrough.
|
|
39
|
+
*
|
|
40
|
+
* Submitted-token sources tried in order on state-changing requests:
|
|
41
|
+
* 1. Header `X-CSRF-Token` (or opts.headerName)
|
|
42
|
+
* 2. Body field `_csrf` (or opts.fieldName) — requires bodyParser
|
|
43
|
+
* mounted before csrfProtect
|
|
44
|
+
*
|
|
45
|
+
* On mismatch:
|
|
46
|
+
* - Audit emit (auth.csrf.denied) with method + path + IP + reason
|
|
47
|
+
* - 403 application/json: { error: "CSRF token mismatch." }
|
|
48
|
+
* - next() NOT called
|
|
49
|
+
*
|
|
50
|
+
* Full options:
|
|
51
|
+
* {
|
|
52
|
+
* cookie: true | { EITHER this...
|
|
53
|
+
* name: "csrf",
|
|
54
|
+
* sameSite: "Lax" | "Strict" | "None",
|
|
55
|
+
* secure: auto-detected from request scheme,
|
|
56
|
+
* path: "/",
|
|
57
|
+
* httpOnly: false,
|
|
58
|
+
* },
|
|
59
|
+
* tokenLookup: (req) => string|null ...OR this
|
|
60
|
+
*
|
|
61
|
+
* fieldName: "_csrf" form-body field name
|
|
62
|
+
* headerName: "X-CSRF-Token" header name
|
|
63
|
+
* methods: ["POST", "PUT", "DELETE", "PATCH"]
|
|
64
|
+
* audit: true
|
|
65
|
+
* }
|
|
66
|
+
*/
|
|
67
|
+
var lazyRequire = require("../lazy-require");
|
|
68
|
+
var forms = require("../forms");
|
|
69
|
+
var validateOpts = require("../validate-opts");
|
|
70
|
+
var audit = lazyRequire(function () { return require("../audit"); });
|
|
71
|
+
|
|
72
|
+
var DEFAULT_FIELD_NAME = "_csrf";
|
|
73
|
+
var DEFAULT_HEADER_NAME = "X-CSRF-Token";
|
|
74
|
+
var DEFAULT_METHODS = Object.freeze(["POST", "PUT", "DELETE", "PATCH"]);
|
|
75
|
+
var DEFAULT_COOKIE_NAME = "csrf";
|
|
76
|
+
|
|
77
|
+
function _parseCookieHeader(header) {
|
|
78
|
+
// Minimal cookie-header parser — RFC 6265 §5.2 form. Ignores attributes,
|
|
79
|
+
// just splits the name=value pairs. Keys that appear multiple times
|
|
80
|
+
// resolve to the FIRST occurrence (browsers send pairs left-to-right
|
|
81
|
+
// by registration order; the first is the most-specific path).
|
|
82
|
+
var out = {};
|
|
83
|
+
if (typeof header !== "string" || header.length === 0) return out;
|
|
84
|
+
var parts = header.split(/;\s*/);
|
|
85
|
+
for (var i = 0; i < parts.length; i++) {
|
|
86
|
+
var p = parts[i];
|
|
87
|
+
var eq = p.indexOf("=");
|
|
88
|
+
if (eq === -1) continue;
|
|
89
|
+
var k = p.slice(0, eq).trim();
|
|
90
|
+
if (k.length === 0 || Object.prototype.hasOwnProperty.call(out, k)) continue;
|
|
91
|
+
var v = p.slice(eq + 1).trim();
|
|
92
|
+
if (v.length >= 2 && v.charCodeAt(0) === 0x22 && v.charCodeAt(v.length - 1) === 0x22) {
|
|
93
|
+
v = v.slice(1, -1);
|
|
94
|
+
}
|
|
95
|
+
out[k] = v;
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function _isHttps(req) {
|
|
101
|
+
if (req && req.socket && req.socket.encrypted) return true;
|
|
102
|
+
var fwd = req && req.headers && req.headers["x-forwarded-proto"];
|
|
103
|
+
if (typeof fwd === "string" && fwd.length > 0) {
|
|
104
|
+
return fwd.split(",")[0].trim().toLowerCase() === "https";
|
|
105
|
+
}
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function _formatSetCookie(name, value, opts) {
|
|
110
|
+
var parts = [name + "=" + value];
|
|
111
|
+
parts.push("Path=" + (opts.path || "/"));
|
|
112
|
+
parts.push("SameSite=" + (opts.sameSite || "Lax"));
|
|
113
|
+
if (opts.httpOnly) parts.push("HttpOnly");
|
|
114
|
+
if (opts.secure) parts.push("Secure");
|
|
115
|
+
if (opts.maxAge != null) parts.push("Max-Age=" + opts.maxAge);
|
|
116
|
+
return parts.join("; ");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function _appendSetCookie(res, value) {
|
|
120
|
+
// Don't clobber other Set-Cookie headers the route may have already
|
|
121
|
+
// queued (login session cookie, etc.). Use res.appendHeader when
|
|
122
|
+
// available; else array-merge manually.
|
|
123
|
+
if (typeof res.appendHeader === "function") {
|
|
124
|
+
res.appendHeader("Set-Cookie", value);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
var existing = typeof res.getHeader === "function" ? res.getHeader("Set-Cookie") : undefined;
|
|
128
|
+
if (existing == null) {
|
|
129
|
+
res.setHeader("Set-Cookie", value);
|
|
130
|
+
} else if (Array.isArray(existing)) {
|
|
131
|
+
res.setHeader("Set-Cookie", existing.concat(value));
|
|
132
|
+
} else {
|
|
133
|
+
res.setHeader("Set-Cookie", [existing, value]);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// csrf-protect does NOT buffer or parse the request body itself.
|
|
138
|
+
// Operators who use form-urlencoded POSTs MUST register
|
|
139
|
+
// `b.middleware.bodyParser()` before csrf-protect so that
|
|
140
|
+
// `req.body[fieldName]` is populated. Header-token submissions
|
|
141
|
+
// (X-CSRF-Token) work without bodyParser. The body-parser primitive
|
|
142
|
+
// owns size caps, content-type dispatch, and prototype-pollution
|
|
143
|
+
// defense; csrf-protect just reads the validated value.
|
|
144
|
+
|
|
145
|
+
function _writeReject(res, message) {
|
|
146
|
+
if (typeof res.writeHead === "function") {
|
|
147
|
+
var body = JSON.stringify({ error: message });
|
|
148
|
+
res.writeHead(403, {
|
|
149
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
150
|
+
"Content-Length": Buffer.byteLength(body),
|
|
151
|
+
});
|
|
152
|
+
res.end(body);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function create(opts) {
|
|
157
|
+
opts = opts || {};
|
|
158
|
+
|
|
159
|
+
validateOpts(opts, [
|
|
160
|
+
"cookie", "tokenLookup", "fieldName", "headerName", "methods", "audit",
|
|
161
|
+
], "middleware.csrfProtect");
|
|
162
|
+
|
|
163
|
+
// Tier A — exactly one issuance source.
|
|
164
|
+
var hasCookie = opts.cookie != null && opts.cookie !== false;
|
|
165
|
+
var hasLookup = typeof opts.tokenLookup === "function";
|
|
166
|
+
if (hasCookie && hasLookup) {
|
|
167
|
+
throw new Error("middleware.csrfProtect: opts.cookie and opts.tokenLookup are " +
|
|
168
|
+
"mutually exclusive — pick one (cookie = double-submit, tokenLookup = session-stored)");
|
|
169
|
+
}
|
|
170
|
+
if (!hasCookie && !hasLookup) {
|
|
171
|
+
throw new Error("middleware.csrfProtect: opts.cookie or opts.tokenLookup is required");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
var fieldName = opts.fieldName || DEFAULT_FIELD_NAME;
|
|
175
|
+
var headerName = (opts.headerName || DEFAULT_HEADER_NAME).toLowerCase();
|
|
176
|
+
var methods = (opts.methods || DEFAULT_METHODS).map(function (m) { return m.toUpperCase(); });
|
|
177
|
+
var auditOn = opts.audit !== false;
|
|
178
|
+
|
|
179
|
+
// Cookie issuance config (only when opts.cookie is set).
|
|
180
|
+
var cookieCfg = null;
|
|
181
|
+
if (hasCookie) {
|
|
182
|
+
var raw = opts.cookie === true ? {} : opts.cookie;
|
|
183
|
+
if (typeof raw !== "object") {
|
|
184
|
+
throw new Error("middleware.csrfProtect: opts.cookie must be true or an object");
|
|
185
|
+
}
|
|
186
|
+
cookieCfg = {
|
|
187
|
+
name: raw.name || DEFAULT_COOKIE_NAME,
|
|
188
|
+
sameSite: raw.sameSite || "Lax",
|
|
189
|
+
// secure: undefined means auto-detect from request scheme; explicit
|
|
190
|
+
// true/false overrides.
|
|
191
|
+
secure: raw.secure,
|
|
192
|
+
path: raw.path || "/",
|
|
193
|
+
httpOnly: !!raw.httpOnly,
|
|
194
|
+
maxAge: raw.maxAge != null ? raw.maxAge : null,
|
|
195
|
+
};
|
|
196
|
+
if (["Lax", "Strict", "None"].indexOf(cookieCfg.sameSite) === -1) {
|
|
197
|
+
throw new Error("middleware.csrfProtect: opts.cookie.sameSite must be Lax|Strict|None");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function _emitDenied(req, reason) {
|
|
202
|
+
if (!auditOn) return;
|
|
203
|
+
audit().safeEmit({
|
|
204
|
+
action: "auth.csrf.denied",
|
|
205
|
+
outcome: "denied",
|
|
206
|
+
actor: { ip: req.socket && req.socket.remoteAddress, userAgent: req.headers && req.headers["user-agent"] },
|
|
207
|
+
reason: reason,
|
|
208
|
+
metadata: { method: req.method, path: (req.url || "").split("?")[0] },
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Issuance path (cookie mode): on safe-method requests with no cookie,
|
|
213
|
+
// generate a token and queue it for the response. Always populate
|
|
214
|
+
// req.csrfToken so templates have something to render.
|
|
215
|
+
function _issueIfNeeded(req, res) {
|
|
216
|
+
if (!cookieCfg) return null;
|
|
217
|
+
var cookies = _parseCookieHeader(req.headers && req.headers.cookie);
|
|
218
|
+
var existing = cookies[cookieCfg.name];
|
|
219
|
+
if (existing && /^[a-f0-9]{2,}$/.test(existing)) {
|
|
220
|
+
req.csrfToken = existing;
|
|
221
|
+
return existing;
|
|
222
|
+
}
|
|
223
|
+
var fresh = forms.generateCsrfToken();
|
|
224
|
+
var setCookie = _formatSetCookie(cookieCfg.name, fresh, {
|
|
225
|
+
path: cookieCfg.path,
|
|
226
|
+
sameSite: cookieCfg.sameSite,
|
|
227
|
+
secure: cookieCfg.secure == null ? _isHttps(req) : !!cookieCfg.secure,
|
|
228
|
+
httpOnly: cookieCfg.httpOnly,
|
|
229
|
+
maxAge: cookieCfg.maxAge,
|
|
230
|
+
});
|
|
231
|
+
_appendSetCookie(res, setCookie);
|
|
232
|
+
req.csrfToken = fresh;
|
|
233
|
+
return fresh;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return function csrfProtect(req, res, next) {
|
|
237
|
+
// Issue/refresh the token on EVERY request (safe + state-changing)
|
|
238
|
+
// when running in cookie mode — templates rendered after a POST
|
|
239
|
+
// (e.g. error response) still need req.csrfToken populated.
|
|
240
|
+
var expected = _issueIfNeeded(req, res);
|
|
241
|
+
|
|
242
|
+
if (methods.indexOf(req.method) === -1) return next();
|
|
243
|
+
|
|
244
|
+
if (!cookieCfg) {
|
|
245
|
+
// Session-stored mode — operator's tokenLookup is the source.
|
|
246
|
+
expected = opts.tokenLookup(req);
|
|
247
|
+
}
|
|
248
|
+
if (!expected) {
|
|
249
|
+
_emitDenied(req, cookieCfg ? "no token cookie issued yet" : "no expected token in session");
|
|
250
|
+
return _writeReject(res, "CSRF token mismatch.");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Header path first — covers JSON / AJAX / multipart cases.
|
|
254
|
+
var submitted = req.headers && req.headers[headerName];
|
|
255
|
+
if (typeof submitted !== "string" || submitted.length === 0) {
|
|
256
|
+
// Fall back to body field if bodyParser already populated req.body.
|
|
257
|
+
// Operators with form-urlencoded POSTs are expected to register
|
|
258
|
+
// bodyParser before csrf-protect; body buffering / parsing lives
|
|
259
|
+
// in bodyParser, not here.
|
|
260
|
+
if (req.body && typeof req.body === "object") {
|
|
261
|
+
var v = req.body[fieldName];
|
|
262
|
+
if (typeof v === "string") submitted = v;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (!forms.verifyCsrfToken(submitted || "", expected)) {
|
|
267
|
+
_emitDenied(req, "submitted token does not match expected");
|
|
268
|
+
return _writeReject(res, "CSRF token mismatch.");
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return next();
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
module.exports = { create: create };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Error-handler middleware — thin adapter over lib/errors-page.
|
|
4
|
+
*
|
|
5
|
+
* Use this for the standard wiring path (`router.onError(b.middleware.
|
|
6
|
+
* errorHandler())`). Constructs an errors-page handler and forwards
|
|
7
|
+
* the (err, req, res, next) router signature into it. All classification,
|
|
8
|
+
* rendering, content negotiation, dev/prod gating, and audit emission
|
|
9
|
+
* lives in lib/errors-page — this file only wires the middleware
|
|
10
|
+
* convention plus the audit-action override that preserves the
|
|
11
|
+
* 'system.http.error' action name the framework's audit log already
|
|
12
|
+
* uses for HTTP-layer failures.
|
|
13
|
+
*
|
|
14
|
+
* Options forward to errors-page.create with one default override:
|
|
15
|
+
* auditAction: "system.http.error" (vs errors-page default "request.error")
|
|
16
|
+
*
|
|
17
|
+
* Plus a back-compat alias:
|
|
18
|
+
* exposeStackInDev: forwards to opts.showStack (true|false)
|
|
19
|
+
*/
|
|
20
|
+
var errorPage = require("../error-page");
|
|
21
|
+
|
|
22
|
+
function create(opts) {
|
|
23
|
+
opts = opts || {};
|
|
24
|
+
var pageOpts = Object.assign({}, opts);
|
|
25
|
+
|
|
26
|
+
// Preserve the existing audit action name for HTTP-layer errors.
|
|
27
|
+
if (pageOpts.auditAction === undefined) pageOpts.auditAction = "system.http.error";
|
|
28
|
+
// The middleware path historically returned JSON regardless of Accept
|
|
29
|
+
// (API-style). Page-style HTML rendering is reachable via the direct
|
|
30
|
+
// errorPage.create() surface, where defaultFormat="auto" negotiates.
|
|
31
|
+
if (pageOpts.defaultFormat === undefined) pageOpts.defaultFormat = "json";
|
|
32
|
+
|
|
33
|
+
// Back-compat: middleware historically used `exposeStackInDev`;
|
|
34
|
+
// errors-page uses `showStack`. Map when only the legacy name is set.
|
|
35
|
+
if (pageOpts.showStack === undefined && pageOpts.exposeStackInDev !== undefined) {
|
|
36
|
+
pageOpts.showStack = !!pageOpts.exposeStackInDev;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
var pageHandler = errorPage.create(pageOpts);
|
|
40
|
+
|
|
41
|
+
return function errorHandler(err, req, res, _next) {
|
|
42
|
+
pageHandler(err, req, res);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = { create: create };
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* health — liveness / readiness / startup endpoint primitive.
|
|
4
|
+
*
|
|
5
|
+
* Without this, every operator wires 5–20 lines of boilerplate that
|
|
6
|
+
* gets subtly wrong: /readyz returning 200 before the DB is connected
|
|
7
|
+
* (LB routes traffic into a half-booted process), /healthz blocking
|
|
8
|
+
* on a slow check (orchestrator kills the pod), no graceful-shutdown
|
|
9
|
+
* coordination (LB sends traffic into a draining process), or
|
|
10
|
+
* leaking internal state on a public endpoint.
|
|
11
|
+
*
|
|
12
|
+
* Three probe tiers, each its own URL path, each its own check set:
|
|
13
|
+
*
|
|
14
|
+
* /healthz liveness "process is alive" — defaults to always-200
|
|
15
|
+
* unless the operator registers a liveness
|
|
16
|
+
* check (e.g. deadlock detector). Orchestrators
|
|
17
|
+
* use this to decide whether to KILL the pod.
|
|
18
|
+
* /readyz readiness "process can serve traffic" — every readiness
|
|
19
|
+
* check must pass. Load balancers use this to
|
|
20
|
+
* decide whether to ROUTE TRAFFIC. Default tier
|
|
21
|
+
* for registerCheck.
|
|
22
|
+
* /startupz startup "slow init has finished" — separate from
|
|
23
|
+
* readiness so a slow-loading model / migration
|
|
24
|
+
* doesn't fail the liveness probe before it
|
|
25
|
+
* finishes. Operators register here for the
|
|
26
|
+
* first-N-seconds-of-process startup work.
|
|
27
|
+
*
|
|
28
|
+
* Graceful-shutdown integration: markShuttingDown() flips readiness
|
|
29
|
+
* (and only readiness) to 503 immediately. /healthz keeps returning
|
|
30
|
+
* 200 throughout so the orchestrator doesn't kill the pod mid-drain.
|
|
31
|
+
* Standard Kubernetes pattern. `b.app.shutdown()` calls this on the
|
|
32
|
+
* health-check instance it manages; standalone callers can invoke
|
|
33
|
+
* markShuttingDown() directly.
|
|
34
|
+
*
|
|
35
|
+
* var hc = b.middleware.health.create({
|
|
36
|
+
* livenessPath: "/healthz",
|
|
37
|
+
* readinessPath: "/readyz",
|
|
38
|
+
* startupPath: "/startupz",
|
|
39
|
+
* defaultTimeoutMs: 5000,
|
|
40
|
+
* cacheMs: 0,
|
|
41
|
+
* detailLevel: "minimal", // "minimal" | "detailed"
|
|
42
|
+
* detailPredicate: function (req) { ... }, // operator decides
|
|
43
|
+
* });
|
|
44
|
+
*
|
|
45
|
+
* hc.registerCheck("db", async function () {
|
|
46
|
+
* return { ok: b.db.isReady(), latencyMs: ... };
|
|
47
|
+
* }, { tier: "readiness", timeoutMs: 1000, critical: true });
|
|
48
|
+
*
|
|
49
|
+
* hc.registerCheck("queue", async function () {
|
|
50
|
+
* return b.queue.isReady();
|
|
51
|
+
* }, { tier: "readiness", critical: false });
|
|
52
|
+
*
|
|
53
|
+
* router.use(hc.middleware());
|
|
54
|
+
*
|
|
55
|
+
* // On SIGTERM:
|
|
56
|
+
* hc.markShuttingDown();
|
|
57
|
+
* // → /readyz returns 503 immediately; LB drains the pod;
|
|
58
|
+
* // /healthz still 200 so orchestrator waits for clean exit.
|
|
59
|
+
*
|
|
60
|
+
* Check function shape — anything truthy/falsy works, but two patterns
|
|
61
|
+
* are preferred:
|
|
62
|
+
*
|
|
63
|
+
* () => true | false fast path; ok flag only
|
|
64
|
+
* () => ({ ok: bool, latencyMs?, ... }) detail visible in detailed mode
|
|
65
|
+
*
|
|
66
|
+
* Promise versions of either also work; per-check timeout (default
|
|
67
|
+
* `defaultTimeoutMs`) bounds the wait. A timed-out check fails ok=false
|
|
68
|
+
* without blocking other checks.
|
|
69
|
+
*
|
|
70
|
+
* Status codes:
|
|
71
|
+
* 200 "ok" every check passed (or no checks registered)
|
|
72
|
+
* 200 "degraded" a NON-critical check failed; service still
|
|
73
|
+
* serving (informational status; operator can
|
|
74
|
+
* alert on the body content)
|
|
75
|
+
* 503 "fail" a CRITICAL check failed; LB should drain
|
|
76
|
+
* 503 "shutting-down" readiness only; markShuttingDown was called
|
|
77
|
+
*
|
|
78
|
+
* Security:
|
|
79
|
+
* - Default `detailLevel: "minimal"` returns only `{ status }` to the
|
|
80
|
+
* public endpoint. Internal state (per-check latency, error text,
|
|
81
|
+
* downstream service health) is not leaked.
|
|
82
|
+
* - `detailLevel: "detailed"` enables the full check breakdown for
|
|
83
|
+
* every probe — only suitable for endpoints behind operator auth.
|
|
84
|
+
* - `detailPredicate(req)` lets the operator decide per-request:
|
|
85
|
+
* return true for internal IPs / authed requests, false otherwise.
|
|
86
|
+
* Detail predicate throwing → minimal response (fail closed).
|
|
87
|
+
* - `Cache-Control: no-store` on every response so probes never get
|
|
88
|
+
* cached by intermediate proxies.
|
|
89
|
+
*
|
|
90
|
+
* Caching:
|
|
91
|
+
* - cacheMs > 0 caches each tier's result for that duration. With
|
|
92
|
+
* k8s-style 1Hz probes against 10 checks, this drops the ambient
|
|
93
|
+
* load substantially. Cache is per-tier (liveness cached separately
|
|
94
|
+
* from readiness) — markShuttingDown bypasses readiness cache.
|
|
95
|
+
*
|
|
96
|
+
* Concurrent execution:
|
|
97
|
+
* - All checks for a tier run via Promise.all with per-check withTimeout.
|
|
98
|
+
* - One stuck check doesn't block the others; the timed-out check
|
|
99
|
+
* fails as { ok: false, error: "timeout" } and the others complete.
|
|
100
|
+
*/
|
|
101
|
+
|
|
102
|
+
var safeAsync = require("../safe-async");
|
|
103
|
+
var validateOpts = require("../validate-opts");
|
|
104
|
+
var { defineClass } = require("../framework-error");
|
|
105
|
+
|
|
106
|
+
var HealthError = defineClass("HealthError", { alwaysPermanent: true });
|
|
107
|
+
|
|
108
|
+
var TIERS = Object.freeze(["liveness", "readiness", "startup"]);
|
|
109
|
+
var TIER_SET = new Set(TIERS);
|
|
110
|
+
|
|
111
|
+
function create(opts) {
|
|
112
|
+
opts = opts || {};
|
|
113
|
+
validateOpts(opts, [
|
|
114
|
+
"livenessPath", "readinessPath", "startupPath", "detailLevel",
|
|
115
|
+
"detailPredicate", "defaultTimeoutMs", "cacheMs", "includeMeta", "version",
|
|
116
|
+
], "middleware.health");
|
|
117
|
+
var livenessPath = opts.livenessPath || "/healthz";
|
|
118
|
+
var readinessPath = opts.readinessPath || "/readyz";
|
|
119
|
+
var startupPath = opts.startupPath || "/startupz";
|
|
120
|
+
var detailLevel = opts.detailLevel || "minimal";
|
|
121
|
+
if (detailLevel !== "minimal" && detailLevel !== "detailed") {
|
|
122
|
+
throw new HealthError("health/bad-detail-level",
|
|
123
|
+
"detailLevel must be 'minimal' or 'detailed'");
|
|
124
|
+
}
|
|
125
|
+
var detailPredicate = typeof opts.detailPredicate === "function" ? opts.detailPredicate : null;
|
|
126
|
+
var defaultTimeoutMs = typeof opts.defaultTimeoutMs === "number" && opts.defaultTimeoutMs > 0
|
|
127
|
+
? opts.defaultTimeoutMs : 5000;
|
|
128
|
+
var cacheMs = typeof opts.cacheMs === "number" && opts.cacheMs > 0 ? opts.cacheMs : 0;
|
|
129
|
+
var includeMeta = opts.includeMeta !== false;
|
|
130
|
+
var version = opts.version || null;
|
|
131
|
+
|
|
132
|
+
var checks = []; // { name, fn, tiers: Set, timeoutMs, critical }
|
|
133
|
+
var shuttingDown = false;
|
|
134
|
+
var startedAt = Date.now();
|
|
135
|
+
var cache = {}; // tier → { result, expiresAt }
|
|
136
|
+
|
|
137
|
+
function registerCheck(name, fn, copts) {
|
|
138
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
139
|
+
throw new HealthError("health/bad-name",
|
|
140
|
+
"registerCheck: name must be a non-empty string");
|
|
141
|
+
}
|
|
142
|
+
if (typeof fn !== "function") {
|
|
143
|
+
throw new HealthError("health/bad-fn",
|
|
144
|
+
"registerCheck: fn must be a function");
|
|
145
|
+
}
|
|
146
|
+
copts = copts || {};
|
|
147
|
+
var tier = copts.tier || "readiness";
|
|
148
|
+
var tiers = Array.isArray(tier) ? tier : [tier];
|
|
149
|
+
for (var i = 0; i < tiers.length; i++) {
|
|
150
|
+
if (!TIER_SET.has(tiers[i])) {
|
|
151
|
+
throw new HealthError("health/bad-tier",
|
|
152
|
+
"registerCheck: tier '" + tiers[i] + "' must be one of " + TIERS.join(", "));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// Refuse duplicate names within a tier — silent overwrite makes
|
|
156
|
+
// operator config bugs impossible to debug.
|
|
157
|
+
for (var j = 0; j < checks.length; j++) {
|
|
158
|
+
if (checks[j].name === name) {
|
|
159
|
+
for (var k = 0; k < tiers.length; k++) {
|
|
160
|
+
if (checks[j].tiers.has(tiers[k])) {
|
|
161
|
+
throw new HealthError("health/duplicate-check",
|
|
162
|
+
"registerCheck: check '" + name + "' already registered for tier '" + tiers[k] + "'");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
var timeoutMs = typeof copts.timeoutMs === "number" && copts.timeoutMs > 0
|
|
168
|
+
? copts.timeoutMs : defaultTimeoutMs;
|
|
169
|
+
checks.push({
|
|
170
|
+
name: name,
|
|
171
|
+
fn: fn,
|
|
172
|
+
tiers: new Set(tiers),
|
|
173
|
+
timeoutMs: timeoutMs,
|
|
174
|
+
critical: copts.critical !== false,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Bypass cache when shuttingDown was just flipped; readiness must
|
|
179
|
+
// surface 503 immediately, not wait for the cache window to expire.
|
|
180
|
+
function _bypassCacheFor(tier) {
|
|
181
|
+
return tier === "readiness" && shuttingDown;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function runChecks(tier) {
|
|
185
|
+
if (!TIER_SET.has(tier)) {
|
|
186
|
+
throw new HealthError("health/bad-tier", "runChecks: tier must be one of " + TIERS.join(", "));
|
|
187
|
+
}
|
|
188
|
+
if (cacheMs > 0 && !_bypassCacheFor(tier)) {
|
|
189
|
+
var cached = cache[tier];
|
|
190
|
+
if (cached && cached.expiresAt > Date.now()) return cached.result;
|
|
191
|
+
}
|
|
192
|
+
var tierChecks = checks.filter(function (c) { return c.tiers.has(tier); });
|
|
193
|
+
var promises = tierChecks.map(function (c) {
|
|
194
|
+
var start = Date.now();
|
|
195
|
+
// Wrap the check in withTimeout. Promise.resolve() coerces sync
|
|
196
|
+
// returns into Promises so the timeout can be applied uniformly.
|
|
197
|
+
return safeAsync.withTimeout(
|
|
198
|
+
Promise.resolve().then(function () { return c.fn(); }),
|
|
199
|
+
c.timeoutMs,
|
|
200
|
+
{ name: "health-check:" + c.name }
|
|
201
|
+
)
|
|
202
|
+
.then(function (raw) {
|
|
203
|
+
var ok, detail;
|
|
204
|
+
if (raw === true) { ok = true; detail = null; }
|
|
205
|
+
else if (raw === false) { ok = false; detail = null; }
|
|
206
|
+
else if (raw && typeof raw === "object") {
|
|
207
|
+
ok = !!raw.ok;
|
|
208
|
+
detail = raw;
|
|
209
|
+
} else {
|
|
210
|
+
// Truthy non-boolean / non-object → treat as ok=true. Falsy → ok=false.
|
|
211
|
+
ok = !!raw;
|
|
212
|
+
detail = null;
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
name: c.name,
|
|
216
|
+
ok: ok,
|
|
217
|
+
detail: detail,
|
|
218
|
+
ms: Date.now() - start,
|
|
219
|
+
critical: c.critical,
|
|
220
|
+
};
|
|
221
|
+
})
|
|
222
|
+
.catch(function (err) {
|
|
223
|
+
return {
|
|
224
|
+
name: c.name,
|
|
225
|
+
ok: false,
|
|
226
|
+
error: (err && err.message) || String(err),
|
|
227
|
+
ms: Date.now() - start,
|
|
228
|
+
critical: c.critical,
|
|
229
|
+
};
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
var checked = await Promise.all(promises);
|
|
234
|
+
var results = {};
|
|
235
|
+
var anyFailed = false;
|
|
236
|
+
var anyCriticalFailed = false;
|
|
237
|
+
for (var i = 0; i < checked.length; i++) {
|
|
238
|
+
var r = checked[i];
|
|
239
|
+
var entry = { ok: r.ok, ms: r.ms };
|
|
240
|
+
if (r.detail) {
|
|
241
|
+
// Merge detail keys other than `ok` into the entry.
|
|
242
|
+
var keys = Object.keys(r.detail);
|
|
243
|
+
for (var n = 0; n < keys.length; n++) {
|
|
244
|
+
if (keys[n] !== "ok") entry[keys[n]] = r.detail[keys[n]];
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (r.error) entry.error = r.error;
|
|
248
|
+
if (!r.critical) entry.critical = false;
|
|
249
|
+
results[r.name] = entry;
|
|
250
|
+
if (!r.ok) {
|
|
251
|
+
anyFailed = true;
|
|
252
|
+
if (r.critical) anyCriticalFailed = true;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
var status;
|
|
257
|
+
if (tier === "readiness" && shuttingDown) status = "shutting-down";
|
|
258
|
+
else if (anyCriticalFailed) status = "fail";
|
|
259
|
+
else if (anyFailed) status = "degraded";
|
|
260
|
+
else status = "ok";
|
|
261
|
+
|
|
262
|
+
var result = { status: status, checks: results, tier: tier, shuttingDown: shuttingDown };
|
|
263
|
+
if (cacheMs > 0 && !_bypassCacheFor(tier)) {
|
|
264
|
+
cache[tier] = { result: result, expiresAt: Date.now() + cacheMs };
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function _writeResponse(res, result, includeDetail) {
|
|
270
|
+
var status = (result.status === "ok" || result.status === "degraded") ? 200 : 503;
|
|
271
|
+
var payload;
|
|
272
|
+
if (includeDetail) {
|
|
273
|
+
payload = { status: result.status, checks: result.checks };
|
|
274
|
+
if (includeMeta) {
|
|
275
|
+
payload.uptime = Date.now() - startedAt;
|
|
276
|
+
if (version) payload.version = version;
|
|
277
|
+
}
|
|
278
|
+
} else {
|
|
279
|
+
payload = { status: result.status };
|
|
280
|
+
}
|
|
281
|
+
var body = JSON.stringify(payload);
|
|
282
|
+
res.writeHead(status, {
|
|
283
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
284
|
+
"Content-Length": Buffer.byteLength(body),
|
|
285
|
+
"Cache-Control": "no-store",
|
|
286
|
+
});
|
|
287
|
+
res.end(body);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function _wantDetail(req) {
|
|
291
|
+
if (detailLevel === "detailed") return true;
|
|
292
|
+
if (!detailPredicate) return false;
|
|
293
|
+
try { return !!detailPredicate(req); }
|
|
294
|
+
catch (_e) { return false; /* fail-closed */ }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function middleware() {
|
|
298
|
+
return async function health(req, res, next) {
|
|
299
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
300
|
+
var url = req.url || "";
|
|
301
|
+
var path = url.split("?")[0];
|
|
302
|
+
var tier;
|
|
303
|
+
if (path === livenessPath) tier = "liveness";
|
|
304
|
+
else if (path === readinessPath) tier = "readiness";
|
|
305
|
+
else if (path === startupPath) tier = "startup";
|
|
306
|
+
else return next();
|
|
307
|
+
|
|
308
|
+
try {
|
|
309
|
+
var result = await runChecks(tier);
|
|
310
|
+
if (req.method === "HEAD") {
|
|
311
|
+
// HEAD: status code only, no body.
|
|
312
|
+
var status = (result.status === "ok" || result.status === "degraded") ? 200 : 503;
|
|
313
|
+
res.writeHead(status, { "Cache-Control": "no-store" });
|
|
314
|
+
res.end();
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
_writeResponse(res, result, _wantDetail(req));
|
|
318
|
+
} catch {
|
|
319
|
+
// Catastrophic — write 503 with minimal detail and never leak
|
|
320
|
+
// internal error info on a public endpoint.
|
|
321
|
+
var body = JSON.stringify({ status: "fail", error: "health-check-internal" });
|
|
322
|
+
res.writeHead(503, {
|
|
323
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
324
|
+
"Content-Length": Buffer.byteLength(body),
|
|
325
|
+
"Cache-Control": "no-store",
|
|
326
|
+
});
|
|
327
|
+
res.end(body);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function markShuttingDown() { shuttingDown = true; }
|
|
333
|
+
function isShuttingDown() { return shuttingDown; }
|
|
334
|
+
function uptime() { return Date.now() - startedAt; }
|
|
335
|
+
|
|
336
|
+
function _resetForTest() {
|
|
337
|
+
checks = [];
|
|
338
|
+
shuttingDown = false;
|
|
339
|
+
startedAt = Date.now();
|
|
340
|
+
cache = {};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return {
|
|
344
|
+
registerCheck: registerCheck,
|
|
345
|
+
middleware: middleware,
|
|
346
|
+
runChecks: runChecks,
|
|
347
|
+
markShuttingDown: markShuttingDown,
|
|
348
|
+
isShuttingDown: isShuttingDown,
|
|
349
|
+
uptime: uptime,
|
|
350
|
+
_resetForTest: _resetForTest,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
module.exports = {
|
|
355
|
+
create: create,
|
|
356
|
+
HealthError: HealthError,
|
|
357
|
+
TIERS: TIERS,
|
|
358
|
+
};
|