@blamejs/core 0.7.1 → 0.7.18
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 +423 -389
- package/README.md +150 -149
- package/bin/blamejs.js +0 -0
- package/index.js +308 -282
- package/lib/api-key.js +660 -672
- package/lib/api-snapshot.js +338 -338
- package/lib/app-shutdown.js +385 -385
- package/lib/app.js +365 -365
- package/lib/archive.js +250 -250
- package/lib/atomic-file.js +544 -544
- package/lib/audit-chain.js +177 -177
- package/lib/audit-sign.js +344 -344
- package/lib/audit-tools.js +677 -677
- package/lib/audit.js +766 -766
- package/lib/auth/jwt.js +311 -311
- package/lib/auth/lockout.js +436 -436
- package/lib/auth/oauth.js +721 -721
- package/lib/auth/passkey.js +181 -181
- package/lib/auth/password.js +594 -594
- package/lib/backup/bundle.js +217 -217
- package/lib/backup/crypto.js +176 -176
- package/lib/backup/index.js +515 -515
- package/lib/backup/manifest.js +282 -282
- package/lib/break-glass.js +1338 -1338
- package/lib/bundler.js +441 -441
- package/lib/cache-redis.js +256 -266
- package/lib/cache.js +1206 -1211
- package/lib/canonical-json.js +115 -115
- package/lib/chain-writer.js +234 -234
- package/lib/cli-helpers.js +206 -206
- package/lib/cli.js +2334 -2334
- package/lib/cluster-provider-db.js +317 -317
- package/lib/cluster-storage.js +226 -226
- package/lib/cluster.js +703 -703
- package/lib/codepoint-class.js +196 -0
- package/lib/config-drift.js +301 -301
- package/lib/consent.js +222 -222
- package/lib/constants.js +191 -191
- package/lib/cookies.js +315 -315
- package/lib/credential-hash.js +322 -322
- package/lib/crypto.js +266 -266
- package/lib/csv.js +275 -286
- package/lib/db-declare-row-policy.js +267 -267
- package/lib/db-declare-view.js +420 -421
- package/lib/db-query.js +406 -406
- package/lib/db-schema.js +319 -319
- package/lib/db.js +1288 -1288
- package/lib/deprecate.js +222 -222
- package/lib/dev.js +335 -335
- package/lib/dual-control.js +473 -473
- package/lib/error-page.js +420 -420
- package/lib/external-db-migrate.js +441 -441
- package/lib/external-db.js +1061 -1061
- package/lib/file-type.js +273 -273
- package/lib/file-upload.js +1136 -0
- package/lib/forms.js +422 -422
- package/lib/framework-error.js +293 -202
- package/lib/framework-schema.js +717 -717
- package/lib/gate-contract.js +971 -0
- package/lib/guard-all.js +405 -0
- package/lib/guard-archive.js +739 -0
- package/lib/guard-csv.js +816 -0
- package/lib/guard-email.js +744 -0
- package/lib/guard-filename.js +724 -0
- package/lib/guard-html.js +976 -0
- package/lib/guard-json.js +729 -0
- package/lib/guard-markdown.js +586 -0
- package/lib/guard-svg.js +976 -0
- package/lib/guard-xml.js +405 -0
- package/lib/guard-yaml.js +529 -0
- package/lib/handlers.js +350 -350
- package/lib/http-client-cookie-jar.js +508 -508
- package/lib/http-client.js +1195 -1195
- package/lib/i18n.js +878 -878
- package/lib/jobs.js +185 -185
- package/lib/log-stream-cloudwatch.js +369 -369
- package/lib/log-stream-local.js +146 -146
- package/lib/log-stream-otlp-grpc.js +410 -410
- package/lib/log-stream-otlp.js +286 -286
- package/lib/log-stream-syslog.js +302 -302
- package/lib/log-stream-webhook.js +199 -199
- package/lib/log-stream.js +330 -330
- package/lib/log.js +500 -500
- package/lib/mail-bounce.js +528 -528
- package/lib/mail-dkim.js +369 -362
- package/lib/mail.js +981 -962
- package/lib/metrics.js +683 -683
- package/lib/middleware/api-encrypt.js +936 -573
- package/lib/middleware/attach-user.js +157 -157
- package/lib/middleware/body-parser.js +1170 -1091
- package/lib/middleware/bot-guard.js +178 -178
- package/lib/middleware/compression.js +452 -452
- package/lib/middleware/cors.js +314 -314
- package/lib/middleware/csp-nonce.js +348 -348
- package/lib/middleware/csrf-protect.js +316 -316
- package/lib/middleware/db-role-for.js +264 -269
- package/lib/middleware/health.js +392 -392
- package/lib/middleware/index.js +79 -79
- package/lib/middleware/rate-limit.js +358 -358
- package/lib/middleware/request-id.js +61 -61
- package/lib/middleware/request-log.js +168 -168
- package/lib/middleware/require-auth.js +104 -104
- package/lib/middleware/security-headers.js +116 -116
- package/lib/middleware/sse.js +166 -166
- package/lib/migrations.js +383 -383
- package/lib/mtls-ca.js +518 -518
- package/lib/mtls-engine-default.js +481 -481
- package/lib/network-dns.js +632 -632
- package/lib/network-heartbeat.js +290 -290
- package/lib/network-nts.js +574 -574
- package/lib/network-proxy.js +265 -265
- package/lib/network-tls.js +328 -328
- package/lib/network.js +233 -233
- package/lib/notify.js +612 -614
- package/lib/ntp-check.js +229 -229
- package/lib/numeric-bounds.js +111 -91
- package/lib/object-store/azure-blob-bucket-ops.js +349 -349
- package/lib/object-store/azure-blob.js +488 -451
- package/lib/object-store/gcs-bucket-ops.js +351 -351
- package/lib/object-store/gcs.js +519 -479
- package/lib/object-store/http-put.js +153 -153
- package/lib/object-store/index.js +197 -197
- package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
- package/lib/object-store/sigv4.js +903 -855
- package/lib/observability.js +151 -151
- package/lib/otel-export.js +269 -269
- package/lib/pagination.js +464 -464
- package/lib/parsers/index.js +80 -80
- package/lib/parsers/safe-env.js +642 -642
- package/lib/parsers/safe-ini.js +292 -292
- package/lib/parsers/safe-toml.js +784 -784
- package/lib/parsers/safe-xml.js +390 -390
- package/lib/parsers/safe-yaml.js +1015 -1015
- package/lib/permissions.js +708 -708
- package/lib/pqc-agent.js +87 -87
- package/lib/pqc-gate.js +279 -279
- package/lib/protobuf-encoder.js +190 -190
- package/lib/protocol-dispatcher.js +161 -161
- package/lib/pubsub-redis.js +167 -177
- package/lib/pubsub.js +429 -429
- package/lib/queue-local.js +476 -476
- package/lib/queue-redis.js +745 -752
- package/lib/queue-sqs.js +319 -319
- package/lib/queue.js +695 -695
- package/lib/redis-client.js +519 -489
- package/lib/request-helpers.js +340 -336
- package/lib/restore-bundle.js +237 -237
- package/lib/restore-rollback.js +259 -259
- package/lib/restore.js +409 -409
- package/lib/retry.js +376 -376
- package/lib/router.js +748 -748
- package/lib/safe-async.js +735 -735
- package/lib/safe-buffer.js +237 -237
- package/lib/safe-json.js +541 -541
- package/lib/safe-schema.js +1266 -1266
- package/lib/safe-url.js +159 -159
- package/lib/scheduler.js +706 -706
- package/lib/security-assert.js +373 -373
- package/lib/seeders.js +618 -630
- package/lib/session.js +478 -478
- package/lib/slug.js +269 -269
- package/lib/ssrf-guard.js +401 -401
- package/lib/static.js +879 -114
- package/lib/storage.js +471 -471
- package/lib/subject.js +281 -281
- package/lib/template.js +791 -791
- package/lib/testing.js +798 -798
- package/lib/time.js +310 -310
- package/lib/totp.js +302 -302
- package/lib/tracing.js +494 -494
- package/lib/uuid.js +132 -132
- package/lib/validate-opts.js +340 -270
- package/lib/vault/index.js +308 -308
- package/lib/vault/rotate.js +784 -784
- package/lib/vault/wrap.js +296 -296
- package/lib/vendor/noble-ciphers.cjs +9 -9
- package/lib/webhook.js +595 -598
- package/lib/websocket.js +1048 -1048
- package/package.json +77 -77
- package/sbom.cyclonedx.json +7 -7
package/lib/auth/lockout.js
CHANGED
|
@@ -1,436 +1,436 @@
|
|
|
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
|
-
validateOpts.auditShape(opts.audit, "auth.lockout.create", LockoutError);
|
|
188
|
-
validateOpts.observabilityShape(opts.observability, "auth.lockout.create", LockoutError);
|
|
189
|
-
validateOpts.optionalFunction(opts.clock, "auth.lockout.create: clock", LockoutError);
|
|
190
|
-
|
|
191
|
-
var cache = opts.cache;
|
|
192
|
-
var namespace = opts.namespace;
|
|
193
|
-
var auditInst = opts.audit || null;
|
|
194
|
-
var obsInst = opts.observability || null;
|
|
195
|
-
var clock = opts.clock || Date.now;
|
|
196
|
-
var auditFailures = opts.auditFailures !== undefined ? !!opts.auditFailures : DEFAULTS.auditFailures;
|
|
197
|
-
var auditEngaged = opts.auditEngaged !== undefined ? !!opts.auditEngaged : DEFAULTS.auditEngaged;
|
|
198
|
-
var auditSuccess = opts.auditSuccess !== undefined ? !!opts.auditSuccess : DEFAULTS.auditSuccess;
|
|
199
|
-
var auditUnlock = opts.auditUnlock !== undefined ? !!opts.auditUnlock : DEFAULTS.auditUnlock;
|
|
200
|
-
|
|
201
|
-
function _scopedKey(key) { return namespace + ":" + key; }
|
|
202
|
-
|
|
203
|
-
function _emitObs(name, labels) {
|
|
204
|
-
var sink = obsInst || _safeGlobalObs();
|
|
205
|
-
if (!sink) return;
|
|
206
|
-
try { sink.event(name, 1, labels); } catch (_e) { /* observability is best-effort */ }
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
// Fall back to the framework's global observability registry when the
|
|
210
|
-
// operator didn't pass their own. event() is a no-op when no registry
|
|
211
|
-
// is wired, so this is zero-cost in apps without observability.
|
|
212
|
-
function _safeGlobalObs() {
|
|
213
|
-
try { return observability(); } catch (_e) { return null; }
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
function _emitAudit(action, key, outcome, metadata, req) {
|
|
217
|
-
if (!auditInst) return;
|
|
218
|
-
try {
|
|
219
|
-
var event = {
|
|
220
|
-
action: action,
|
|
221
|
-
outcome: outcome,
|
|
222
|
-
resource: { kind: "auth.lockout", id: namespace + ":" + key },
|
|
223
|
-
metadata: metadata || {},
|
|
224
|
-
};
|
|
225
|
-
if (req) event.actor = requestHelpers.extractActorContext(req);
|
|
226
|
-
auditInst.safeEmit(event);
|
|
227
|
-
} catch (_e) { /* audit best-effort */ }
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
async function _readState(key) {
|
|
231
|
-
try {
|
|
232
|
-
var raw = await cache.get(_scopedKey(key));
|
|
233
|
-
return raw || null;
|
|
234
|
-
} catch (_e) {
|
|
235
|
-
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "get" });
|
|
236
|
-
return null;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
async function _writeState(key, state, ttlMs) {
|
|
241
|
-
try {
|
|
242
|
-
await cache.set(_scopedKey(key), state, { ttlMs: ttlMs });
|
|
243
|
-
} catch (_e) {
|
|
244
|
-
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "set" });
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
async function _deleteState(key) {
|
|
249
|
-
try {
|
|
250
|
-
await cache.del(_scopedKey(key));
|
|
251
|
-
} catch (_e) {
|
|
252
|
-
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "del" });
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function _verdictFromState(state, now) {
|
|
257
|
-
if (!state) return { locked: false, attempts: 0 };
|
|
258
|
-
if (state.lockedUntil && state.lockedUntil > now) {
|
|
259
|
-
return {
|
|
260
|
-
locked: true,
|
|
261
|
-
attempts: state.attempts || 0,
|
|
262
|
-
lockedUntil: state.lockedUntil,
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
return { locked: false, attempts: state.attempts || 0 };
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// ---- Public surface ----
|
|
269
|
-
|
|
270
|
-
async function recordFailure(key, callOpts) {
|
|
271
|
-
_requireKey(key);
|
|
272
|
-
callOpts = callOpts || {};
|
|
273
|
-
var now = clock();
|
|
274
|
-
var state = await _readState(key);
|
|
275
|
-
|
|
276
|
-
// If currently locked, the lockout itself counts — don't accumulate
|
|
277
|
-
// additional attempts during the cooldown. The caller saw locked=true
|
|
278
|
-
// from check() OR from a prior failure; this branch handles a caller
|
|
279
|
-
// that calls recordFailure() on a locked account anyway (e.g. they
|
|
280
|
-
// skipped check()).
|
|
281
|
-
if (state && state.lockedUntil && state.lockedUntil > now) {
|
|
282
|
-
_emitObs("auth.lockout.failure_during_lock", { namespace: namespace });
|
|
283
|
-
if (auditFailures) {
|
|
284
|
-
_emitAudit("auth.lockout.failure", key, "denied",
|
|
285
|
-
{ duringLock: true, attempts: state.attempts || 0,
|
|
286
|
-
lockNumber: state.lockNumber || 0,
|
|
287
|
-
lockedUntil: state.lockedUntil,
|
|
288
|
-
reason: callOpts.reason || null },
|
|
289
|
-
callOpts.req);
|
|
290
|
-
}
|
|
291
|
-
return {
|
|
292
|
-
locked: true,
|
|
293
|
-
attempts: state.attempts || 0,
|
|
294
|
-
lockedUntil: state.lockedUntil,
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
// Window decay: failures older than windowMs reset the counter.
|
|
299
|
-
// Lock-number persists across decay windows so an attacker who
|
|
300
|
-
// sleeps off a lockout doesn't get a fresh ladder rung.
|
|
301
|
-
if (state && state.lastFailureAt && (now - state.lastFailureAt) > windowMs) {
|
|
302
|
-
state = {
|
|
303
|
-
attempts: 0,
|
|
304
|
-
lockNumber: state.lockNumber || 0,
|
|
305
|
-
firstFailureAt: null,
|
|
306
|
-
lastFailureAt: null,
|
|
307
|
-
lockedUntil: null,
|
|
308
|
-
};
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
var attempts = (state && state.attempts) || 0;
|
|
312
|
-
var lockNumber = (state && state.lockNumber) || 0;
|
|
313
|
-
attempts += 1;
|
|
314
|
-
|
|
315
|
-
var lockedUntil = null;
|
|
316
|
-
var newLock = false;
|
|
317
|
-
if (attempts >= maxAttempts) {
|
|
318
|
-
lockNumber += 1;
|
|
319
|
-
var dur = _resolveDuration(lockoutDurations, lockNumber);
|
|
320
|
-
lockedUntil = now + dur;
|
|
321
|
-
newLock = true;
|
|
322
|
-
attempts = 0; // counter resets — the lockout window IS the punishment
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
var newState = {
|
|
326
|
-
attempts: attempts,
|
|
327
|
-
lockNumber: lockNumber,
|
|
328
|
-
firstFailureAt: (state && state.firstFailureAt) || now,
|
|
329
|
-
lastFailureAt: now,
|
|
330
|
-
lockedUntil: lockedUntil,
|
|
331
|
-
};
|
|
332
|
-
|
|
333
|
-
// TTL: keep the state alive long enough that a follower-up failure
|
|
334
|
-
// after the window/lockout expires still finds the lockNumber. The
|
|
335
|
-
// longer of (windowMs after last failure) or (lockedUntil + windowMs).
|
|
336
|
-
var ttlMs = lockedUntil ? (lockedUntil - now + windowMs) : windowMs;
|
|
337
|
-
await _writeState(key, newState, ttlMs);
|
|
338
|
-
|
|
339
|
-
_emitObs("auth.lockout.failure", { namespace: namespace });
|
|
340
|
-
if (auditFailures) {
|
|
341
|
-
_emitAudit("auth.lockout.failure", key, "failure",
|
|
342
|
-
{ attempts: newState.attempts, lockNumber: lockNumber,
|
|
343
|
-
reason: callOpts.reason || null },
|
|
344
|
-
callOpts.req);
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
if (newLock) {
|
|
348
|
-
_emitObs("auth.lockout.engaged", {
|
|
349
|
-
namespace: namespace,
|
|
350
|
-
lockNumber: String(lockNumber),
|
|
351
|
-
});
|
|
352
|
-
if (auditEngaged) {
|
|
353
|
-
_emitAudit("auth.lockout.engaged", key, "denied",
|
|
354
|
-
{ lockNumber: lockNumber, lockedUntil: lockedUntil,
|
|
355
|
-
durationMs: lockedUntil - now,
|
|
356
|
-
reason: callOpts.reason || null },
|
|
357
|
-
callOpts.req);
|
|
358
|
-
}
|
|
359
|
-
return { locked: true, attempts: 0, lockedUntil: lockedUntil };
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
return { locked: false, attempts: attempts };
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
async function recordSuccess(key, callOpts) {
|
|
366
|
-
_requireKey(key);
|
|
367
|
-
callOpts = callOpts || {};
|
|
368
|
-
var state = await _readState(key);
|
|
369
|
-
var hadCounter = !!(state && (state.attempts > 0 || state.lockedUntil));
|
|
370
|
-
if (state) await _deleteState(key);
|
|
371
|
-
_emitObs("auth.lockout.success", { namespace: namespace });
|
|
372
|
-
if (auditSuccess) {
|
|
373
|
-
_emitAudit("auth.lockout.success", key, "success",
|
|
374
|
-
{ attemptsCleared: (state && state.attempts) || 0,
|
|
375
|
-
hadCounter: hadCounter },
|
|
376
|
-
callOpts.req);
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
async function check(key) {
|
|
381
|
-
_requireKey(key);
|
|
382
|
-
var state = await _readState(key);
|
|
383
|
-
return _verdictFromState(state, clock());
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
async function unlock(key, callOpts) {
|
|
387
|
-
_requireKey(key);
|
|
388
|
-
callOpts = callOpts || {};
|
|
389
|
-
var state = await _readState(key);
|
|
390
|
-
var now = clock();
|
|
391
|
-
var hadLock = !!(state && (
|
|
392
|
-
(state.lockedUntil && state.lockedUntil > now) ||
|
|
393
|
-
(state.attempts || 0) > 0
|
|
394
|
-
));
|
|
395
|
-
if (state) await _deleteState(key);
|
|
396
|
-
_emitObs("auth.lockout.unlock", { namespace: namespace });
|
|
397
|
-
if (auditUnlock) {
|
|
398
|
-
_emitAudit("auth.lockout.unlock", key, "success",
|
|
399
|
-
{ hadLock: hadLock,
|
|
400
|
-
priorAttempts: (state && state.attempts) || 0,
|
|
401
|
-
priorLockedUntil: (state && state.lockedUntil) || null,
|
|
402
|
-
priorLockNumber: (state && state.lockNumber) || 0,
|
|
403
|
-
reason: callOpts.reason || null },
|
|
404
|
-
callOpts.req);
|
|
405
|
-
}
|
|
406
|
-
return hadLock;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
async function attempts(key) {
|
|
410
|
-
_requireKey(key);
|
|
411
|
-
var state = await _readState(key);
|
|
412
|
-
return (state && state.attempts) || 0;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
async function close() {
|
|
416
|
-
// The cache is operator-owned; lockout doesn't close it. Provided
|
|
417
|
-
// for API symmetry with other primitives (cache.close, notify.close,
|
|
418
|
-
// etc.) so operator shutdown code can call close() uniformly.
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
return {
|
|
422
|
-
recordFailure: recordFailure,
|
|
423
|
-
recordSuccess: recordSuccess,
|
|
424
|
-
check: check,
|
|
425
|
-
unlock: unlock,
|
|
426
|
-
attempts: attempts,
|
|
427
|
-
close: close,
|
|
428
|
-
namespace: namespace,
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
module.exports = {
|
|
433
|
-
create: create,
|
|
434
|
-
LockoutError: LockoutError,
|
|
435
|
-
DEFAULTS: DEFAULTS,
|
|
436
|
-
};
|
|
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
|
+
validateOpts.auditShape(opts.audit, "auth.lockout.create", LockoutError);
|
|
188
|
+
validateOpts.observabilityShape(opts.observability, "auth.lockout.create", LockoutError);
|
|
189
|
+
validateOpts.optionalFunction(opts.clock, "auth.lockout.create: clock", LockoutError);
|
|
190
|
+
|
|
191
|
+
var cache = opts.cache;
|
|
192
|
+
var namespace = opts.namespace;
|
|
193
|
+
var auditInst = opts.audit || null;
|
|
194
|
+
var obsInst = opts.observability || null;
|
|
195
|
+
var clock = opts.clock || Date.now;
|
|
196
|
+
var auditFailures = opts.auditFailures !== undefined ? !!opts.auditFailures : DEFAULTS.auditFailures;
|
|
197
|
+
var auditEngaged = opts.auditEngaged !== undefined ? !!opts.auditEngaged : DEFAULTS.auditEngaged;
|
|
198
|
+
var auditSuccess = opts.auditSuccess !== undefined ? !!opts.auditSuccess : DEFAULTS.auditSuccess;
|
|
199
|
+
var auditUnlock = opts.auditUnlock !== undefined ? !!opts.auditUnlock : DEFAULTS.auditUnlock;
|
|
200
|
+
|
|
201
|
+
function _scopedKey(key) { return namespace + ":" + key; }
|
|
202
|
+
|
|
203
|
+
function _emitObs(name, labels) {
|
|
204
|
+
var sink = obsInst || _safeGlobalObs();
|
|
205
|
+
if (!sink) return;
|
|
206
|
+
try { sink.event(name, 1, labels); } catch (_e) { /* observability is best-effort */ }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Fall back to the framework's global observability registry when the
|
|
210
|
+
// operator didn't pass their own. event() is a no-op when no registry
|
|
211
|
+
// is wired, so this is zero-cost in apps without observability.
|
|
212
|
+
function _safeGlobalObs() {
|
|
213
|
+
try { return observability(); } catch (_e) { return null; }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function _emitAudit(action, key, outcome, metadata, req) {
|
|
217
|
+
if (!auditInst) return;
|
|
218
|
+
try {
|
|
219
|
+
var event = {
|
|
220
|
+
action: action,
|
|
221
|
+
outcome: outcome,
|
|
222
|
+
resource: { kind: "auth.lockout", id: namespace + ":" + key },
|
|
223
|
+
metadata: metadata || {},
|
|
224
|
+
};
|
|
225
|
+
if (req) event.actor = requestHelpers.extractActorContext(req);
|
|
226
|
+
auditInst.safeEmit(event);
|
|
227
|
+
} catch (_e) { /* audit best-effort */ }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function _readState(key) {
|
|
231
|
+
try {
|
|
232
|
+
var raw = await cache.get(_scopedKey(key));
|
|
233
|
+
return raw || null;
|
|
234
|
+
} catch (_e) {
|
|
235
|
+
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "get" });
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function _writeState(key, state, ttlMs) {
|
|
241
|
+
try {
|
|
242
|
+
await cache.set(_scopedKey(key), state, { ttlMs: ttlMs });
|
|
243
|
+
} catch (_e) {
|
|
244
|
+
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "set" });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function _deleteState(key) {
|
|
249
|
+
try {
|
|
250
|
+
await cache.del(_scopedKey(key));
|
|
251
|
+
} catch (_e) {
|
|
252
|
+
_emitObs("auth.lockout.cache_error", { namespace: namespace, op: "del" });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function _verdictFromState(state, now) {
|
|
257
|
+
if (!state) return { locked: false, attempts: 0 };
|
|
258
|
+
if (state.lockedUntil && state.lockedUntil > now) {
|
|
259
|
+
return {
|
|
260
|
+
locked: true,
|
|
261
|
+
attempts: state.attempts || 0,
|
|
262
|
+
lockedUntil: state.lockedUntil,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
return { locked: false, attempts: state.attempts || 0 };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ---- Public surface ----
|
|
269
|
+
|
|
270
|
+
async function recordFailure(key, callOpts) {
|
|
271
|
+
_requireKey(key);
|
|
272
|
+
callOpts = callOpts || {};
|
|
273
|
+
var now = clock();
|
|
274
|
+
var state = await _readState(key);
|
|
275
|
+
|
|
276
|
+
// If currently locked, the lockout itself counts — don't accumulate
|
|
277
|
+
// additional attempts during the cooldown. The caller saw locked=true
|
|
278
|
+
// from check() OR from a prior failure; this branch handles a caller
|
|
279
|
+
// that calls recordFailure() on a locked account anyway (e.g. they
|
|
280
|
+
// skipped check()).
|
|
281
|
+
if (state && state.lockedUntil && state.lockedUntil > now) {
|
|
282
|
+
_emitObs("auth.lockout.failure_during_lock", { namespace: namespace });
|
|
283
|
+
if (auditFailures) {
|
|
284
|
+
_emitAudit("auth.lockout.failure", key, "denied",
|
|
285
|
+
{ duringLock: true, attempts: state.attempts || 0,
|
|
286
|
+
lockNumber: state.lockNumber || 0,
|
|
287
|
+
lockedUntil: state.lockedUntil,
|
|
288
|
+
reason: callOpts.reason || null },
|
|
289
|
+
callOpts.req);
|
|
290
|
+
}
|
|
291
|
+
return {
|
|
292
|
+
locked: true,
|
|
293
|
+
attempts: state.attempts || 0,
|
|
294
|
+
lockedUntil: state.lockedUntil,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Window decay: failures older than windowMs reset the counter.
|
|
299
|
+
// Lock-number persists across decay windows so an attacker who
|
|
300
|
+
// sleeps off a lockout doesn't get a fresh ladder rung.
|
|
301
|
+
if (state && state.lastFailureAt && (now - state.lastFailureAt) > windowMs) {
|
|
302
|
+
state = {
|
|
303
|
+
attempts: 0,
|
|
304
|
+
lockNumber: state.lockNumber || 0,
|
|
305
|
+
firstFailureAt: null,
|
|
306
|
+
lastFailureAt: null,
|
|
307
|
+
lockedUntil: null,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
var attempts = (state && state.attempts) || 0;
|
|
312
|
+
var lockNumber = (state && state.lockNumber) || 0;
|
|
313
|
+
attempts += 1;
|
|
314
|
+
|
|
315
|
+
var lockedUntil = null;
|
|
316
|
+
var newLock = false;
|
|
317
|
+
if (attempts >= maxAttempts) {
|
|
318
|
+
lockNumber += 1;
|
|
319
|
+
var dur = _resolveDuration(lockoutDurations, lockNumber);
|
|
320
|
+
lockedUntil = now + dur;
|
|
321
|
+
newLock = true;
|
|
322
|
+
attempts = 0; // counter resets — the lockout window IS the punishment
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
var newState = {
|
|
326
|
+
attempts: attempts,
|
|
327
|
+
lockNumber: lockNumber,
|
|
328
|
+
firstFailureAt: (state && state.firstFailureAt) || now,
|
|
329
|
+
lastFailureAt: now,
|
|
330
|
+
lockedUntil: lockedUntil,
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
// TTL: keep the state alive long enough that a follower-up failure
|
|
334
|
+
// after the window/lockout expires still finds the lockNumber. The
|
|
335
|
+
// longer of (windowMs after last failure) or (lockedUntil + windowMs).
|
|
336
|
+
var ttlMs = lockedUntil ? (lockedUntil - now + windowMs) : windowMs;
|
|
337
|
+
await _writeState(key, newState, ttlMs);
|
|
338
|
+
|
|
339
|
+
_emitObs("auth.lockout.failure", { namespace: namespace });
|
|
340
|
+
if (auditFailures) {
|
|
341
|
+
_emitAudit("auth.lockout.failure", key, "failure",
|
|
342
|
+
{ attempts: newState.attempts, lockNumber: lockNumber,
|
|
343
|
+
reason: callOpts.reason || null },
|
|
344
|
+
callOpts.req);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (newLock) {
|
|
348
|
+
_emitObs("auth.lockout.engaged", {
|
|
349
|
+
namespace: namespace,
|
|
350
|
+
lockNumber: String(lockNumber),
|
|
351
|
+
});
|
|
352
|
+
if (auditEngaged) {
|
|
353
|
+
_emitAudit("auth.lockout.engaged", key, "denied",
|
|
354
|
+
{ lockNumber: lockNumber, lockedUntil: lockedUntil,
|
|
355
|
+
durationMs: lockedUntil - now,
|
|
356
|
+
reason: callOpts.reason || null },
|
|
357
|
+
callOpts.req);
|
|
358
|
+
}
|
|
359
|
+
return { locked: true, attempts: 0, lockedUntil: lockedUntil };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
return { locked: false, attempts: attempts };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function recordSuccess(key, callOpts) {
|
|
366
|
+
_requireKey(key);
|
|
367
|
+
callOpts = callOpts || {};
|
|
368
|
+
var state = await _readState(key);
|
|
369
|
+
var hadCounter = !!(state && (state.attempts > 0 || state.lockedUntil));
|
|
370
|
+
if (state) await _deleteState(key);
|
|
371
|
+
_emitObs("auth.lockout.success", { namespace: namespace });
|
|
372
|
+
if (auditSuccess) {
|
|
373
|
+
_emitAudit("auth.lockout.success", key, "success",
|
|
374
|
+
{ attemptsCleared: (state && state.attempts) || 0,
|
|
375
|
+
hadCounter: hadCounter },
|
|
376
|
+
callOpts.req);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async function check(key) {
|
|
381
|
+
_requireKey(key);
|
|
382
|
+
var state = await _readState(key);
|
|
383
|
+
return _verdictFromState(state, clock());
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function unlock(key, callOpts) {
|
|
387
|
+
_requireKey(key);
|
|
388
|
+
callOpts = callOpts || {};
|
|
389
|
+
var state = await _readState(key);
|
|
390
|
+
var now = clock();
|
|
391
|
+
var hadLock = !!(state && (
|
|
392
|
+
(state.lockedUntil && state.lockedUntil > now) ||
|
|
393
|
+
(state.attempts || 0) > 0
|
|
394
|
+
));
|
|
395
|
+
if (state) await _deleteState(key);
|
|
396
|
+
_emitObs("auth.lockout.unlock", { namespace: namespace });
|
|
397
|
+
if (auditUnlock) {
|
|
398
|
+
_emitAudit("auth.lockout.unlock", key, "success",
|
|
399
|
+
{ hadLock: hadLock,
|
|
400
|
+
priorAttempts: (state && state.attempts) || 0,
|
|
401
|
+
priorLockedUntil: (state && state.lockedUntil) || null,
|
|
402
|
+
priorLockNumber: (state && state.lockNumber) || 0,
|
|
403
|
+
reason: callOpts.reason || null },
|
|
404
|
+
callOpts.req);
|
|
405
|
+
}
|
|
406
|
+
return hadLock;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function attempts(key) {
|
|
410
|
+
_requireKey(key);
|
|
411
|
+
var state = await _readState(key);
|
|
412
|
+
return (state && state.attempts) || 0;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function close() {
|
|
416
|
+
// The cache is operator-owned; lockout doesn't close it. Provided
|
|
417
|
+
// for API symmetry with other primitives (cache.close, notify.close,
|
|
418
|
+
// etc.) so operator shutdown code can call close() uniformly.
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
return {
|
|
422
|
+
recordFailure: recordFailure,
|
|
423
|
+
recordSuccess: recordSuccess,
|
|
424
|
+
check: check,
|
|
425
|
+
unlock: unlock,
|
|
426
|
+
attempts: attempts,
|
|
427
|
+
close: close,
|
|
428
|
+
namespace: namespace,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
module.exports = {
|
|
433
|
+
create: create,
|
|
434
|
+
LockoutError: LockoutError,
|
|
435
|
+
DEFAULTS: DEFAULTS,
|
|
436
|
+
};
|