@blamejs/core 0.4.8 → 0.4.10
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 +7 -0
- package/README.md +1 -1
- package/index.js +2 -1
- package/lib/auth/lockout.js +446 -0
- package/lib/framework-error.js +6 -0
- package/lib/middleware/body-parser.js +150 -9
- package/lib/middleware/security-headers.js +17 -8
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,13 @@ upgrading across more than a few patches at a time.
|
|
|
8
8
|
|
|
9
9
|
## v0.4.x
|
|
10
10
|
|
|
11
|
+
- **0.4.9** (2026-04-30) — Origin-Agent-Cluster + DNS-Prefetch-Control headers; b.auth.lockout primitive
|
|
12
|
+
- **0.4.8** (2026-04-30) — wiki SEO surface: per-page OG / Twitter / JSON-LD + sitemap.xml + robots.txt
|
|
13
|
+
- **0.4.7** (2026-04-30) — audit-fix the welcome page's "what's in the box" table
|
|
14
|
+
- **0.4.6** (2026-04-30) — wiki gets the brand-flare on every page + substantive content additions
|
|
15
|
+
- **0.4.5** (2026-04-30) — canonical domain is blamejs.com (was blamejs.app everywhere)
|
|
16
|
+
- **0.4.4** (2026-04-30) — document BLAMEJS_AUDIT_SIGNING_PASSPHRASE everywhere
|
|
17
|
+
- **0.4.3** (2026-04-30) — b.ssrfGuard primitive (default-on in httpClient) + wiki posture auto-detect
|
|
11
18
|
- **0.4.2** (2026-04-30) — npm keywords
|
|
12
19
|
- **0.4.1** (2026-04-29) — wiki bot-guard skips /healthz so the post-publish smoke check passes
|
|
13
20
|
- **0.4.0** (2026-04-29) — bench suite + drops the deprecated b.logger.createLogger
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ One install. One upgrade path. One place to look when something breaks — no bl
|
|
|
11
11
|
The modern Node app is a 1,200-package supply-chain liability with no LTS calendar, no curator, and no accountability. Frameworks peer-depend their internals onto you and call it modularity. blamejs takes the opposite stance:
|
|
12
12
|
|
|
13
13
|
- **Vendored standard library.** Auth, sessions, jobs, mail, storage, crypto, ORM, templating — bundled with the framework, not hunted on npm. Your `package.json` has one entry.
|
|
14
|
-
- **Security as a default, not a config flag.** Post-quantum-aware crypto envelopes, sealed-by-default storage, server-rendered output, CSRF/origin/bot defenses wired in from line zero.
|
|
14
|
+
- **Security as a default, not a config flag.** Post-quantum-aware crypto envelopes, sealed-by-default storage, server-rendered output, CSRF/origin/bot defenses, per-account brute-force lockout, all wired in from line zero.
|
|
15
15
|
- **Server-rendering first.** HTML out of the box; client JS is opt-in islands, not the foundation.
|
|
16
16
|
- **A real LTS calendar.** Major versions on a published cadence with documented deprecation windows. No silent semver-major surprises in transitive deps.
|
|
17
17
|
|
package/index.js
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* error-handler, body-parser, csp-nonce, compression,
|
|
21
21
|
* health, api-encrypt), httpClient, websocket,
|
|
22
22
|
* websocketChannels, nonceStore
|
|
23
|
-
* Auth: auth.{password,totp,passkey,jwt,oauth}, authHeader
|
|
23
|
+
* Auth: auth.{password,totp,passkey,jwt,oauth,lockout}, authHeader
|
|
24
24
|
* Render: template, render, staticServe, forms, errorPage
|
|
25
25
|
* App: createApp, jobs, mail, mailBounce, scheduler,
|
|
26
26
|
* appShutdown
|
|
@@ -93,6 +93,7 @@ var auth = {
|
|
|
93
93
|
passkey: require("./lib/auth/passkey"),
|
|
94
94
|
jwt: require("./lib/auth/jwt"),
|
|
95
95
|
oauth: require("./lib/auth/oauth"),
|
|
96
|
+
lockout: require("./lib/auth/lockout"),
|
|
96
97
|
};
|
|
97
98
|
var template = require("./lib/template");
|
|
98
99
|
var render = require("./lib/render");
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* b.auth.lockout — per-key failed-attempt tracking with exponential
|
|
4
|
+
* backoff lockout windows and admin/unlock.
|
|
5
|
+
*
|
|
6
|
+
* Operators compose this around any "X attempts to do Y" surface where
|
|
7
|
+
* online brute force is the threat — login by password, login by TOTP,
|
|
8
|
+
* passkey verification, password-reset code entry, etc. Each operator-
|
|
9
|
+
* named instance keeps its own counter namespace, so login attempts and
|
|
10
|
+
* TOTP attempts decay and lock independently.
|
|
11
|
+
*
|
|
12
|
+
* State storage is a b.cache instance the operator passes in. Memory
|
|
13
|
+
* backend → per-process counters. Cluster backend → shared across nodes.
|
|
14
|
+
* The cache TTL keeps the state self-cleaning — no separate sweep.
|
|
15
|
+
*
|
|
16
|
+
* var loginLock = b.auth.lockout.create({
|
|
17
|
+
* namespace: "login",
|
|
18
|
+
* cache: b.cache.create({ namespace: "auth.lockout.login", backend: "cluster" }),
|
|
19
|
+
* audit: b.audit,
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* // Pre-check before doing argon2 verify (saves ~250ms when locked)
|
|
23
|
+
* var state = await loginLock.check(req.body.email);
|
|
24
|
+
* if (state.locked) return res.status(429).json({ lockedUntil: state.lockedUntil });
|
|
25
|
+
*
|
|
26
|
+
* var ok = await b.auth.password.verify(stored, req.body.password);
|
|
27
|
+
* if (!ok) {
|
|
28
|
+
* var verdict = await loginLock.recordFailure(req.body.email, { req });
|
|
29
|
+
* return res.status(401).json({
|
|
30
|
+
* attemptsRemaining: Math.max(0, MAX - verdict.attempts),
|
|
31
|
+
* lockedUntil: verdict.lockedUntil,
|
|
32
|
+
* });
|
|
33
|
+
* }
|
|
34
|
+
* await loginLock.recordSuccess(req.body.email, { req });
|
|
35
|
+
* // ... session.create
|
|
36
|
+
*
|
|
37
|
+
* // Admin-driven unlock — emits auth.lockout.unlock with the admin
|
|
38
|
+
* // operator's 5 W's via extractActorContext({ req }).
|
|
39
|
+
* await loginLock.unlock(targetUserId, { req, reason: "support ticket #4471" });
|
|
40
|
+
*
|
|
41
|
+
* Default backoff ladder (each subsequent lockout in a window-of-windows
|
|
42
|
+
* stays longer to make sustained attacks expensive):
|
|
43
|
+
*
|
|
44
|
+
* 1st lockout → C.TIME.minutes(1)
|
|
45
|
+
* 2nd → C.TIME.minutes(5)
|
|
46
|
+
* 3rd → C.TIME.minutes(15)
|
|
47
|
+
* 4th → C.TIME.hours(1)
|
|
48
|
+
* 5th and later → C.TIME.hours(6)
|
|
49
|
+
*
|
|
50
|
+
* Failures outside `windowMs` decay (counter resets on the next failure).
|
|
51
|
+
* Successful auth clears the counter and any active lockout entirely so
|
|
52
|
+
* a legitimate user who finally remembers their password isn't penalised
|
|
53
|
+
* for the prior streak.
|
|
54
|
+
*
|
|
55
|
+
* Backend-error posture: if the cache backend throws on get/set/del —
|
|
56
|
+
* Redis down, cluster DB unreachable — the lockout fails OPEN, not
|
|
57
|
+
* closed. The framework's job is to slow brute force, not to lock
|
|
58
|
+
* operators out of their own admin account because the cache went
|
|
59
|
+
* away. Backend errors emit `auth.lockout.cache_error` observability
|
|
60
|
+
* so ops dashboards see the issue.
|
|
61
|
+
*
|
|
62
|
+
* Operator surface returned by create():
|
|
63
|
+
*
|
|
64
|
+
* recordFailure(key, opts?) → { locked, attempts, lockedUntil? }
|
|
65
|
+
* recordSuccess(key, opts?) → void (clears counter)
|
|
66
|
+
* check(key) → { locked, attempts, lockedUntil? }
|
|
67
|
+
* (read-only)
|
|
68
|
+
* unlock(key, opts?) → boolean (admin unlock)
|
|
69
|
+
* attempts(key) → number
|
|
70
|
+
* close() → void (no-op; cache is
|
|
71
|
+
* operator-owned)
|
|
72
|
+
*
|
|
73
|
+
* Audit events (when `audit: b.audit` passed):
|
|
74
|
+
*
|
|
75
|
+
* auth.lockout.failure — every recordFailure. Default ON.
|
|
76
|
+
* auth.lockout.engaged — lockout transition. Default ON.
|
|
77
|
+
* auth.lockout.unlock — admin unlock. Default ON.
|
|
78
|
+
* auth.lockout.success — recordSuccess. Default OFF (opt in via
|
|
79
|
+
* auditSuccess: true for raw request-log mode).
|
|
80
|
+
*/
|
|
81
|
+
|
|
82
|
+
var C = require("../constants");
|
|
83
|
+
var lazyRequire = require("../lazy-require");
|
|
84
|
+
var requestHelpers = require("../request-helpers");
|
|
85
|
+
var validateOpts = require("../validate-opts");
|
|
86
|
+
var { LockoutError } = require("../framework-error");
|
|
87
|
+
|
|
88
|
+
var observability = lazyRequire(function () { return require("../observability"); });
|
|
89
|
+
|
|
90
|
+
var _err = LockoutError.factory;
|
|
91
|
+
|
|
92
|
+
var DEFAULTS = Object.freeze({
|
|
93
|
+
maxAttempts: 5,
|
|
94
|
+
windowMs: C.TIME.minutes(15),
|
|
95
|
+
lockoutDurations: Object.freeze([
|
|
96
|
+
C.TIME.minutes(1),
|
|
97
|
+
C.TIME.minutes(5),
|
|
98
|
+
C.TIME.minutes(15),
|
|
99
|
+
C.TIME.hours(1),
|
|
100
|
+
C.TIME.hours(6),
|
|
101
|
+
]),
|
|
102
|
+
auditFailures: true,
|
|
103
|
+
auditEngaged: true,
|
|
104
|
+
auditUnlock: true,
|
|
105
|
+
auditSuccess: false,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
var ALLOWED_OPTS = [
|
|
109
|
+
"namespace", "cache", "maxAttempts", "windowMs", "lockoutDurations",
|
|
110
|
+
"audit", "auditFailures", "auditEngaged", "auditSuccess", "auditUnlock",
|
|
111
|
+
"observability", "clock",
|
|
112
|
+
];
|
|
113
|
+
|
|
114
|
+
function _requireString(name, val) {
|
|
115
|
+
if (typeof val !== "string" || val.length === 0) {
|
|
116
|
+
throw _err("BAD_OPT", name + ": expected non-empty string, got " +
|
|
117
|
+
typeof val + " " + JSON.stringify(val));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function _requirePositiveInt(name, val) {
|
|
122
|
+
if (typeof val !== "number" || !isFinite(val) || val < 1 || Math.floor(val) !== val) {
|
|
123
|
+
throw _err("BAD_OPT", name + ": expected positive integer, got " +
|
|
124
|
+
typeof val + " " + JSON.stringify(val));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function _requireNonNegFinite(name, val) {
|
|
129
|
+
if (typeof val !== "number" || !isFinite(val) || val < 0) {
|
|
130
|
+
throw _err("BAD_OPT", name + ": expected non-negative finite number, got " +
|
|
131
|
+
typeof val + " " + JSON.stringify(val));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function _requireKey(key) {
|
|
136
|
+
if (typeof key !== "string" || key.length === 0) {
|
|
137
|
+
throw _err("BAD_KEY", "key must be a non-empty string, got " +
|
|
138
|
+
typeof key + " " + JSON.stringify(key));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function _resolveDuration(durations, lockNumber) {
|
|
143
|
+
if (typeof durations === "function") {
|
|
144
|
+
var v = durations(lockNumber);
|
|
145
|
+
if (typeof v !== "number" || !isFinite(v) || v < 0) {
|
|
146
|
+
throw _err("BAD_LOCKOUT_DURATION",
|
|
147
|
+
"lockoutDurations(" + lockNumber + ") must return a non-negative finite number, got " +
|
|
148
|
+
typeof v + " " + JSON.stringify(v));
|
|
149
|
+
}
|
|
150
|
+
return v;
|
|
151
|
+
}
|
|
152
|
+
// Array — clamp to last entry so deeper lockouts stay at the longest.
|
|
153
|
+
var idx = Math.min(lockNumber - 1, durations.length - 1);
|
|
154
|
+
return durations[idx];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function create(opts) {
|
|
158
|
+
opts = opts || {};
|
|
159
|
+
validateOpts(opts, ALLOWED_OPTS, "auth.lockout");
|
|
160
|
+
|
|
161
|
+
if (!opts.cache || typeof opts.cache !== "object" ||
|
|
162
|
+
typeof opts.cache.get !== "function" ||
|
|
163
|
+
typeof opts.cache.set !== "function" ||
|
|
164
|
+
typeof opts.cache.del !== "function") {
|
|
165
|
+
throw _err("BAD_OPT", "auth.lockout.create: opts.cache must be a b.cache " +
|
|
166
|
+
"instance (or shape with get/set/del). Pass b.cache.create({...}).");
|
|
167
|
+
}
|
|
168
|
+
_requireString("namespace", opts.namespace);
|
|
169
|
+
|
|
170
|
+
var maxAttempts = opts.maxAttempts !== undefined ? opts.maxAttempts : DEFAULTS.maxAttempts;
|
|
171
|
+
_requirePositiveInt("maxAttempts", maxAttempts);
|
|
172
|
+
|
|
173
|
+
var windowMs = opts.windowMs !== undefined ? opts.windowMs : DEFAULTS.windowMs;
|
|
174
|
+
_requireNonNegFinite("windowMs", windowMs);
|
|
175
|
+
|
|
176
|
+
var lockoutDurations = opts.lockoutDurations !== undefined
|
|
177
|
+
? opts.lockoutDurations : DEFAULTS.lockoutDurations;
|
|
178
|
+
if (typeof lockoutDurations !== "function") {
|
|
179
|
+
if (!Array.isArray(lockoutDurations) || lockoutDurations.length === 0) {
|
|
180
|
+
throw _err("BAD_OPT", "lockoutDurations must be a non-empty array of ms or a function(lockNumber)→ms");
|
|
181
|
+
}
|
|
182
|
+
for (var i = 0; i < lockoutDurations.length; i++) {
|
|
183
|
+
_requireNonNegFinite("lockoutDurations[" + i + "]", lockoutDurations[i]);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (opts.audit !== undefined && opts.audit !== null) {
|
|
188
|
+
if (typeof opts.audit !== "object" || typeof opts.audit.safeEmit !== "function") {
|
|
189
|
+
throw _err("BAD_OPT", "auth.lockout.create: audit must be a b.audit-shaped object (safeEmit fn)");
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (opts.observability !== undefined && opts.observability !== null) {
|
|
193
|
+
if (typeof opts.observability !== "object" || typeof opts.observability.event !== "function") {
|
|
194
|
+
throw _err("BAD_OPT", "auth.lockout.create: observability must be b.observability-shaped (event fn)");
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (opts.clock !== undefined && typeof opts.clock !== "function") {
|
|
198
|
+
throw _err("BAD_OPT", "auth.lockout.create: clock must be a function or undefined");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
var cache = opts.cache;
|
|
202
|
+
var namespace = opts.namespace;
|
|
203
|
+
var auditInst = opts.audit || null;
|
|
204
|
+
var obsInst = opts.observability || null;
|
|
205
|
+
var clock = opts.clock || Date.now;
|
|
206
|
+
var auditFailures = opts.auditFailures !== undefined ? !!opts.auditFailures : DEFAULTS.auditFailures;
|
|
207
|
+
var auditEngaged = opts.auditEngaged !== undefined ? !!opts.auditEngaged : DEFAULTS.auditEngaged;
|
|
208
|
+
var auditSuccess = opts.auditSuccess !== undefined ? !!opts.auditSuccess : DEFAULTS.auditSuccess;
|
|
209
|
+
var auditUnlock = opts.auditUnlock !== undefined ? !!opts.auditUnlock : DEFAULTS.auditUnlock;
|
|
210
|
+
|
|
211
|
+
function _scopedKey(key) { return namespace + ":" + key; }
|
|
212
|
+
|
|
213
|
+
function _emitObs(name, labels) {
|
|
214
|
+
var sink = obsInst || _safeGlobalObs();
|
|
215
|
+
if (!sink) return;
|
|
216
|
+
try { sink.event(name, 1, labels); } catch (_e) { /* observability is best-effort */ }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Fall back to the framework's global observability registry when the
|
|
220
|
+
// operator didn't pass their own. event() is a no-op when no registry
|
|
221
|
+
// is wired, so this is zero-cost in apps without observability.
|
|
222
|
+
function _safeGlobalObs() {
|
|
223
|
+
try { return observability(); } catch (_e) { return null; }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function _emitAudit(action, key, outcome, metadata, req) {
|
|
227
|
+
if (!auditInst) return;
|
|
228
|
+
try {
|
|
229
|
+
var event = {
|
|
230
|
+
action: action,
|
|
231
|
+
outcome: outcome,
|
|
232
|
+
resource: { kind: "auth.lockout", id: namespace + ":" + key },
|
|
233
|
+
metadata: metadata || {},
|
|
234
|
+
};
|
|
235
|
+
if (req) event.actor = requestHelpers.extractActorContext(req);
|
|
236
|
+
auditInst.safeEmit(event);
|
|
237
|
+
} catch (_e) { /* audit best-effort */ }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function _readState(key) {
|
|
241
|
+
try {
|
|
242
|
+
var raw = await cache.get(_scopedKey(key));
|
|
243
|
+
return raw || null;
|
|
244
|
+
} catch (_e) {
|
|
245
|
+
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "get" });
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function _writeState(key, state, ttlMs) {
|
|
251
|
+
try {
|
|
252
|
+
await cache.set(_scopedKey(key), state, { ttlMs: ttlMs });
|
|
253
|
+
} catch (_e) {
|
|
254
|
+
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "set" });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function _deleteState(key) {
|
|
259
|
+
try {
|
|
260
|
+
await cache.del(_scopedKey(key));
|
|
261
|
+
} catch (_e) {
|
|
262
|
+
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "del" });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function _verdictFromState(state, now) {
|
|
267
|
+
if (!state) return { locked: false, attempts: 0 };
|
|
268
|
+
if (state.lockedUntil && state.lockedUntil > now) {
|
|
269
|
+
return {
|
|
270
|
+
locked: true,
|
|
271
|
+
attempts: state.attempts || 0,
|
|
272
|
+
lockedUntil: state.lockedUntil,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
return { locked: false, attempts: state.attempts || 0 };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ---- Public surface ----
|
|
279
|
+
|
|
280
|
+
async function recordFailure(key, callOpts) {
|
|
281
|
+
_requireKey(key);
|
|
282
|
+
callOpts = callOpts || {};
|
|
283
|
+
var now = clock();
|
|
284
|
+
var state = await _readState(key);
|
|
285
|
+
|
|
286
|
+
// If currently locked, the lockout itself counts — don't accumulate
|
|
287
|
+
// additional attempts during the cooldown. The caller saw locked=true
|
|
288
|
+
// from check() OR from a prior failure; this branch handles a caller
|
|
289
|
+
// that calls recordFailure() on a locked account anyway (e.g. they
|
|
290
|
+
// skipped check()).
|
|
291
|
+
if (state && state.lockedUntil && state.lockedUntil > now) {
|
|
292
|
+
_emitObs("auth.lockout.failure_during_lock", { namespace: namespace });
|
|
293
|
+
if (auditFailures) {
|
|
294
|
+
_emitAudit("auth.lockout.failure", key, "denied",
|
|
295
|
+
{ duringLock: true, attempts: state.attempts || 0,
|
|
296
|
+
lockNumber: state.lockNumber || 0,
|
|
297
|
+
lockedUntil: state.lockedUntil,
|
|
298
|
+
reason: callOpts.reason || null },
|
|
299
|
+
callOpts.req);
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
locked: true,
|
|
303
|
+
attempts: state.attempts || 0,
|
|
304
|
+
lockedUntil: state.lockedUntil,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Window decay: failures older than windowMs reset the counter.
|
|
309
|
+
// Lock-number persists across decay windows so an attacker who
|
|
310
|
+
// sleeps off a lockout doesn't get a fresh ladder rung.
|
|
311
|
+
if (state && state.lastFailureAt && (now - state.lastFailureAt) > windowMs) {
|
|
312
|
+
state = {
|
|
313
|
+
attempts: 0,
|
|
314
|
+
lockNumber: state.lockNumber || 0,
|
|
315
|
+
firstFailureAt: null,
|
|
316
|
+
lastFailureAt: null,
|
|
317
|
+
lockedUntil: null,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
var attempts = (state && state.attempts) || 0;
|
|
322
|
+
var lockNumber = (state && state.lockNumber) || 0;
|
|
323
|
+
attempts += 1;
|
|
324
|
+
|
|
325
|
+
var lockedUntil = null;
|
|
326
|
+
var newLock = false;
|
|
327
|
+
if (attempts >= maxAttempts) {
|
|
328
|
+
lockNumber += 1;
|
|
329
|
+
var dur = _resolveDuration(lockoutDurations, lockNumber);
|
|
330
|
+
lockedUntil = now + dur;
|
|
331
|
+
newLock = true;
|
|
332
|
+
attempts = 0; // counter resets — the lockout window IS the punishment
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
var newState = {
|
|
336
|
+
attempts: attempts,
|
|
337
|
+
lockNumber: lockNumber,
|
|
338
|
+
firstFailureAt: (state && state.firstFailureAt) || now,
|
|
339
|
+
lastFailureAt: now,
|
|
340
|
+
lockedUntil: lockedUntil,
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
// TTL: keep the state alive long enough that a follower-up failure
|
|
344
|
+
// after the window/lockout expires still finds the lockNumber. The
|
|
345
|
+
// longer of (windowMs after last failure) or (lockedUntil + windowMs).
|
|
346
|
+
var ttlMs = lockedUntil ? (lockedUntil - now + windowMs) : windowMs;
|
|
347
|
+
await _writeState(key, newState, ttlMs);
|
|
348
|
+
|
|
349
|
+
_emitObs("auth.lockout.failure", { namespace: namespace });
|
|
350
|
+
if (auditFailures) {
|
|
351
|
+
_emitAudit("auth.lockout.failure", key, "failure",
|
|
352
|
+
{ attempts: newState.attempts, lockNumber: lockNumber,
|
|
353
|
+
reason: callOpts.reason || null },
|
|
354
|
+
callOpts.req);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (newLock) {
|
|
358
|
+
_emitObs("auth.lockout.engaged", {
|
|
359
|
+
namespace: namespace,
|
|
360
|
+
lockNumber: String(lockNumber),
|
|
361
|
+
});
|
|
362
|
+
if (auditEngaged) {
|
|
363
|
+
_emitAudit("auth.lockout.engaged", key, "denied",
|
|
364
|
+
{ lockNumber: lockNumber, lockedUntil: lockedUntil,
|
|
365
|
+
durationMs: lockedUntil - now,
|
|
366
|
+
reason: callOpts.reason || null },
|
|
367
|
+
callOpts.req);
|
|
368
|
+
}
|
|
369
|
+
return { locked: true, attempts: 0, lockedUntil: lockedUntil };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return { locked: false, attempts: attempts };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function recordSuccess(key, callOpts) {
|
|
376
|
+
_requireKey(key);
|
|
377
|
+
callOpts = callOpts || {};
|
|
378
|
+
var state = await _readState(key);
|
|
379
|
+
var hadCounter = !!(state && (state.attempts > 0 || state.lockedUntil));
|
|
380
|
+
if (state) await _deleteState(key);
|
|
381
|
+
_emitObs("auth.lockout.success", { namespace: namespace });
|
|
382
|
+
if (auditSuccess) {
|
|
383
|
+
_emitAudit("auth.lockout.success", key, "success",
|
|
384
|
+
{ attemptsCleared: (state && state.attempts) || 0,
|
|
385
|
+
hadCounter: hadCounter },
|
|
386
|
+
callOpts.req);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async function check(key) {
|
|
391
|
+
_requireKey(key);
|
|
392
|
+
var state = await _readState(key);
|
|
393
|
+
return _verdictFromState(state, clock());
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function unlock(key, callOpts) {
|
|
397
|
+
_requireKey(key);
|
|
398
|
+
callOpts = callOpts || {};
|
|
399
|
+
var state = await _readState(key);
|
|
400
|
+
var now = clock();
|
|
401
|
+
var hadLock = !!(state && (
|
|
402
|
+
(state.lockedUntil && state.lockedUntil > now) ||
|
|
403
|
+
(state.attempts || 0) > 0
|
|
404
|
+
));
|
|
405
|
+
if (state) await _deleteState(key);
|
|
406
|
+
_emitObs("auth.lockout.unlock", { namespace: namespace });
|
|
407
|
+
if (auditUnlock) {
|
|
408
|
+
_emitAudit("auth.lockout.unlock", key, "success",
|
|
409
|
+
{ hadLock: hadLock,
|
|
410
|
+
priorAttempts: (state && state.attempts) || 0,
|
|
411
|
+
priorLockedUntil: (state && state.lockedUntil) || null,
|
|
412
|
+
priorLockNumber: (state && state.lockNumber) || 0,
|
|
413
|
+
reason: callOpts.reason || null },
|
|
414
|
+
callOpts.req);
|
|
415
|
+
}
|
|
416
|
+
return hadLock;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function attempts(key) {
|
|
420
|
+
_requireKey(key);
|
|
421
|
+
var state = await _readState(key);
|
|
422
|
+
return (state && state.attempts) || 0;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function close() {
|
|
426
|
+
// The cache is operator-owned; lockout doesn't close it. Provided
|
|
427
|
+
// for API symmetry with other primitives (cache.close, notify.close,
|
|
428
|
+
// etc.) so operator shutdown code can call close() uniformly.
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
recordFailure: recordFailure,
|
|
433
|
+
recordSuccess: recordSuccess,
|
|
434
|
+
check: check,
|
|
435
|
+
unlock: unlock,
|
|
436
|
+
attempts: attempts,
|
|
437
|
+
close: close,
|
|
438
|
+
namespace: namespace,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
module.exports = {
|
|
443
|
+
create: create,
|
|
444
|
+
LockoutError: LockoutError,
|
|
445
|
+
DEFAULTS: DEFAULTS,
|
|
446
|
+
};
|
package/lib/framework-error.js
CHANGED
|
@@ -161,6 +161,11 @@ var NotifyError = defineClass("NotifyError", { alwaysPermane
|
|
|
161
161
|
// (NaN clock, non-fn predicate, path-traversal tempDir prefix) and
|
|
162
162
|
// waitFor timeouts are programming bugs at test-write time.
|
|
163
163
|
var TestingError = defineClass("TestingError", { alwaysPermanent: true });
|
|
164
|
+
// LockoutError is alwaysPermanent: misconfig at create() and bad keys at
|
|
165
|
+
// recordFailure/recordSuccess/check/unlock are programming bugs. The
|
|
166
|
+
// "account is currently locked" condition is NOT an error — recordFailure
|
|
167
|
+
// returns { locked: true, lockedUntil } so the caller decides the response.
|
|
168
|
+
var LockoutError = defineClass("LockoutError", { alwaysPermanent: true });
|
|
164
169
|
|
|
165
170
|
module.exports = {
|
|
166
171
|
FrameworkError: FrameworkError,
|
|
@@ -186,4 +191,5 @@ module.exports = {
|
|
|
186
191
|
I18nError: I18nError,
|
|
187
192
|
NotifyError: NotifyError,
|
|
188
193
|
TestingError: TestingError,
|
|
194
|
+
LockoutError: LockoutError,
|
|
189
195
|
};
|
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
* multipart/form-data → req.body = { field: value }
|
|
16
16
|
* req.files = [{ field, filename,
|
|
17
17
|
* mimeType, path, size, hash }]
|
|
18
|
+
* req.filesRejected = [{ field,
|
|
19
|
+
* filename, mimeType, code, message }]
|
|
18
20
|
*
|
|
19
21
|
* Multipart parses incrementally — file parts stream to a tmp dir
|
|
20
22
|
* rather than buffering in memory. Per-file + total-request size caps
|
|
@@ -42,6 +44,33 @@
|
|
|
42
44
|
* fieldCount: 100,
|
|
43
45
|
* fieldSize: 1024 * 1024,
|
|
44
46
|
* mimeAllowlist: ["image/jpeg", "image/png", "application/pdf"], // null = any
|
|
47
|
+
*
|
|
48
|
+
* // Per-part predicate. Runs after sanitization + MIME checks but
|
|
49
|
+
* // BEFORE the tmp file opens. Rejected parts are SKIPPED — the body
|
|
50
|
+
* // bytes are consumed (we still must scan past them to find the
|
|
51
|
+
* // next boundary) but never written to disk; the part metadata
|
|
52
|
+
* // lands in req.filesRejected. Surviving files appear in req.files
|
|
53
|
+
* // as usual. Sync only — async filtering goes in the route handler.
|
|
54
|
+
* fileFilter: function (part) {
|
|
55
|
+
* // part = { field, filename, mimeType, partHeaders }
|
|
56
|
+
* // return true / undefined → accept
|
|
57
|
+
* // return false → reject silently (entry in req.filesRejected)
|
|
58
|
+
* // return { reject: true, code, message } → reject with custom info
|
|
59
|
+
* return part.field === "avatar" && part.mimeType.startsWith("image/");
|
|
60
|
+
* },
|
|
61
|
+
*
|
|
62
|
+
* // Per-field overrides. maxBytes overrides global fileSize for file
|
|
63
|
+
* // parts and fieldSize for text parts. mimeTypes overrides the
|
|
64
|
+
* // global mimeAllowlist for the named field; other fields still
|
|
65
|
+
* // use the global list.
|
|
66
|
+
* fields: {
|
|
67
|
+
* avatar: { maxBytes: 2 * 1024 * 1024, mimeTypes: ["image/jpeg", "image/png"] },
|
|
68
|
+
* document: { maxBytes: 25 * 1024 * 1024 },
|
|
69
|
+
* },
|
|
70
|
+
*
|
|
71
|
+
* // When wired, fileFilter rejections emit body-parser.multipart.file_rejected
|
|
72
|
+
* // on the audit chain with the field, filename, mime, and reason.
|
|
73
|
+
* audit: b.audit,
|
|
45
74
|
* },
|
|
46
75
|
* // Stash the raw bytes for webhook-signature paths that need to
|
|
47
76
|
* // verify the wire bytes rather than the parsed shape.
|
|
@@ -128,6 +157,9 @@ var DEFAULTS = Object.freeze({
|
|
|
128
157
|
fieldCount: 100,
|
|
129
158
|
fieldSize: C.BYTES.mib(1),
|
|
130
159
|
mimeAllowlist: null,
|
|
160
|
+
fileFilter: null, // fn({ field, filename, mimeType, partHeaders }) → bool | { reject, code, message }
|
|
161
|
+
fields: null, // per-field overrides: { name: { maxBytes?, mimeTypes? } }
|
|
162
|
+
audit: null, // when wired, file-rejection emits an audit event
|
|
131
163
|
contentTypes: ["multipart/form-data"],
|
|
132
164
|
},
|
|
133
165
|
});
|
|
@@ -446,6 +478,7 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
446
478
|
|
|
447
479
|
var fields = {};
|
|
448
480
|
var files = [];
|
|
481
|
+
var filesRejected = [];
|
|
449
482
|
var totalRead = 0;
|
|
450
483
|
var fileCount = 0;
|
|
451
484
|
var fieldCount = 0;
|
|
@@ -455,6 +488,9 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
455
488
|
var fieldLimit = opts.fieldCount;
|
|
456
489
|
var fieldSize = opts.fieldSize;
|
|
457
490
|
var mimeAllowlist = Array.isArray(opts.mimeAllowlist) ? opts.mimeAllowlist : null;
|
|
491
|
+
var fileFilter = typeof opts.fileFilter === "function" ? opts.fileFilter : null;
|
|
492
|
+
var perField = (opts.fields && typeof opts.fields === "object") ? opts.fields : null;
|
|
493
|
+
var auditInst = (opts.audit && typeof opts.audit.safeEmit === "function") ? opts.audit : null;
|
|
458
494
|
|
|
459
495
|
var state = MP_INITIAL;
|
|
460
496
|
var pending = Buffer.alloc(0);
|
|
@@ -467,6 +503,10 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
467
503
|
var currentSize = 0;
|
|
468
504
|
var currentHash = null;
|
|
469
505
|
var currentBuf = null; // for fields (in-memory accumulator)
|
|
506
|
+
var currentDiscarded = false; // true when fileFilter rejected the part — body bytes are
|
|
507
|
+
// still consumed (we have to read past them to find the next
|
|
508
|
+
// boundary) but never written to disk.
|
|
509
|
+
var currentEffectiveLimit = 0; // per-field-or-global cap; recomputed at part start.
|
|
470
510
|
|
|
471
511
|
function _resetCurrent() {
|
|
472
512
|
currentHeaders = null;
|
|
@@ -478,6 +518,28 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
478
518
|
currentSize = 0;
|
|
479
519
|
currentHash = null;
|
|
480
520
|
currentBuf = null;
|
|
521
|
+
currentDiscarded = false;
|
|
522
|
+
currentEffectiveLimit = 0;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function _emitRejection(field, filename, mimeType, code, message) {
|
|
526
|
+
filesRejected.push({
|
|
527
|
+
field: field,
|
|
528
|
+
filename: filename,
|
|
529
|
+
mimeType: mimeType,
|
|
530
|
+
code: code,
|
|
531
|
+
message: message || null,
|
|
532
|
+
});
|
|
533
|
+
if (auditInst) {
|
|
534
|
+
try {
|
|
535
|
+
auditInst.safeEmit({
|
|
536
|
+
action: "body-parser.multipart.file_rejected",
|
|
537
|
+
outcome: "denied",
|
|
538
|
+
resource: { kind: "multipart.file", id: field + (filename ? ":" + filename : "") },
|
|
539
|
+
metadata: { field: field, filename: filename, mimeType: mimeType, code: code, message: message || null },
|
|
540
|
+
});
|
|
541
|
+
} catch (_e) { /* audit best-effort */ }
|
|
542
|
+
}
|
|
481
543
|
}
|
|
482
544
|
|
|
483
545
|
function _cleanup() {
|
|
@@ -527,7 +589,7 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
527
589
|
if (pending.length < 2) return;
|
|
528
590
|
if (pending[0] === 0x2d && pending[1] === 0x2d) { // "--"
|
|
529
591
|
state = MP_DONE;
|
|
530
|
-
done(null, { fields: fields, files: files });
|
|
592
|
+
done(null, { fields: fields, files: files, filesRejected: filesRejected });
|
|
531
593
|
return;
|
|
532
594
|
}
|
|
533
595
|
if (pending[0] === 0x0d && pending[1] === 0x0a) { // "\r\n"
|
|
@@ -581,7 +643,20 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
581
643
|
return;
|
|
582
644
|
}
|
|
583
645
|
currentMime = currentHeaders["content-type"] || "application/octet-stream";
|
|
584
|
-
|
|
646
|
+
// Per-field MIME allowlist takes precedence over the global one
|
|
647
|
+
// for this field; global applies to fields without an entry.
|
|
648
|
+
var fieldRule = perField ? perField[currentField] : null;
|
|
649
|
+
var perFieldMime = (fieldRule && Array.isArray(fieldRule.mimeTypes))
|
|
650
|
+
? fieldRule.mimeTypes : null;
|
|
651
|
+
if (perFieldMime) {
|
|
652
|
+
if (perFieldMime.indexOf(currentMime) === -1) {
|
|
653
|
+
done(new BodyParserError("body-parser/multipart-mime-not-allowed",
|
|
654
|
+
"multipart file '" + currentField + "' MIME '" + currentMime +
|
|
655
|
+
"' is not on the per-field allowlist",
|
|
656
|
+
true, 415));
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
} else if (mimeAllowlist && mimeAllowlist.indexOf(currentMime) === -1) {
|
|
585
660
|
done(new BodyParserError("body-parser/multipart-mime-not-allowed",
|
|
586
661
|
"multipart file MIME '" + currentMime + "' is not on the allowlist",
|
|
587
662
|
true, 415));
|
|
@@ -594,6 +669,43 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
594
669
|
true, 413));
|
|
595
670
|
return;
|
|
596
671
|
}
|
|
672
|
+
// Per-field cap overrides global fileSize for this field.
|
|
673
|
+
currentEffectiveLimit = (fieldRule && typeof fieldRule.maxBytes === "number")
|
|
674
|
+
? fieldRule.maxBytes : fileSize;
|
|
675
|
+
|
|
676
|
+
// fileFilter runs AFTER sanitize + MIME checks but BEFORE the
|
|
677
|
+
// tmp file opens. Synchronous so the parser can decide between
|
|
678
|
+
// disk-write and discard-bytes without buffering the part.
|
|
679
|
+
if (fileFilter) {
|
|
680
|
+
var filterVerdict;
|
|
681
|
+
try {
|
|
682
|
+
filterVerdict = fileFilter({
|
|
683
|
+
field: currentField,
|
|
684
|
+
filename: currentFilename,
|
|
685
|
+
mimeType: currentMime,
|
|
686
|
+
partHeaders: currentHeaders,
|
|
687
|
+
});
|
|
688
|
+
} catch (e) {
|
|
689
|
+
done(new BodyParserError("body-parser/multipart-file-filter-throw",
|
|
690
|
+
"fileFilter threw: " + ((e && e.message) || String(e)),
|
|
691
|
+
true, 500));
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
if (filterVerdict === false ||
|
|
695
|
+
(filterVerdict && typeof filterVerdict === "object" && filterVerdict.reject)) {
|
|
696
|
+
var rejCode = (filterVerdict && filterVerdict.code) || "fileFilter";
|
|
697
|
+
var rejMessage = (filterVerdict && filterVerdict.message) || null;
|
|
698
|
+
_emitRejection(currentField, currentFilename, currentMime, rejCode, rejMessage);
|
|
699
|
+
// Read past the body bytes (we still must find the next
|
|
700
|
+
// boundary) but never open a tmp file or push to req.files.
|
|
701
|
+
currentDiscarded = true;
|
|
702
|
+
fileCount--; // doesn't count toward the limit since it didn't land
|
|
703
|
+
currentSize = 0;
|
|
704
|
+
state = MP_BODY;
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
597
709
|
// Generate the tmp path — never derived from the
|
|
598
710
|
// operator-supplied filename.
|
|
599
711
|
var unique = nodeCrypto.randomBytes(16).toString("hex");
|
|
@@ -616,6 +728,10 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
616
728
|
true, 413));
|
|
617
729
|
return;
|
|
618
730
|
}
|
|
731
|
+
// Per-field cap overrides global fieldSize for text parts too.
|
|
732
|
+
var textFieldRule = perField ? perField[currentField] : null;
|
|
733
|
+
currentEffectiveLimit = (textFieldRule && typeof textFieldRule.maxBytes === "number")
|
|
734
|
+
? textFieldRule.maxBytes : fieldSize;
|
|
619
735
|
currentBuf = [];
|
|
620
736
|
currentSize = 0;
|
|
621
737
|
}
|
|
@@ -640,12 +756,27 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
640
756
|
}
|
|
641
757
|
if (emitLen > 0) {
|
|
642
758
|
var bodyChunk = pending.slice(0, emitLen);
|
|
643
|
-
if (
|
|
759
|
+
if (currentDiscarded) {
|
|
760
|
+
// fileFilter rejected this part — read past the bytes to find
|
|
761
|
+
// the next boundary but never write to disk. totalSize still
|
|
762
|
+
// applies as a per-request DoS guard.
|
|
763
|
+
totalRead += bodyChunk.length;
|
|
764
|
+
if (totalRead > totalSize) {
|
|
765
|
+
done(new BodyParserError("body-parser/multipart-total-too-large",
|
|
766
|
+
"multipart total request size exceeds totalSize (" + totalSize + ")",
|
|
767
|
+
true, 413));
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
} else if (currentFd !== null) {
|
|
644
771
|
// File part — write to disk.
|
|
645
772
|
currentSize += bodyChunk.length;
|
|
646
|
-
if (currentSize >
|
|
773
|
+
if (currentSize > currentEffectiveLimit) {
|
|
774
|
+
var perFieldFile = (perField && perField[currentField] &&
|
|
775
|
+
typeof perField[currentField].maxBytes === "number");
|
|
647
776
|
done(new BodyParserError("body-parser/multipart-file-too-large",
|
|
648
|
-
"multipart file '" + currentField + "' exceeds
|
|
777
|
+
"multipart file '" + currentField + "' exceeds " +
|
|
778
|
+
(perFieldFile ? "per-field maxBytes" : "fileSize") +
|
|
779
|
+
" (" + currentEffectiveLimit + ")",
|
|
649
780
|
true, 413));
|
|
650
781
|
return;
|
|
651
782
|
}
|
|
@@ -669,11 +800,15 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
669
800
|
}
|
|
670
801
|
currentHash.update(bodyChunk);
|
|
671
802
|
} else {
|
|
672
|
-
// Field part — buffer in memory up to
|
|
803
|
+
// Field part — buffer in memory up to per-field-or-global cap.
|
|
673
804
|
currentSize += bodyChunk.length;
|
|
674
|
-
if (currentSize >
|
|
805
|
+
if (currentSize > currentEffectiveLimit) {
|
|
806
|
+
var perFieldText = (perField && perField[currentField] &&
|
|
807
|
+
typeof perField[currentField].maxBytes === "number");
|
|
675
808
|
done(new BodyParserError("body-parser/multipart-field-too-large",
|
|
676
|
-
"multipart field '" + currentField + "' exceeds
|
|
809
|
+
"multipart field '" + currentField + "' exceeds " +
|
|
810
|
+
(perFieldText ? "per-field maxBytes" : "fieldSize") +
|
|
811
|
+
" (" + currentEffectiveLimit + ")",
|
|
677
812
|
true, 413));
|
|
678
813
|
return;
|
|
679
814
|
}
|
|
@@ -692,7 +827,10 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
692
827
|
// Consume the boundary delimiter; transition to AFTER_BD.
|
|
693
828
|
pending = pending.slice(boundaryDelimBuf.length);
|
|
694
829
|
// Finalize the current part.
|
|
695
|
-
if (
|
|
830
|
+
if (currentDiscarded) {
|
|
831
|
+
// fileFilter rejected — already recorded in filesRejected; no
|
|
832
|
+
// tmp file was opened, nothing to clean up here.
|
|
833
|
+
} else if (currentFd !== null) {
|
|
696
834
|
try { fs.closeSync(currentFd); } catch (_e) {}
|
|
697
835
|
currentFd = null;
|
|
698
836
|
files.push({
|
|
@@ -723,6 +861,8 @@ async function _parseMultipart(req, opts, ctParams) {
|
|
|
723
861
|
currentSize = 0;
|
|
724
862
|
currentHash = null;
|
|
725
863
|
currentBuf = null;
|
|
864
|
+
currentDiscarded = false;
|
|
865
|
+
currentEffectiveLimit = 0;
|
|
726
866
|
state = MP_AFTER_BD;
|
|
727
867
|
continue;
|
|
728
868
|
}
|
|
@@ -804,6 +944,7 @@ function create(opts) {
|
|
|
804
944
|
var mpResult = await _parseMultipart(req, multipartOpts, ct.params);
|
|
805
945
|
req.body = mpResult.fields;
|
|
806
946
|
req.files = mpResult.files;
|
|
947
|
+
req.filesRejected = mpResult.filesRejected || [];
|
|
807
948
|
// Cleanup tmp files when the response finishes / closes / errors,
|
|
808
949
|
// regardless of whether the handler returned cleanly. Operators
|
|
809
950
|
// who want to KEEP a file move it elsewhere inside the handler.
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
* Cross-Origin-Opener-Policy: same-origin
|
|
13
13
|
* Cross-Origin-Embedder-Policy: require-corp (off by default — breaks images from CDNs)
|
|
14
14
|
* Cross-Origin-Resource-Policy: same-origin
|
|
15
|
+
* Origin-Agent-Cluster: ?1 — origin-keyed agent cluster; extra process isolation
|
|
16
|
+
* X-DNS-Prefetch-Control: off — don't pre-resolve DNS for off-page links
|
|
15
17
|
* Content-Security-Policy — operator-supplied; framework provides a safe default that
|
|
16
18
|
* only allows same-origin and prevents inline scripts
|
|
17
19
|
*
|
|
@@ -21,13 +23,15 @@
|
|
|
21
23
|
*
|
|
22
24
|
* Options:
|
|
23
25
|
* {
|
|
24
|
-
* hsts:
|
|
25
|
-
* contentTypeOptions:
|
|
26
|
-
* frameOptions:
|
|
27
|
-
* referrerPolicy:
|
|
28
|
-
* permissionsPolicy:
|
|
29
|
-
* coop / coep / corp:
|
|
30
|
-
*
|
|
26
|
+
* hsts: '<value>' or false to disable
|
|
27
|
+
* contentTypeOptions: 'nosniff' or false
|
|
28
|
+
* frameOptions: 'DENY' | 'SAMEORIGIN' or false
|
|
29
|
+
* referrerPolicy: '<value>' or false
|
|
30
|
+
* permissionsPolicy: '<value>' or false
|
|
31
|
+
* coop / coep / corp: '<value>' or false
|
|
32
|
+
* originAgentCluster: '?1' (default) or '?0' or false
|
|
33
|
+
* dnsPrefetchControl: 'off' (default) or 'on' or false
|
|
34
|
+
* csp: '<full CSP string>' or false to disable
|
|
31
35
|
* }
|
|
32
36
|
*/
|
|
33
37
|
|
|
@@ -57,7 +61,8 @@ function create(opts) {
|
|
|
57
61
|
opts = opts || {};
|
|
58
62
|
validateOpts(opts, [
|
|
59
63
|
"hsts", "contentTypeOptions", "frameOptions", "referrerPolicy",
|
|
60
|
-
"permissionsPolicy", "coop", "coep", "corp",
|
|
64
|
+
"permissionsPolicy", "coop", "coep", "corp",
|
|
65
|
+
"originAgentCluster", "dnsPrefetchControl", "csp",
|
|
61
66
|
], "middleware.securityHeaders");
|
|
62
67
|
var hsts = opts.hsts === undefined ? "max-age=63072000; includeSubDomains; preload" : opts.hsts;
|
|
63
68
|
var ctOpts = opts.contentTypeOptions === undefined ? "nosniff" : opts.contentTypeOptions;
|
|
@@ -67,6 +72,8 @@ function create(opts) {
|
|
|
67
72
|
var coop = opts.coop === undefined ? "same-origin" : opts.coop;
|
|
68
73
|
var coep = opts.coep === undefined ? false : opts.coep;
|
|
69
74
|
var corp = opts.corp === undefined ? "same-origin" : opts.corp;
|
|
75
|
+
var oac = opts.originAgentCluster === undefined ? "?1" : opts.originAgentCluster;
|
|
76
|
+
var dpc = opts.dnsPrefetchControl === undefined ? "off" : opts.dnsPrefetchControl;
|
|
70
77
|
var csp = opts.csp === undefined ? DEFAULT_CSP : opts.csp;
|
|
71
78
|
|
|
72
79
|
return function securityHeaders(req, res, next) {
|
|
@@ -79,6 +86,8 @@ function create(opts) {
|
|
|
79
86
|
if (coop) res.setHeader("Cross-Origin-Opener-Policy", coop);
|
|
80
87
|
if (coep) res.setHeader("Cross-Origin-Embedder-Policy", coep);
|
|
81
88
|
if (corp) res.setHeader("Cross-Origin-Resource-Policy", corp);
|
|
89
|
+
if (oac) res.setHeader("Origin-Agent-Cluster", oac);
|
|
90
|
+
if (dpc) res.setHeader("X-DNS-Prefetch-Control", dpc);
|
|
82
91
|
if (csp) res.setHeader("Content-Security-Policy", csp);
|
|
83
92
|
next();
|
|
84
93
|
};
|