@warlock.js/auth 5.52.0 → 5.53.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 +40 -0
- package/esm/contracts/index.d.mts +2 -2
- package/esm/contracts/providers.d.mts +53 -0
- package/esm/contracts/providers.d.mts.map +1 -1
- package/esm/contracts/types.d.mts +53 -0
- package/esm/contracts/types.d.mts.map +1 -1
- package/esm/contracts/types.mjs.map +1 -1
- package/esm/errors/index.d.mts +2 -1
- package/esm/errors/index.mjs +2 -1
- package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
- package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
- package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
- package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
- package/esm/index.d.mts +3 -2
- package/esm/index.mjs +2 -1
- package/esm/middleware/auth.middleware.mjs +1 -1
- package/esm/middleware/auth.middleware.mjs.map +1 -1
- package/esm/middleware/login-throttle.middleware.d.mts +38 -8
- package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
- package/esm/middleware/login-throttle.middleware.mjs +93 -29
- package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
- package/esm/models/access-token/access-token.model.d.mts +14 -3
- package/esm/models/access-token/access-token.model.d.mts.map +1 -1
- package/esm/models/access-token/access-token.model.mjs +15 -8
- package/esm/models/access-token/access-token.model.mjs.map +1 -1
- package/esm/models/auth.model.d.mts +8 -0
- package/esm/models/auth.model.d.mts.map +1 -1
- package/esm/models/auth.model.mjs +3 -0
- package/esm/models/auth.model.mjs.map +1 -1
- package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
- package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
- package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
- package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
- package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
- package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
- package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
- package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
- package/esm/otp/otp.d.mts +5 -1
- package/esm/otp/otp.d.mts.map +1 -1
- package/esm/otp/otp.mjs +18 -3
- package/esm/otp/otp.mjs.map +1 -1
- package/esm/passkeys/passkey-authentication.mjs +2 -2
- package/esm/passkeys/passkey-authentication.mjs.map +1 -1
- package/esm/passkeys/passkey-registration.d.mts.map +1 -1
- package/esm/passkeys/passkey-registration.mjs +2 -2
- package/esm/passkeys/passkey-registration.mjs.map +1 -1
- package/esm/providers/apple-provider.d.mts +2 -0
- package/esm/providers/apple-provider.d.mts.map +1 -1
- package/esm/providers/apple-provider.mjs +4 -1
- package/esm/providers/apple-provider.mjs.map +1 -1
- package/esm/providers/discord-provider.d.mts +2 -0
- package/esm/providers/discord-provider.d.mts.map +1 -1
- package/esm/providers/discord-provider.mjs +7 -1
- package/esm/providers/discord-provider.mjs.map +1 -1
- package/esm/providers/facebook-provider.d.mts +2 -0
- package/esm/providers/facebook-provider.d.mts.map +1 -1
- package/esm/providers/facebook-provider.mjs +10 -2
- package/esm/providers/facebook-provider.mjs.map +1 -1
- package/esm/providers/github-provider.d.mts +2 -0
- package/esm/providers/github-provider.d.mts.map +1 -1
- package/esm/providers/github-provider.mjs +19 -10
- package/esm/providers/github-provider.mjs.map +1 -1
- package/esm/providers/linkedin-provider.d.mts +2 -0
- package/esm/providers/linkedin-provider.d.mts.map +1 -1
- package/esm/providers/linkedin-provider.mjs +4 -1
- package/esm/providers/linkedin-provider.mjs.map +1 -1
- package/esm/providers/provider-timeout.mjs +17 -0
- package/esm/providers/provider-timeout.mjs.map +1 -0
- package/esm/providers/resolve-provider-user.mjs +21 -1
- package/esm/providers/resolve-provider-user.mjs.map +1 -1
- package/esm/providers/x-provider.d.mts +2 -0
- package/esm/providers/x-provider.d.mts.map +1 -1
- package/esm/providers/x-provider.mjs +7 -1
- package/esm/providers/x-provider.mjs.map +1 -1
- package/esm/services/auth-config.mjs +65 -6
- package/esm/services/auth-config.mjs.map +1 -1
- package/esm/services/auth-cookie-names.mjs +49 -0
- package/esm/services/auth-cookie-names.mjs.map +1 -0
- package/esm/services/auth-events.d.mts +4 -0
- package/esm/services/auth-events.d.mts.map +1 -1
- package/esm/services/auth-events.mjs.map +1 -1
- package/esm/services/auth.service.d.mts +8 -0
- package/esm/services/auth.service.d.mts.map +1 -1
- package/esm/services/auth.service.mjs +146 -20
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/services/jwt.d.mts.map +1 -1
- package/esm/services/jwt.mjs +92 -10
- package/esm/services/jwt.mjs.map +1 -1
- package/esm/services/password-reset.d.mts +5 -0
- package/esm/services/password-reset.d.mts.map +1 -1
- package/esm/services/password-reset.mjs +15 -1
- package/esm/services/password-reset.mjs.map +1 -1
- package/esm/services/resolve-request-user.d.mts.map +1 -1
- package/esm/services/resolve-request-user.mjs +17 -3
- package/esm/services/resolve-request-user.mjs.map +1 -1
- package/esm/session/page-session.d.mts.map +1 -1
- package/esm/session/page-session.mjs +5 -3
- package/esm/session/page-session.mjs.map +1 -1
- package/esm/utils/auth-error-codes.d.mts +8 -1
- package/esm/utils/auth-error-codes.d.mts.map +1 -1
- package/esm/utils/auth-error-codes.mjs +7 -0
- package/esm/utils/auth-error-codes.mjs.map +1 -1
- package/esm/utils/token-digest.mjs +47 -0
- package/esm/utils/token-digest.mjs.map +1 -0
- package/esm/utils/token-expiry.d.mts +3 -1
- package/esm/utils/token-expiry.d.mts.map +1 -1
- package/esm/utils/token-expiry.mjs +7 -2
- package/esm/utils/token-expiry.mjs.map +1 -1
- package/llms-full.txt +70 -30
- package/llms.txt +2 -2
- package/package.json +9 -9
- package/skills/auth-basics/SKILL.md +9 -0
- package/skills/customize-token-storage/SKILL.md +10 -10
- package/skills/login-with-providers/SKILL.md +14 -3
- package/skills/manage-tokens/SKILL.md +6 -0
- package/skills/protect-routes/SKILL.md +5 -0
- package/skills/throttle-login-attempts/SKILL.md +23 -17
- package/skills/verify-email-and-reset-password/SKILL.md +3 -0
|
@@ -14,16 +14,19 @@ export type LoginThrottleIdentifier = "email" | "ip";
|
|
|
14
14
|
/**
|
|
15
15
|
* Options for {@link loginThrottleMiddleware}.
|
|
16
16
|
*
|
|
17
|
-
* Failure-aware by design:
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* Failure-aware by design: every attempt is counted when it arrives (so a
|
|
18
|
+
* burst of concurrent requests cannot outrun the limit), and a successful
|
|
19
|
+
* response (2xx, or whatever `isFailure` says) resets the count, so a user who
|
|
20
|
+
* types a wrong password three times then the right one is not penalised.
|
|
20
21
|
*
|
|
21
22
|
* @example
|
|
22
23
|
* loginThrottleMiddleware({ max: 5, window: "15m", lockoutDuration: "15m" });
|
|
23
24
|
*/
|
|
24
25
|
export type LoginThrottleOptions = {
|
|
25
26
|
/**
|
|
26
|
-
* Failures allowed within the window before the identifier is locked.
|
|
27
|
+
* Failures allowed within the window before the identifier is locked. It
|
|
28
|
+
* also caps how many attempts may be in flight at once: a request beyond it
|
|
29
|
+
* is refused with `429` before the controller runs.
|
|
27
30
|
*
|
|
28
31
|
* @default 5
|
|
29
32
|
*/
|
|
@@ -54,6 +57,28 @@ export type LoginThrottleOptions = {
|
|
|
54
57
|
* @default "email"
|
|
55
58
|
*/
|
|
56
59
|
identifierKey?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Who an account lock applies to when both `"email"` and `"ip"` are tracked.
|
|
62
|
+
*
|
|
63
|
+
* - `"global"` — `max` failures for an email, from any source, lock that
|
|
64
|
+
* email for everyone (the account owner included).
|
|
65
|
+
* - `"pair"` — the `max` lock applies to the (email, source IP) pair, so a
|
|
66
|
+
* stranger guessing from their own IP cannot lock the owner out. The email
|
|
67
|
+
* alone keeps a wider bucket (`accountMax`) that still stops guessing
|
|
68
|
+
* spread across many IPs.
|
|
69
|
+
*
|
|
70
|
+
* Ignored when `identify` is set or `by` does not track both.
|
|
71
|
+
*
|
|
72
|
+
* @default "global"
|
|
73
|
+
*/
|
|
74
|
+
emailLock?: "pair" | "global";
|
|
75
|
+
/**
|
|
76
|
+
* Attempts one email may take from all sources together within the window
|
|
77
|
+
* before it is locked, when `emailLock` is `"pair"`.
|
|
78
|
+
*
|
|
79
|
+
* @default max * 10
|
|
80
|
+
*/
|
|
81
|
+
accountMax?: number;
|
|
57
82
|
/**
|
|
58
83
|
* Override the default error message returned with the 429 response.
|
|
59
84
|
*/
|
|
@@ -97,11 +122,16 @@ export declare function throttleIdentifierHash(kind: string, value: string): str
|
|
|
97
122
|
*
|
|
98
123
|
* 1. **Before the controller** — reject with `429` if a lock key is set,
|
|
99
124
|
* skipping the DB lookup AND the bcrypt verify (this also neutralises the
|
|
100
|
-
* CPU-DoS angle of brute-forcing).
|
|
125
|
+
* CPU-DoS angle of brute-forcing). Otherwise count the attempt in a
|
|
126
|
+
* fixed-window counter right away, and reject with `429` (setting the lock)
|
|
127
|
+
* when it goes past `max`. Counting at entry is what bounds a burst of
|
|
128
|
+
* concurrent requests: at most `max` attempts per window reach the
|
|
129
|
+
* controller, however many arrive at once.
|
|
101
130
|
* 2. **After the controller** — observe the outcome via `response.onSent`.
|
|
102
|
-
* On failure (non-2xx by default),
|
|
103
|
-
*
|
|
104
|
-
*
|
|
131
|
+
* On failure (non-2xx by default), set a lock key with `lockoutDuration`
|
|
132
|
+
* TTL once the attempt count has reached `max` (unless a success reset the
|
|
133
|
+
* counter meanwhile). On success, reset the counter to 0 and clear the lock
|
|
134
|
+
* for that identifier.
|
|
105
135
|
*
|
|
106
136
|
* Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,
|
|
107
137
|
* transitively guaranteed via `@warlock.js/core`). Lockout state is shared
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;YAmBY
|
|
1
|
+
{"version":3,"file":"login-throttle.middleware.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;YAmBY;;;;;;;;;;;;YAaA;;;;;;;;EAQV;;;;;;EAOA;;;;;;EAOA;;;;;;EAOA,KAAK;;;;;;;;EASL;;;;;;;;;;;;;;;EAgBA;;;;;;;EAQA;;;;EAKA;;;;;;;;EASA,aAAa,UAAU;;;;;;EAOvB,YAAY,SAAS;;;;;;;;;;;;;;;;wBAwCP,uBAAuB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiLrC,wBAAwB,UAAS,uBAA4B"}
|
|
@@ -3,9 +3,9 @@ import { normalizeEmailIdentifier } from "../utils/normalize-credentials.mjs";
|
|
|
3
3
|
import { authConfig } from "../services/auth-config.mjs";
|
|
4
4
|
import { t } from "@warlock.js/core";
|
|
5
5
|
import { createHash, createHmac } from "node:crypto";
|
|
6
|
+
import { cache } from "@warlock.js/cache";
|
|
6
7
|
import { log } from "@warlock.js/logger";
|
|
7
8
|
import ms from "ms";
|
|
8
|
-
import { cache } from "@warlock.js/cache";
|
|
9
9
|
|
|
10
10
|
//#region ../../packages/auth/src/middleware/login-throttle.middleware.ts
|
|
11
11
|
const COUNTER_PREFIX = "auth.throttle.count.";
|
|
@@ -89,19 +89,51 @@ function durationSeconds(duration) {
|
|
|
89
89
|
* per-source key. Untruthy values are dropped; a request that yields zero
|
|
90
90
|
* identifiers is left untracked so the middleware no-ops for it.
|
|
91
91
|
*/
|
|
92
|
-
function buildDefaultIdentifiers(request, tracked, credentialField) {
|
|
92
|
+
function buildDefaultIdentifiers(request, tracked, credentialField, max, pair) {
|
|
93
93
|
const identifiers = [];
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
94
|
+
const value = tracked.includes("email") ? request.input(credentialField) : void 0;
|
|
95
|
+
const email = typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
96
|
+
const ip = tracked.includes("ip") ? request.detectIp() : void 0;
|
|
97
|
+
if (email !== void 0) {
|
|
98
|
+
if (pair && ip) {
|
|
99
|
+
const pairValue = `${normalizeEmailIdentifier(email)}|${ip}`;
|
|
100
|
+
identifiers.push({
|
|
101
|
+
key: `email-ip.${throttleIdentifierHash("email-ip", pairValue)}`,
|
|
102
|
+
max
|
|
103
|
+
});
|
|
104
|
+
identifiers.push({
|
|
105
|
+
key: `email.${throttleIdentifierHash("email", email)}`,
|
|
106
|
+
max: pair.accountMax
|
|
107
|
+
});
|
|
108
|
+
} else identifiers.push({
|
|
109
|
+
key: `email.${throttleIdentifierHash("email", email)}`,
|
|
110
|
+
max
|
|
111
|
+
});
|
|
101
112
|
}
|
|
113
|
+
if (ip) identifiers.push({
|
|
114
|
+
key: `ip.${throttleIdentifierHash("ip", ip)}`,
|
|
115
|
+
max
|
|
116
|
+
});
|
|
102
117
|
return identifiers;
|
|
103
118
|
}
|
|
104
119
|
/**
|
|
120
|
+
* Whether the counter now reads a number below `count`, i.e. a success reset
|
|
121
|
+
* it while this attempt ran. Fails closed: a missing value (expired, evicted,
|
|
122
|
+
* a driver that stores nothing), a non-numeric one or a failed read all answer
|
|
123
|
+
* `false`, so the caller locks.
|
|
124
|
+
*/
|
|
125
|
+
async function counterWasReset(identifier, count) {
|
|
126
|
+
let current;
|
|
127
|
+
try {
|
|
128
|
+
current = await cache.get(counterKey(identifier));
|
|
129
|
+
} catch (error) {
|
|
130
|
+
log.error("auth", "login-throttle", error);
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
if (typeof current === "string" && current.trim() !== "") current = Number(current);
|
|
134
|
+
return typeof current === "number" && Number.isFinite(current) && current < count;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
105
137
|
* Failure-aware login throttle. Locks an identifier (account, IP, or both)
|
|
106
138
|
* after too many failed login attempts within a window — without penalising
|
|
107
139
|
* a user who eventually types the right password.
|
|
@@ -110,11 +142,16 @@ function buildDefaultIdentifiers(request, tracked, credentialField) {
|
|
|
110
142
|
*
|
|
111
143
|
* 1. **Before the controller** — reject with `429` if a lock key is set,
|
|
112
144
|
* skipping the DB lookup AND the bcrypt verify (this also neutralises the
|
|
113
|
-
* CPU-DoS angle of brute-forcing).
|
|
145
|
+
* CPU-DoS angle of brute-forcing). Otherwise count the attempt in a
|
|
146
|
+
* fixed-window counter right away, and reject with `429` (setting the lock)
|
|
147
|
+
* when it goes past `max`. Counting at entry is what bounds a burst of
|
|
148
|
+
* concurrent requests: at most `max` attempts per window reach the
|
|
149
|
+
* controller, however many arrive at once.
|
|
114
150
|
* 2. **After the controller** — observe the outcome via `response.onSent`.
|
|
115
|
-
* On failure (non-2xx by default),
|
|
116
|
-
*
|
|
117
|
-
*
|
|
151
|
+
* On failure (non-2xx by default), set a lock key with `lockoutDuration`
|
|
152
|
+
* TTL once the attempt count has reached `max` (unless a success reset the
|
|
153
|
+
* counter meanwhile). On success, reset the counter to 0 and clear the lock
|
|
154
|
+
* for that identifier.
|
|
118
155
|
*
|
|
119
156
|
* Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,
|
|
120
157
|
* transitively guaranteed via `@warlock.js/core`). Lockout state is shared
|
|
@@ -143,15 +180,47 @@ function loginThrottleMiddleware(options = {}) {
|
|
|
143
180
|
const lockoutDuration = options.lockoutDuration ?? "15m";
|
|
144
181
|
const tracked = options.by ?? ["email", "ip"];
|
|
145
182
|
const credentialField = options.identifierKey ?? "email";
|
|
183
|
+
const pair = options.emailLock === "pair" && tracked.includes("email") && tracked.includes("ip") ? { accountMax: options.accountMax ?? max * 10 } : void 0;
|
|
184
|
+
/**
|
|
185
|
+
* Lock an identifier for `lockoutDuration`. The counter is rewritten with
|
|
186
|
+
* the same TTL, so the two expire together and the identifier starts a fresh
|
|
187
|
+
* window once the lockout ends. Rewriting keeps a value of at least `count`,
|
|
188
|
+
* so a request that slipped past the lock check still sees "over the limit".
|
|
189
|
+
*/
|
|
190
|
+
const lock = async (identifier, count) => {
|
|
191
|
+
const lockSeconds = durationSeconds(lockoutDuration);
|
|
192
|
+
await cache.set(lockKey(identifier), lockSeconds === void 0 ? true : Date.now() + lockSeconds * 1e3, { ttl: lockoutDuration });
|
|
193
|
+
await cache.set(counterKey(identifier), count, { ttl: lockoutDuration });
|
|
194
|
+
};
|
|
146
195
|
return async ({ request, response }) => {
|
|
147
|
-
const identifiers = options.identify ? options.identify(request)
|
|
196
|
+
const identifiers = options.identify ? options.identify(request).map((key) => ({
|
|
197
|
+
key,
|
|
198
|
+
max
|
|
199
|
+
})) : buildDefaultIdentifiers(request, tracked, credentialField, max, pair);
|
|
148
200
|
if (identifiers.length === 0) return;
|
|
149
201
|
warnIfNullDriver();
|
|
202
|
+
const tooManyRequests = () => response.tooManyRequests({
|
|
203
|
+
error: options.errorMessage ?? t("auth.errors.tooManyAttempts"),
|
|
204
|
+
errorCode: "EC004"
|
|
205
|
+
});
|
|
206
|
+
/** The attempt number this request took in each identifier's window. */
|
|
207
|
+
const counts = /* @__PURE__ */ new Map();
|
|
150
208
|
try {
|
|
151
|
-
for (const identifier of identifiers) if (isLocked(await cache.get(lockKey(identifier)))) return
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
209
|
+
for (const identifier of identifiers) if (isLocked(await cache.get(lockKey(identifier.key)))) return tooManyRequests();
|
|
210
|
+
for (const identifier of identifiers) {
|
|
211
|
+
const key = counterKey(identifier.key);
|
|
212
|
+
await cache.set(key, 0, {
|
|
213
|
+
ttl: window,
|
|
214
|
+
onConflict: "create"
|
|
215
|
+
});
|
|
216
|
+
const count = await cache.increment(key, 1, { ttl: window });
|
|
217
|
+
if (typeof count !== "number" || !Number.isFinite(count)) continue;
|
|
218
|
+
counts.set(identifier.key, count);
|
|
219
|
+
if (count > identifier.max) {
|
|
220
|
+
if (count === identifier.max + 1) await lock(identifier.key, count);
|
|
221
|
+
return tooManyRequests();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
155
224
|
} catch (error) {
|
|
156
225
|
log.error("auth", "login-throttle", error);
|
|
157
226
|
return;
|
|
@@ -160,21 +229,16 @@ function loginThrottleMiddleware(options = {}) {
|
|
|
160
229
|
try {
|
|
161
230
|
if (!(options.isFailure ? options.isFailure(resolvedResponse) : !resolvedResponse.isOk)) {
|
|
162
231
|
for (const identifier of identifiers) {
|
|
163
|
-
await cache.
|
|
164
|
-
await cache.remove(lockKey(identifier));
|
|
232
|
+
await cache.set(counterKey(identifier.key), 0, { ttl: window });
|
|
233
|
+
await cache.remove(lockKey(identifier.key));
|
|
165
234
|
}
|
|
166
235
|
return;
|
|
167
236
|
}
|
|
168
237
|
for (const identifier of identifiers) {
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
});
|
|
174
|
-
if (await cache.increment(key, 1, { ttl: window }) >= max) {
|
|
175
|
-
const lockSeconds = durationSeconds(lockoutDuration);
|
|
176
|
-
await cache.set(lockKey(identifier), lockSeconds === void 0 ? true : Date.now() + lockSeconds * 1e3, { ttl: lockoutDuration });
|
|
177
|
-
}
|
|
238
|
+
const count = counts.get(identifier.key);
|
|
239
|
+
if (count === void 0 || count < identifier.max) continue;
|
|
240
|
+
if (await counterWasReset(identifier.key, count)) continue;
|
|
241
|
+
await lock(identifier.key, count);
|
|
178
242
|
}
|
|
179
243
|
} catch (error) {
|
|
180
244
|
log.error("auth", "login-throttle", error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { normalizeEmailIdentifier } from \"../utils/normalize-credentials\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` — defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: only counts requests whose response is non-2xx\n * (or whatever `isFailure` says) and resets on success, so a user who types\n * a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number → seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor — reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n): string[] {\n const identifiers: string[] = [];\n\n if (tracked.includes(\"email\")) {\n const value = request.input(credentialField);\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n identifiers.push(`email.${throttleIdentifierHash(\"email\", value)}`);\n }\n }\n\n if (tracked.includes(\"ip\")) {\n const ip = request.detectIp();\n\n if (ip) {\n identifiers.push(`ip.${throttleIdentifierHash(\"ip\", ip)}`);\n }\n }\n\n return identifiers;\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window — without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** — reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing).\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), bump a fixed-window counter; once it\n * reaches `max`, set a lock key with `lockoutDuration` TTL. On success,\n * clear both the counter and the lock for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas — correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only — avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n\n return async ({ request, response }) => {\n const identifiers = options.identify\n ? options.identify(request)\n : buildDefaultIdentifiers(request, tracked, credentialField);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n try {\n for (const identifier of identifiers) {\n const locked = isLocked(await cache.get(lockKey(identifier)));\n\n if (locked) {\n return response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n }\n }\n } catch (error) {\n // Fail open — a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n await cache.remove(counterKey(identifier));\n await cache.remove(lockKey(identifier));\n }\n\n return;\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier);\n\n // Open the window on the first failure: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent failures across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing\n // the TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (count >= max) {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding\n // expiration (`memoryExtended`) pushes the key's TTL forward on\n // every read, but the deadline in the value does not move, so a\n // client that keeps retrying is still released after\n // `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n }\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AA2FA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,cAAc,eAA+B,GAAG,iBAAiB;AACvE,MAAM,WAAW,eAA+B,GAAG,cAAc;;;;;;AAOjE,SAAS,kBAAsC;CAC7C,IAAI;CAEJ,IAAI;EACF,SAAS,WAAW,YAAY,OAAO;CACzC,QAAQ;EACN;CACF;CAEA,OAAO,WAAW,UAAU,MAAM,CAAC,CAAC,OAAO,2BAA2B,CAAC,CAAC,OAAO;AACjF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,MAAc,OAAuB;CAC1E,MAAM,aAAa,GAAG,KAAK,GAAG,yBAAyB,KAAK;CAC5D,MAAM,MAAM,gBAAgB;CAE5B,OAAO,MACH,WAAW,UAAU,GA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S,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { normalizeEmailIdentifier } from \"../utils/normalize-credentials\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` — defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: every attempt is counted when it arrives (so a\n * burst of concurrent requests cannot outrun the limit), and a successful\n * response (2xx, or whatever `isFailure` says) resets the count, so a user who\n * types a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked. It\n * also caps how many attempts may be in flight at once: a request beyond it\n * is refused with `429` before the controller runs.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Who an account lock applies to when both `\"email\"` and `\"ip\"` are tracked.\n *\n * - `\"global\"` — `max` failures for an email, from any source, lock that\n * email for everyone (the account owner included).\n * - `\"pair\"` — the `max` lock applies to the (email, source IP) pair, so a\n * stranger guessing from their own IP cannot lock the owner out. The email\n * alone keeps a wider bucket (`accountMax`) that still stops guessing\n * spread across many IPs.\n *\n * Ignored when `identify` is set or `by` does not track both.\n *\n * @default \"global\"\n */\n emailLock?: \"pair\" | \"global\";\n\n /**\n * Attempts one email may take from all sources together within the window\n * before it is locked, when `emailLock` is `\"pair\"`.\n *\n * @default max * 10\n */\n accountMax?: number;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number → seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor — reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n max: number,\n pair: { accountMax: number } | undefined,\n): TrackedIdentifier[] {\n const identifiers: TrackedIdentifier[] = [];\n const value = tracked.includes(\"email\") ? request.input(credentialField) : undefined;\n const email = typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n const ip = tracked.includes(\"ip\") ? request.detectIp() : undefined;\n\n if (email !== undefined) {\n if (pair && ip) {\n // The hard lock belongs to this source only; the email-wide bucket is\n // wider, so a stranger cannot lock the owner out with `max` guesses.\n const pairValue = `${normalizeEmailIdentifier(email)}|${ip}`;\n\n identifiers.push({ key: `email-ip.${throttleIdentifierHash(\"email-ip\", pairValue)}`, max });\n identifiers.push({\n key: `email.${throttleIdentifierHash(\"email\", email)}`,\n max: pair.accountMax,\n });\n } else {\n identifiers.push({ key: `email.${throttleIdentifierHash(\"email\", email)}`, max });\n }\n }\n\n if (ip) {\n identifiers.push({ key: `ip.${throttleIdentifierHash(\"ip\", ip)}`, max });\n }\n\n return identifiers;\n}\n\n/** One throttle bucket: its cache-key suffix and the attempts it allows. */\ntype TrackedIdentifier = { key: string; max: number };\n\n/**\n * Whether the counter now reads a number below `count`, i.e. a success reset\n * it while this attempt ran. Fails closed: a missing value (expired, evicted,\n * a driver that stores nothing), a non-numeric one or a failed read all answer\n * `false`, so the caller locks.\n */\nasync function counterWasReset(identifier: string, count: number): Promise<boolean> {\n let current: unknown;\n\n try {\n current = await cache.get(counterKey(identifier));\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n\n return false;\n }\n\n if (typeof current === \"string\" && current.trim() !== \"\") current = Number(current);\n\n return typeof current === \"number\" && Number.isFinite(current) && current < count;\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window — without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** — reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing). Otherwise count the attempt in a\n * fixed-window counter right away, and reject with `429` (setting the lock)\n * when it goes past `max`. Counting at entry is what bounds a burst of\n * concurrent requests: at most `max` attempts per window reach the\n * controller, however many arrive at once.\n * 2. **After the controller** — observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), set a lock key with `lockoutDuration`\n * TTL once the attempt count has reached `max` (unless a success reset the\n * counter meanwhile). On success, reset the counter to 0 and clear the lock\n * for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas — correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only — avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n const pair =\n options.emailLock === \"pair\" && tracked.includes(\"email\") && tracked.includes(\"ip\")\n ? { accountMax: options.accountMax ?? max * 10 }\n : undefined;\n\n /**\n * Lock an identifier for `lockoutDuration`. The counter is rewritten with\n * the same TTL, so the two expire together and the identifier starts a fresh\n * window once the lockout ends. Rewriting keeps a value of at least `count`,\n * so a request that slipped past the lock check still sees \"over the limit\".\n */\n const lock = async (identifier: string, count: number): Promise<void> => {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding expiration\n // (`memoryExtended`) pushes the key's TTL forward on every read, but the\n // deadline in the value does not move, so a client that keeps retrying is\n // still released after `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n await cache.set(counterKey(identifier), count, { ttl: lockoutDuration });\n };\n\n return async ({ request, response }) => {\n const identifiers: TrackedIdentifier[] = options.identify\n ? options.identify(request).map((key) => ({ key, max }))\n : buildDefaultIdentifiers(request, tracked, credentialField, max, pair);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n const tooManyRequests = () =>\n response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n\n /** The attempt number this request took in each identifier's window. */\n const counts = new Map<string, number>();\n\n try {\n for (const identifier of identifiers) {\n if (isLocked(await cache.get(lockKey(identifier.key)))) {\n return tooManyRequests();\n }\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier.key);\n\n // Open the window on the first attempt: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent attempts across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing the\n // TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (typeof count !== \"number\" || !Number.isFinite(count)) continue;\n\n counts.set(identifier.key, count);\n\n if (count > identifier.max) {\n if (count === identifier.max + 1) {\n await lock(identifier.key, count);\n }\n\n return tooManyRequests();\n }\n }\n } catch (error) {\n // Fail open — a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n // Reset to 0 rather than delete: a failure still in flight reads\n // the 0 as proof that a success reset the window (see below).\n await cache.set(counterKey(identifier.key), 0, { ttl: window });\n await cache.remove(lockKey(identifier.key));\n }\n\n return;\n }\n\n // Already counted at entry; a failure that used the last allowed\n // attempt starts the lockout, unless a success that finished while it\n // ran reset the counter (a correct login racing a mistyped one must\n // not lock the account it just signed in to).\n for (const identifier of identifiers) {\n const count = counts.get(identifier.key);\n\n if (count === undefined || count < identifier.max) continue;\n\n if (await counterWasReset(identifier.key, count)) continue;\n\n await lock(identifier.key, count);\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AAsHA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,cAAc,eAA+B,GAAG,iBAAiB;AACvE,MAAM,WAAW,eAA+B,GAAG,cAAc;;;;;;AAOjE,SAAS,kBAAsC;CAC7C,IAAI;CAEJ,IAAI;EACF,SAAS,WAAW,YAAY,OAAO;CACzC,QAAQ;EACN;CACF;CAEA,OAAO,WAAW,UAAU,MAAM,CAAC,CAAC,OAAO,2BAA2B,CAAC,CAAC,OAAO;AACjF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,MAAc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,CAAC,iBAAiB,OAET;KACX,KAAK,MAAM,cAAc,aAAa;MAGpC,MAAM,MAAM,IAAI,WAAW,WAAW,GAAG,GAAG,GAAG,EAAE,KAAK,OAAO,CAAC;MAC9D,MAAM,MAAM,OAAO,QAAQ,WAAW,GAAG,CAAC;KAC5C;KAEA;IACF;IAMA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,QAAQ,OAAO,IAAI,WAAW,GAAG;KAEvC,IAAI,UAAU,UAAa,QAAQ,WAAW,KAAK;KAEnD,IAAI,MAAM,gBAAgB,WAAW,KAAK,KAAK,GAAG;KAElD,MAAM,KAAK,WAAW,KAAK,KAAK;IAClC;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
|
|
@@ -46,6 +46,10 @@ export declare class AccessToken extends Model {
|
|
|
46
46
|
* only strips it from `toJSON()` / `JSON.stringify(model)` (so
|
|
47
47
|
* `response.json(token)` or a resource cannot leak it); `get("token")`,
|
|
48
48
|
* `findByToken` and every query still read the column.
|
|
49
|
+
*
|
|
50
|
+
* With `auth.hashTokensAtRest` on, the column holds the token's SHA-256
|
|
51
|
+
* digest instead, so a copy of the table cannot be replayed; read the raw
|
|
52
|
+
* token of a freshly issued row through {@link plainToken}.
|
|
49
53
|
*/
|
|
50
54
|
static hidden: string[];
|
|
51
55
|
/**
|
|
@@ -60,6 +64,11 @@ export declare class AccessToken extends Model {
|
|
|
60
64
|
get userId(): any;
|
|
61
65
|
/** The user-type slug this token was issued for. */
|
|
62
66
|
get userType(): string;
|
|
67
|
+
/**
|
|
68
|
+
* The raw token, when it is known: always for a row stored unhashed, and
|
|
69
|
+
* for a hashed row only in the process that just issued it.
|
|
70
|
+
*/
|
|
71
|
+
get plainToken(): string | undefined;
|
|
63
72
|
/**
|
|
64
73
|
* Whether the persisted expiry has passed.
|
|
65
74
|
*
|
|
@@ -84,15 +93,17 @@ export declare class AccessToken extends Model {
|
|
|
84
93
|
*/
|
|
85
94
|
get neverExpires(): boolean;
|
|
86
95
|
/**
|
|
87
|
-
* Persist a freshly-signed access token for the user.
|
|
96
|
+
* Persist a freshly-signed access token for the user. `token` is the value
|
|
97
|
+
* to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.
|
|
88
98
|
*/
|
|
89
99
|
static issue(user: Auth, token: string, expiresAt: Date, familyId?: string): Promise<AccessToken>;
|
|
90
100
|
/**
|
|
91
|
-
* Find an access-token row by its raw token string
|
|
101
|
+
* Find an access-token row by its raw token string, whether the row stores
|
|
102
|
+
* the token hashed or raw (one query).
|
|
92
103
|
*/
|
|
93
104
|
static findByToken(token: string): Promise<AccessToken | null>;
|
|
94
105
|
/**
|
|
95
|
-
* Delete a specific token that belongs to the given user.
|
|
106
|
+
* Delete a specific token that belongs to the given user, stored hashed or raw.
|
|
96
107
|
*/
|
|
97
108
|
static deleteForUser(user: Auth, token: string): Promise<number>;
|
|
98
109
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"access-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;qBAca,8CAAiB;;;;;;;;;;;;;;;;;;;;qBAmBjB,oBAAoB;SACjB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;SAYN;;;;;;;;SASA;;MAGH;;MAKA;;;;;MAQA;;;;;;;;;;;;;;;;MAmBA;;;;;;;MAcA;;;;;SAQG,MAAM,MAAM,MAAM,eAAe,WAAW,MAAM,oBAAiB,QAAA;;;;;SAcnE,YAAY,gBAAgB,QAAQ;;;;SAOpC,cAAc,MAAM,MAAM,gBAAa;;;;SAUvC,iBAAiB,MAAM,OAAI;;;;;;SASrB,6BAA6B,MAAM,MAAM,mBAAmB;;;;;SAS5D,gBAAgB;;;;;;;;;;;;SAqBhB,qBAAqB,QAAQ;;;;;;SAW7B,sBAAsB,QAAQ"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { plainTokenOf, storedTokenForms } from "../../utils/token-digest.mjs";
|
|
1
2
|
import { isNeverExpiring, isUsableExpiry } from "../../utils/token-expiry.mjs";
|
|
2
3
|
import { Model } from "@warlock.js/cascade";
|
|
3
4
|
import { v } from "@warlock.js/seal";
|
|
@@ -51,6 +52,13 @@ var AccessToken = class extends Model {
|
|
|
51
52
|
return this.get("user_type");
|
|
52
53
|
}
|
|
53
54
|
/**
|
|
55
|
+
* The raw token, when it is known: always for a row stored unhashed, and
|
|
56
|
+
* for a hashed row only in the process that just issued it.
|
|
57
|
+
*/
|
|
58
|
+
get plainToken() {
|
|
59
|
+
return plainTokenOf(this, this.get("token"));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
54
62
|
* Whether the persisted expiry has passed.
|
|
55
63
|
*
|
|
56
64
|
* The middleware asks this on every request, which is what makes the row the
|
|
@@ -80,7 +88,8 @@ var AccessToken = class extends Model {
|
|
|
80
88
|
return isNeverExpiring(this.get("token"), this.get("expires_at"));
|
|
81
89
|
}
|
|
82
90
|
/**
|
|
83
|
-
* Persist a freshly-signed access token for the user.
|
|
91
|
+
* Persist a freshly-signed access token for the user. `token` is the value
|
|
92
|
+
* to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.
|
|
84
93
|
*/
|
|
85
94
|
static issue(user, token, expiresAt, familyId) {
|
|
86
95
|
return this.create({
|
|
@@ -92,19 +101,17 @@ var AccessToken = class extends Model {
|
|
|
92
101
|
});
|
|
93
102
|
}
|
|
94
103
|
/**
|
|
95
|
-
* Find an access-token row by its raw token string
|
|
104
|
+
* Find an access-token row by its raw token string, whether the row stores
|
|
105
|
+
* the token hashed or raw (one query).
|
|
96
106
|
*/
|
|
97
107
|
static findByToken(token) {
|
|
98
|
-
return this.
|
|
108
|
+
return this.query().whereIn("token", storedTokenForms(token)).first();
|
|
99
109
|
}
|
|
100
110
|
/**
|
|
101
|
-
* Delete a specific token that belongs to the given user.
|
|
111
|
+
* Delete a specific token that belongs to the given user, stored hashed or raw.
|
|
102
112
|
*/
|
|
103
113
|
static deleteForUser(user, token) {
|
|
104
|
-
return this.delete(
|
|
105
|
-
token,
|
|
106
|
-
user_id: user.id
|
|
107
|
-
});
|
|
114
|
+
return this.query().where({ user_id: user.id }).whereIn("token", storedTokenForms(token)).delete();
|
|
108
115
|
}
|
|
109
116
|
/**
|
|
110
117
|
* Delete every access token belonging to the user.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted access-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape.\n *\n * `last_access` and the `is_active` soft-revoke flag were removed — neither was\n * ever read; access tokens are revoked by deleting the row.\n */\nexport const accessTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n /** Null for tokens issued before family tracking was introduced. */\n family_id: v.string().optional(),\n expires_at: v.date().required(),\n});\n\n/**\n * Persisted access-token record + the data layer for access tokens.\n *\n * **Role.** Owns access-token persistence and lookup. The middleware checks a\n * presented JWT against this table so deleting a row (logout) invalidates the\n * token immediately, before its JWT expiry. The auth service goes through the\n * named statics exclusively, so it never hard-codes a column name and an\n * override can rename/add columns by registering under\n * `config.auth.accessToken.model`.\n */\nexport class AccessToken extends Model {\n public static table = \"access_tokens\";\n\n public static schema = accessTokenSchema;\n\n /**\n * The raw signed JWT is a bearer credential — never serialize it. `hidden`\n * only strips it from `toJSON()` / `JSON.stringify(model)` (so\n * `response.json(token)` or a resource cannot leak it); `get(\"token\")`,\n * `findByToken` and every query still read the column.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `access_tokensTrash` on every `destroy()` (logout, expiry purge,\n * never-expiring purge). A revoked/expired access token must not survive\n * anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /**\n * Whether the persisted expiry has passed.\n *\n * The middleware asks this on every request, which is what makes the row the\n * authority it always looked like it was: before 4.12.0 the gate only checked\n * that the row *existed*, so a row the database knew was dead still let its\n * token through — the database was never asked.\n *\n * **Fails closed.** A missing or unparseable `expires_at` counts as expired.\n * `expires_at` is `required` in the schema, so a row that cannot answer \"when\n * does this die\" is malformed, and the safe reading of a malformed credential\n * is that it is not one. This is deliberately stricter than a naive\n * `now > expires_at`, which answers `false` for an `Invalid Date` and thereby\n * grants exactly the poisoned rows an unlimited life.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Whether nothing about this row can ever retire it — an unusable\n * `expires_at`, or a token carrying no `exp` claim. See\n * {@link isNeverExpiring}; this is the predicate `purgeNeverExpiring` selects\n * on.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /**\n * Persist a freshly-signed access token for the user
|
|
1
|
+
{"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted access-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape.\n *\n * `last_access` and the `is_active` soft-revoke flag were removed — neither was\n * ever read; access tokens are revoked by deleting the row.\n */\nexport const accessTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n /** Null for tokens issued before family tracking was introduced. */\n family_id: v.string().optional(),\n expires_at: v.date().required(),\n});\n\n/**\n * Persisted access-token record + the data layer for access tokens.\n *\n * **Role.** Owns access-token persistence and lookup. The middleware checks a\n * presented JWT against this table so deleting a row (logout) invalidates the\n * token immediately, before its JWT expiry. The auth service goes through the\n * named statics exclusively, so it never hard-codes a column name and an\n * override can rename/add columns by registering under\n * `config.auth.accessToken.model`.\n */\nexport class AccessToken extends Model {\n public static table = \"access_tokens\";\n\n public static schema = accessTokenSchema;\n\n /**\n * The raw signed JWT is a bearer credential — never serialize it. `hidden`\n * only strips it from `toJSON()` / `JSON.stringify(model)` (so\n * `response.json(token)` or a resource cannot leak it); `get(\"token\")`,\n * `findByToken` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead, so a copy of the table cannot be replayed; read the raw\n * token of a freshly issued row through {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `access_tokensTrash` on every `destroy()` (logout, expiry purge,\n * never-expiring purge). A revoked/expired access token must not survive\n * anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /**\n * The raw token, when it is known: always for a row stored unhashed, and\n * for a hashed row only in the process that just issued it.\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the persisted expiry has passed.\n *\n * The middleware asks this on every request, which is what makes the row the\n * authority it always looked like it was: before 4.12.0 the gate only checked\n * that the row *existed*, so a row the database knew was dead still let its\n * token through — the database was never asked.\n *\n * **Fails closed.** A missing or unparseable `expires_at` counts as expired.\n * `expires_at` is `required` in the schema, so a row that cannot answer \"when\n * does this die\" is malformed, and the safe reading of a malformed credential\n * is that it is not one. This is deliberately stricter than a naive\n * `now > expires_at`, which answers `false` for an `Invalid Date` and thereby\n * grants exactly the poisoned rows an unlimited life.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Whether nothing about this row can ever retire it — an unusable\n * `expires_at`, or a token carrying no `exp` claim. See\n * {@link isNeverExpiring}; this is the predicate `purgeNeverExpiring` selects\n * on.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /**\n * Persist a freshly-signed access token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, expiresAt: Date, familyId?: string) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: familyId,\n expires_at: expiresAt,\n });\n }\n\n /**\n * Find an access-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<AccessToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Delete a specific token that belongs to the given user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Delete every access token belonging to the user.\n */\n public static deleteAllForUser(user: Auth) {\n return this.delete({ user_id: user.id });\n }\n\n /**\n * Delete every access token attached to one family, plus pre-family rows for\n * the same user type. The latter is deliberately conservative during the\n * additive upgrade: old access rows cannot be assigned safely to a family.\n */\n public static async deleteFamilyAndLegacyForUser(user: Auth, familyId: string): Promise<void> {\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: familyId });\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: null });\n }\n\n /**\n * Hard-delete every expired access-token row. Returns the number removed.\n * Runs from the `auth.cleanup` CLI command (a cold batch path).\n */\n public static async purgeExpired(): Promise<number> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens.length;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}.\n *\n * **A full scan, filtered in memory, on purpose.** The defining case is a row\n * whose `expires_at` is an `Invalid Date`, which no date predicate can select\n * (`< now` and `> now` are both `false` for it), and the definitive case is a\n * token with no `exp` claim, which lives inside the token string rather than\n * in a column. Neither is expressible as a `where`, so the rows have to be\n * read to be judged. This runs from a one-off remediation command, not a\n * request path.\n */\n public static async findNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: AccessToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed so the\n * caller can report what it revoked. Deletion *is* revocation for access\n * tokens — the middleware rejects a token with no row.\n */\n public static async purgeNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oBAAoB,EAAE,OAAO;CACxC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;;;;;;;;;;AAYD,IAAa,cAAb,cAAiC,MAAM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;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,WAAW;EAAK,CAAC;CACnF;;;;;CAMA,aAAoB,eAAgC;EAClD,MAAM,gBAAgB,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO,cAAc;CACvB;;;;;;;;;;;;CAaA,aAAoB,oBAA4C;EAG9D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAuB,MAAM,YAAY;CACjE;;;;;;CAOA,aAAoB,qBAA6C;EAC/D,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
@@ -4,6 +4,14 @@ import { Authenticable } from "../contracts/auth-contract.mjs";
|
|
|
4
4
|
import { ChildModel, Model, ModelSchema } from "@warlock.js/cascade";
|
|
5
5
|
//#region ../../packages/auth/src/models/auth.model.d.ts
|
|
6
6
|
export declare abstract class Auth<out Schema extends ModelSchema = ModelSchema> extends Model<Schema> implements Authenticable {
|
|
7
|
+
/**
|
|
8
|
+
* The password hash never leaves the server through serialization:
|
|
9
|
+
* `toJSON()` (so `response.json(user)`), lean query rows and embedded
|
|
10
|
+
* copies all drop it, while `user.get("password")` / `user.string("password")`
|
|
11
|
+
* still read it for verification. A subclass that sets its own `hidden`
|
|
12
|
+
* replaces this list, so keep `"password"` in it.
|
|
13
|
+
*/
|
|
14
|
+
static hidden: string[];
|
|
7
15
|
/**
|
|
8
16
|
* Get user type
|
|
9
17
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.model.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"mappings":";;;;;8BAQsB,SAAS,eAAe,cAAc,qBAClD,MAAM,mBACH;;;;
|
|
1
|
+
{"version":3,"file":"auth.model.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"mappings":";;;;;8BAQsB,SAAS,eAAe,cAAc,qBAClD,MAAM,mBACH;;;;;;;;SASG;;;;eAKM;;;;EAKb,sBAAkB;;;;EAOZ,gBAAgB,aAAa,aAAa,QAAQ;;;;EAOlD,oBAAoB,aAAa,QAAQ;;;;EAOzC,qBAAqB,aAAa,aAAa,QAAQ;;;;EAOvD,kBAAkB,gBAAgB;;;;EAOlC,mBAAmB,gBAAgB;;;;EAOnC,yBAAyB;;;;EAOzB,mBAAmB;;;;EAOnB,kBAAkB,QAAQ;;;;SAOnB,QAAQ,MAAM,WAAW,OAAO,YAAY,QAAQ;;;;EAO3D,gBAAgB,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.model.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"sourcesContent":["import { type ChildModel, Model, type ModelSchema } from \"@warlock.js/cascade\";\nimport type { Authenticable } from \"../contracts/auth-contract\";\nimport type { AccessTokenOutput, DeviceInfo, TokenPair } from \"../contracts/types\";\nimport { authService } from \"../services\";\nimport type { RefreshToken } from \"./refresh-token/refresh-token.model\";\n\n// `out` keeps a typed auth model assignable to the loose `Auth`, like `Model` itself.\n// @ts-expect-error TS2636: variance cannot be verified through Model's typed get()/set()\nexport abstract class Auth<out Schema extends ModelSchema = ModelSchema>\n extends Model<Schema>\n implements Authenticable\n{\n /**\n * Get user type\n */\n public abstract get userType(): string;\n\n /**\n * Get access token payload\n */\n public accessTokenPayload() {\n return authService.buildAccessTokenPayload(this);\n }\n\n /**\n * Create both access and refresh tokens\n */\n public async createTokenPair(deviceInfo?: DeviceInfo): Promise<TokenPair> {\n return authService.createTokenPair(this, deviceInfo);\n }\n\n /**\n * Generate access token\n */\n public async generateAccessToken(data?: any): Promise<AccessTokenOutput> {\n return authService.generateAccessToken(this, data);\n }\n\n /**\n * Generate refresh token\n */\n public async generateRefreshToken(deviceInfo?: DeviceInfo): Promise<RefreshToken | undefined> {\n return authService.createRefreshToken(this, deviceInfo);\n }\n\n /**\n * Remove current access token\n */\n public async removeAccessToken(token: string): Promise<void> {\n return authService.removeAccessToken(this, token);\n }\n\n /**\n * Remove refresh token\n */\n public async removeRefreshToken(token: string): Promise<void> {\n return authService.removeRefreshToken(this, token);\n }\n\n /**\n * Remove all access tokens\n */\n public async removeAllAccessTokens(): Promise<void> {\n return authService.removeAllAccessTokens(this);\n }\n\n /**\n * Revoke all tokens (logout from all devices)\n */\n public async revokeAllTokens(): Promise<void> {\n return authService.revokeAllTokens(this);\n }\n\n /**\n * Get active sessions\n */\n public async activeSessions(): Promise<RefreshToken[]> {\n return authService.getActiveSessions(this);\n }\n\n /**\n * Attempt to login the user\n */\n public static async attempt(this: ChildModel<Auth>, data: any): Promise<Auth | null> {\n return authService.attemptLogin(this, data);\n }\n\n /**\n * Confirm password\n */\n public async confirmPassword(password: string): Promise<boolean> {\n return authService.verifyPassword(password, this.string(\"password\")!);\n }\n}\n"],"mappings":";;;;;AAQA,IAAsB,OAAtB,cACU,MAEV
|
|
1
|
+
{"version":3,"file":"auth.model.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"sourcesContent":["import { type ChildModel, Model, type ModelSchema } from \"@warlock.js/cascade\";\nimport type { Authenticable } from \"../contracts/auth-contract\";\nimport type { AccessTokenOutput, DeviceInfo, TokenPair } from \"../contracts/types\";\nimport { authService } from \"../services\";\nimport type { RefreshToken } from \"./refresh-token/refresh-token.model\";\n\n// `out` keeps a typed auth model assignable to the loose `Auth`, like `Model` itself.\n// @ts-expect-error TS2636: variance cannot be verified through Model's typed get()/set()\nexport abstract class Auth<out Schema extends ModelSchema = ModelSchema>\n extends Model<Schema>\n implements Authenticable\n{\n /**\n * The password hash never leaves the server through serialization:\n * `toJSON()` (so `response.json(user)`), lean query rows and embedded\n * copies all drop it, while `user.get(\"password\")` / `user.string(\"password\")`\n * still read it for verification. A subclass that sets its own `hidden`\n * replaces this list, so keep `\"password\"` in it.\n */\n public static hidden: string[] = [\"password\"];\n\n /**\n * Get user type\n */\n public abstract get userType(): string;\n\n /**\n * Get access token payload\n */\n public accessTokenPayload() {\n return authService.buildAccessTokenPayload(this);\n }\n\n /**\n * Create both access and refresh tokens\n */\n public async createTokenPair(deviceInfo?: DeviceInfo): Promise<TokenPair> {\n return authService.createTokenPair(this, deviceInfo);\n }\n\n /**\n * Generate access token\n */\n public async generateAccessToken(data?: any): Promise<AccessTokenOutput> {\n return authService.generateAccessToken(this, data);\n }\n\n /**\n * Generate refresh token\n */\n public async generateRefreshToken(deviceInfo?: DeviceInfo): Promise<RefreshToken | undefined> {\n return authService.createRefreshToken(this, deviceInfo);\n }\n\n /**\n * Remove current access token\n */\n public async removeAccessToken(token: string): Promise<void> {\n return authService.removeAccessToken(this, token);\n }\n\n /**\n * Remove refresh token\n */\n public async removeRefreshToken(token: string): Promise<void> {\n return authService.removeRefreshToken(this, token);\n }\n\n /**\n * Remove all access tokens\n */\n public async removeAllAccessTokens(): Promise<void> {\n return authService.removeAllAccessTokens(this);\n }\n\n /**\n * Revoke all tokens (logout from all devices)\n */\n public async revokeAllTokens(): Promise<void> {\n return authService.revokeAllTokens(this);\n }\n\n /**\n * Get active sessions\n */\n public async activeSessions(): Promise<RefreshToken[]> {\n return authService.getActiveSessions(this);\n }\n\n /**\n * Attempt to login the user\n */\n public static async attempt(this: ChildModel<Auth>, data: any): Promise<Auth | null> {\n return authService.attemptLogin(this, data);\n }\n\n /**\n * Confirm password\n */\n public async confirmPassword(password: string): Promise<boolean> {\n return authService.verifyPassword(password, this.string(\"password\")!);\n }\n}\n"],"mappings":";;;;;AAQA,IAAsB,OAAtB,cACU,MAEV;;gBAQmC,CAAC,UAAU;;;;;CAU5C,AAAO,qBAAqB;EAC1B,OAAO,YAAY,wBAAwB,IAAI;CACjD;;;;CAKA,MAAa,gBAAgB,YAA6C;EACxE,OAAO,YAAY,gBAAgB,MAAM,UAAU;CACrD;;;;CAKA,MAAa,oBAAoB,MAAwC;EACvE,OAAO,YAAY,oBAAoB,MAAM,IAAI;CACnD;;;;CAKA,MAAa,qBAAqB,YAA4D;EAC5F,OAAO,YAAY,mBAAmB,MAAM,UAAU;CACxD;;;;CAKA,MAAa,kBAAkB,OAA8B;EAC3D,OAAO,YAAY,kBAAkB,MAAM,KAAK;CAClD;;;;CAKA,MAAa,mBAAmB,OAA8B;EAC5D,OAAO,YAAY,mBAAmB,MAAM,KAAK;CACnD;;;;CAKA,MAAa,wBAAuC;EAClD,OAAO,YAAY,sBAAsB,IAAI;CAC/C;;;;CAKA,MAAa,kBAAiC;EAC5C,OAAO,YAAY,gBAAgB,IAAI;CACzC;;;;CAKA,MAAa,iBAA0C;EACrD,OAAO,YAAY,kBAAkB,IAAI;CAC3C;;;;CAKA,aAAoB,QAAgC,MAAiC;EACnF,OAAO,YAAY,aAAa,MAAM,IAAI;CAC5C;;;;CAKA,MAAa,gBAAgB,UAAoC;EAC/D,OAAO,YAAY,eAAe,UAAU,KAAK,OAAO,UAAU,CAAE;CACtE;AACF"}
|
|
@@ -97,8 +97,13 @@ export declare class OneTimeToken extends Model {
|
|
|
97
97
|
/**
|
|
98
98
|
* Hard-delete every spent row — expired, or consumed (used, invalidated by a
|
|
99
99
|
* newer token, or exhausted). Neither can ever be redeemed again, so nothing
|
|
100
|
-
* reads them.
|
|
101
|
-
* command
|
|
100
|
+
* reads them. Returns the number removed. Runs from the `auth.cleanup` CLI
|
|
101
|
+
* command.
|
|
102
|
+
*
|
|
103
|
+
* Two set-based deletes, never a read: the rows are not loaded into memory,
|
|
104
|
+
* so a table grown by anonymous passkey-option calls cannot make the cleanup
|
|
105
|
+
* run out of memory. A query-builder delete is a driver-level hard delete,
|
|
106
|
+
* so no token hash is copied into a trash collection.
|
|
102
107
|
*/
|
|
103
108
|
static purgeSpent(): Promise<number>;
|
|
104
109
|
/** Find a token by hash, scoped to a purpose — a token of the other purpose is not found. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"one-time-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/one-time-token.model.ts"],"mappings":";;;;YAMY;;;;;qBAWC,+CAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;qBAoBlB,qBAAqB;SAClB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;;;SAON;;;;;;;SAQA;;MAGH;;MAKA;;MAKA;;MAKA;;;;;;EAaE,mBAAmB;;SAYlB,MACZ,MAAM,MACN,SAAS,qBACT,mBACA,WAAW,OAAI,QAAA;;;;;SAiBH,eACZ,SAAS,qBACT,mBACA,WAAW,MACX,OAAO,OAAI,QAAA;;SAcC,cACZ,MAAM,MACN,SAAS,sBACR,QAAQ;;;;;;EAYE,cAAc,cAAc
|
|
1
|
+
{"version":3,"file":"one-time-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/one-time-token.model.ts"],"mappings":";;;;YAMY;;;;;qBAWC,+CAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;qBAoBlB,qBAAqB;SAClB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;;;SAON;;;;;;;SAQA;;MAGH;;MAKA;;MAKA;;MAKA;;;;;;EAaE,mBAAmB;;SAYlB,MACZ,MAAM,MACN,SAAS,qBACT,mBACA,WAAW,OAAI,QAAA;;;;;SAiBH,eACZ,SAAS,qBACT,mBACA,WAAW,MACX,OAAO,OAAI,QAAA;;SAcC,cACZ,MAAM,MACN,SAAS,sBACR,QAAQ;;;;;;EAYE,cAAc,cAAc;;;;;;;;;;;;SAwBrB,cAAc;;SAQpB,WACZ,mBACA,SAAS,sBACR,QAAQ;;;;;SAQG,oBAAoB,MAAM,MAAM,SAAS,sBAAsB"}
|
|
@@ -118,15 +118,16 @@ var OneTimeToken = class extends Model {
|
|
|
118
118
|
/**
|
|
119
119
|
* Hard-delete every spent row — expired, or consumed (used, invalidated by a
|
|
120
120
|
* newer token, or exhausted). Neither can ever be redeemed again, so nothing
|
|
121
|
-
* reads them.
|
|
122
|
-
* command
|
|
121
|
+
* reads them. Returns the number removed. Runs from the `auth.cleanup` CLI
|
|
122
|
+
* command.
|
|
123
|
+
*
|
|
124
|
+
* Two set-based deletes, never a read: the rows are not loaded into memory,
|
|
125
|
+
* so a table grown by anonymous passkey-option calls cannot make the cleanup
|
|
126
|
+
* run out of memory. A query-builder delete is a driver-level hard delete,
|
|
127
|
+
* so no token hash is copied into a trash collection.
|
|
123
128
|
*/
|
|
124
129
|
static async purgeSpent() {
|
|
125
|
-
|
|
126
|
-
const consumed = await this.query().whereNotNull("consumed_at").get();
|
|
127
|
-
const spent = new Map([...expired, ...consumed].map((token) => [String(token.id), token]));
|
|
128
|
-
for (const token of spent.values()) await token.destroy();
|
|
129
|
-
return spent.size;
|
|
130
|
+
return await this.query().where("expires_at", "<", /* @__PURE__ */ new Date()).delete() + await this.query().whereNotNull("consumed_at").delete();
|
|
130
131
|
}
|
|
131
132
|
/** Find a token by hash, scoped to a purpose — a token of the other purpose is not found. */
|
|
132
133
|
static findByHash(tokenHash, purpose) {
|