@basaltkit/auth 2.2.0 → 3.1.0

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/dist/routes.d.ts CHANGED
@@ -17,9 +17,43 @@ export interface PasswordPolicy {
17
17
  minLength?: number;
18
18
  }
19
19
  export interface AuthRoutesOptions {
20
- /** A minimum length, or the schema itself. Default: `min(8)`. */
20
+ /**
21
+ * A minimum length, or the schema itself. Default: `min(8)`. Whatever the
22
+ * policy, passwords are capped at {@link MAX_PASSWORD_LENGTH} characters
23
+ * before it runs, so an oversized body never reaches the password hasher.
24
+ */
21
25
  password?: PasswordPolicy | z.ZodType<string>;
26
+ /**
27
+ * Per-route rate limit (`meta.rateLimit`, enforced per client ip by
28
+ * `securityPlugin` when its rate limiter is on) for the unauthenticated
29
+ * routes that hash, mail or guess: register, login, verification requests
30
+ * and password forgot/reset.
31
+ * Default {@link DEFAULT_AUTH_RATE_LIMIT}; pass `false` to omit it.
32
+ */
33
+ rateLimit?: {
34
+ limit: number;
35
+ windowMs: number;
36
+ } | false;
22
37
  }
38
+ /**
39
+ * Route meta shared by the account routes (sign-in, profile, MFA self-service):
40
+ * `account: true` exempts them from tenant-membership guards (they are about
41
+ * the caller, not a tenant's data — `@basaltkit/teams` honours it) and
42
+ * `mfa: false` keeps them reachable before MFA under `requireMfa`.
43
+ */
44
+ export declare const ACCOUNT_META: {
45
+ readonly account: true;
46
+ readonly mfa: false;
47
+ };
48
+ /** RFC 5321 caps a forward path at 254 characters. */
49
+ export declare const MAX_EMAIL_LENGTH = 254;
50
+ /** Far above any passphrase; bounds the work an unauthenticated body can cause. */
51
+ export declare const MAX_PASSWORD_LENGTH = 1024;
52
+ /** Default `meta.rateLimit` on the public auth routes: 10 requests per minute per ip and route. */
53
+ export declare const DEFAULT_AUTH_RATE_LIMIT: {
54
+ readonly limit: 10;
55
+ readonly windowMs: 60000;
56
+ };
23
57
  /**
24
58
  * Ready-made auth routes — register them in fastifyPlugin({ routes }):
25
59
  * register · login · refresh · logout · me, plus email verification
package/dist/routes.js CHANGED
@@ -1,16 +1,32 @@
1
1
  import { ctx, BasaltError } from '@basaltkit/core';
2
2
  import { route } from '@basaltkit/http';
3
3
  import { z } from 'zod';
4
- import { AUTH } from './plugin.js';
4
+ import { AUTH, CsrfRejectedError, isCsrfRejected } from './plugin.js';
5
5
  import { API_KEYS } from './apikeys-plugin.js';
6
- const DEFAULT_PASSWORD = z.string().min(8);
6
+ /**
7
+ * Route meta shared by the account routes (sign-in, profile, MFA self-service):
8
+ * `account: true` exempts them from tenant-membership guards (they are about
9
+ * the caller, not a tenant's data — `@basaltkit/teams` honours it) and
10
+ * `mfa: false` keeps them reachable before MFA under `requireMfa`.
11
+ */
12
+ export const ACCOUNT_META = { account: true, mfa: false };
13
+ /** RFC 5321 caps a forward path at 254 characters. */
14
+ export const MAX_EMAIL_LENGTH = 254;
15
+ /** Far above any passphrase; bounds the work an unauthenticated body can cause. */
16
+ export const MAX_PASSWORD_LENGTH = 1024;
17
+ /** Default `meta.rateLimit` on the public auth routes: 10 requests per minute per ip and route. */
18
+ export const DEFAULT_AUTH_RATE_LIMIT = { limit: 10, windowMs: 60_000 };
19
+ const email = () => z.string().trim().max(MAX_EMAIL_LENGTH).email();
20
+ const token = () => z.string().max(512);
21
+ const DEFAULT_PASSWORD = z.string().min(8).max(MAX_PASSWORD_LENGTH);
7
22
  const passwordSchema = (policy) => {
8
23
  if (!policy)
9
24
  return DEFAULT_PASSWORD;
10
- if (typeof policy.safeParse === 'function')
11
- return policy;
25
+ if (typeof policy.safeParse === 'function') {
26
+ return z.string().max(MAX_PASSWORD_LENGTH).pipe(policy);
27
+ }
12
28
  const { minLength } = policy;
13
- return minLength === undefined ? DEFAULT_PASSWORD : z.string().min(minLength);
29
+ return minLength === undefined ? DEFAULT_PASSWORD : z.string().min(minLength).max(MAX_PASSWORD_LENGTH);
14
30
  };
15
31
  const auth = () => ctx().container.get(AUTH);
16
32
  const apiKeys = () => ctx().container.get(API_KEYS);
@@ -23,11 +39,16 @@ const apiKeys = () => ctx().container.get(API_KEYS);
23
39
  */
24
40
  export function authRoutes(options = {}) {
25
41
  const password = passwordSchema(options.password);
26
- const credentials = z.object({ email: z.string().email(), password });
42
+ const credentials = z.object({ email: email(), password });
43
+ const limit = options.rateLimit === false ? {} : { rateLimit: options.rateLimit ?? { ...DEFAULT_AUTH_RATE_LIMIT } };
44
+ // Every route here is about the caller's own account: exempt from the
45
+ // tenant-membership guard (`account`) and reachable before MFA (`mfa: false`).
46
+ const account = ACCOUNT_META;
27
47
  return [
28
48
  route({
29
49
  method: 'POST',
30
50
  url: '/auth/register',
51
+ meta: { ...account, ...limit },
31
52
  body: credentials,
32
53
  // Enumeration-safe: the same 202 whether the email is new or already taken
33
54
  // (a collision is signalled out-of-band via auth:register_existing_email).
@@ -39,10 +60,11 @@ export function authRoutes(options = {}) {
39
60
  route({
40
61
  method: 'POST',
41
62
  url: '/auth/login',
42
- body: credentials.extend({ mfaCode: z.string().optional() }),
63
+ meta: { ...account, ...limit },
64
+ body: credentials.extend({ mfaCode: z.string().max(64).optional() }),
43
65
  async handler({ body, request, reply }) {
44
- const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
45
- const session = await auth().createSession(user.id);
66
+ const { user, tokens, amr } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
67
+ const session = await auth().createSession(user.id, { amr });
46
68
  const sessionCookie = auth().sessionCookieHeader(session.id);
47
69
  if (sessionCookie)
48
70
  reply.header('set-cookie', sessionCookie);
@@ -52,7 +74,8 @@ export function authRoutes(options = {}) {
52
74
  route({
53
75
  method: 'POST',
54
76
  url: '/auth/refresh',
55
- body: z.object({ refreshToken: z.string() }),
77
+ meta: { ...account },
78
+ body: z.object({ refreshToken: token() }),
56
79
  async handler({ body }) {
57
80
  return auth().refresh(body.refreshToken);
58
81
  },
@@ -60,12 +83,27 @@ export function authRoutes(options = {}) {
60
83
  route({
61
84
  method: 'POST',
62
85
  url: '/auth/logout',
63
- body: z.object({ refreshToken: z.string() }),
86
+ meta: { ...account },
87
+ // The refresh token is optional: a SPA on the HttpOnly session cookie
88
+ // alone never sees one, and ends its session with an empty body.
89
+ body: z.object({ refreshToken: token().optional() }).optional(),
64
90
  async handler({ body, request, reply }) {
65
- await auth().revoke(body.refreshToken);
66
- const sessionId = auth().sessionIdFromCookie(request.headers.cookie);
67
- if (sessionId)
68
- await auth().logout(sessionId);
91
+ const refreshToken = body?.refreshToken;
92
+ if (refreshToken)
93
+ await auth().revoke(refreshToken);
94
+ const headerSession = request.headers['x-session-id'];
95
+ if (typeof headerSession === 'string')
96
+ await auth().logout(headerSession);
97
+ const cookieSession = auth().sessionIdFromCookie(request.headers.cookie);
98
+ if (cookieSession && isCsrfRejected(ctx())) {
99
+ // A cross-site request must not end the cookie session (logout CSRF).
100
+ // With nothing else to act on, say so instead of a silent 204.
101
+ if (!refreshToken && typeof headerSession !== 'string')
102
+ throw new CsrfRejectedError();
103
+ return reply.code(204).send();
104
+ }
105
+ if (cookieSession)
106
+ await auth().logout(cookieSession);
69
107
  const expiredCookie = auth().expiredSessionCookieHeader();
70
108
  if (expiredCookie)
71
109
  reply.header('set-cookie', expiredCookie);
@@ -75,7 +113,7 @@ export function authRoutes(options = {}) {
75
113
  route({
76
114
  method: 'GET',
77
115
  url: '/auth/me',
78
- meta: { auth: true },
116
+ meta: { auth: true, ...account },
79
117
  async handler() {
80
118
  return ctx().user;
81
119
  },
@@ -84,7 +122,8 @@ export function authRoutes(options = {}) {
84
122
  route({
85
123
  method: 'POST',
86
124
  url: '/auth/verify/request',
87
- body: z.object({ email: z.string().email() }),
125
+ meta: { ...account, ...limit },
126
+ body: z.object({ email: email() }),
88
127
  async handler({ body }) {
89
128
  // The app emails the token (via the auth:verify_requested hook). Always
90
129
  // 200, so the response never reveals whether the email has an account.
@@ -95,7 +134,8 @@ export function authRoutes(options = {}) {
95
134
  route({
96
135
  method: 'POST',
97
136
  url: '/auth/verify',
98
- body: z.object({ token: z.string() }),
137
+ meta: { ...account },
138
+ body: z.object({ token: token() }),
99
139
  async handler({ body }) {
100
140
  return { user: await auth().verifyEmail(body.token) };
101
141
  },
@@ -104,7 +144,8 @@ export function authRoutes(options = {}) {
104
144
  route({
105
145
  method: 'POST',
106
146
  url: '/auth/password/forgot',
107
- body: z.object({ email: z.string().email() }),
147
+ meta: { ...account, ...limit },
148
+ body: z.object({ email: email() }),
108
149
  async handler({ body }) {
109
150
  await auth().requestPasswordReset(body.email);
110
151
  return { ok: true };
@@ -116,7 +157,8 @@ export function authRoutes(options = {}) {
116
157
  // The same policy as register. Covering register and leaving reset behind
117
158
  // would let anyone walk a strong password back down to eight characters
118
159
  // through "forgot password" — a loophole worse than having no option.
119
- body: z.object({ token: z.string(), password }),
160
+ meta: { ...account, ...limit },
161
+ body: z.object({ token: token(), password }),
120
162
  async handler({ body }) {
121
163
  await auth().resetPassword(body.token, body.password);
122
164
  return { ok: true };
@@ -150,7 +192,9 @@ export function apiKeyRoutes() {
150
192
  route({
151
193
  method: 'POST',
152
194
  url: '/apikeys',
153
- meta: { auth: true },
195
+ // Session-only: a key must never mint, list or revoke keys (a narrow or
196
+ // expiring key could otherwise mint a permanent '*' key).
197
+ meta: { auth: true, apiKey: false },
154
198
  body: z.object({
155
199
  name: z.string().min(1).max(100),
156
200
  scopes: z.array(z.string().min(1)).optional(),
@@ -165,7 +209,9 @@ export function apiKeyRoutes() {
165
209
  route({
166
210
  method: 'GET',
167
211
  url: '/apikeys',
168
- meta: { auth: true },
212
+ // Session-only: a key must never mint, list or revoke keys (a narrow or
213
+ // expiring key could otherwise mint a permanent '*' key).
214
+ meta: { auth: true, apiKey: false },
169
215
  async handler() {
170
216
  return apiKeys().list(scope());
171
217
  },
@@ -173,7 +219,7 @@ export function apiKeyRoutes() {
173
219
  route({
174
220
  method: 'DELETE',
175
221
  url: '/apikeys/:id',
176
- meta: { auth: true },
222
+ meta: { auth: true, apiKey: false },
177
223
  params: z.object({ id: z.string() }),
178
224
  async handler({ params, reply }) {
179
225
  const record = await apiKeys().get(params.id);
@@ -211,7 +257,7 @@ export function mfaRoutes() {
211
257
  route({
212
258
  method: 'POST',
213
259
  url: '/auth/mfa/enroll',
214
- meta: { auth: true },
260
+ meta: { auth: true, apiKey: false, ...ACCOUNT_META },
215
261
  async handler() {
216
262
  return auth().enrollMfa(currentUserId());
217
263
  },
@@ -219,8 +265,8 @@ export function mfaRoutes() {
219
265
  route({
220
266
  method: 'POST',
221
267
  url: '/auth/mfa/activate',
222
- meta: { auth: true },
223
- body: z.object({ code: z.string().min(6) }),
268
+ meta: { auth: true, apiKey: false, ...ACCOUNT_META },
269
+ body: z.object({ code: z.string().min(6).max(64) }),
224
270
  async handler({ body }) {
225
271
  return auth().activateMfa(currentUserId(), body.code);
226
272
  },
@@ -228,7 +274,7 @@ export function mfaRoutes() {
228
274
  route({
229
275
  method: 'GET',
230
276
  url: '/auth/mfa/status',
231
- meta: { auth: true },
277
+ meta: { auth: true, apiKey: false, ...ACCOUNT_META },
232
278
  async handler() {
233
279
  return auth().mfaStatus(currentUserId());
234
280
  },
@@ -236,8 +282,10 @@ export function mfaRoutes() {
236
282
  route({
237
283
  method: 'POST',
238
284
  url: '/auth/mfa/disable',
239
- meta: { auth: true },
240
- body: z.object({ code: z.string().min(6) }),
285
+ // Account route, but NOT exempt from `requireMfa`: switching MFA off
286
+ // under the policy needs an MFA sign-in.
287
+ meta: { auth: true, apiKey: false, account: true },
288
+ body: z.object({ code: z.string().min(6).max(64) }),
241
289
  async handler({ body, reply }) {
242
290
  await auth().disableMfa(currentUserId(), body.code);
243
291
  return reply.code(204).send();
package/dist/stores.d.ts CHANGED
@@ -131,12 +131,26 @@ export interface MfaStore {
131
131
  get(userId: string): Promise<MfaRecord | null>;
132
132
  set(userId: string, record: MfaRecord): Promise<void>;
133
133
  delete(userId: string): Promise<void>;
134
+ /**
135
+ * Atomically records `step` as the last accepted TOTP step, only if MFA is
136
+ * enabled and no step ≥ `step` was accepted before (a conditional UPDATE).
137
+ * Returns whether THIS call consumed it. Optional: without it, Auth falls back
138
+ * to get → set, which lets two parallel requests replay the same code.
139
+ */
140
+ consumeTotpStep?(userId: string, step: number): Promise<boolean>;
141
+ /**
142
+ * Atomically removes the recovery-code hash, returning whether THIS call
143
+ * removed it (a compare-and-swap). Optional, with the same fallback caveat.
144
+ */
145
+ consumeRecoveryCode?(userId: string, hash: string): Promise<boolean>;
134
146
  }
135
147
  export declare class MemoryMfaStore implements MfaStore {
136
148
  private readonly records;
137
149
  get(userId: string): Promise<MfaRecord | null>;
138
150
  set(userId: string, record: MfaRecord): Promise<void>;
139
151
  delete(userId: string): Promise<void>;
152
+ consumeTotpStep(userId: string, step: number): Promise<boolean>;
153
+ consumeRecoveryCode(userId: string, hash: string): Promise<boolean>;
140
154
  }
141
155
  /**
142
156
  * Per-user access-token version. Access tokens carry the version they were
package/dist/stores.js CHANGED
@@ -4,8 +4,11 @@ const hashSessionId = (id) => createHash('sha256').update(id).digest('hex');
4
4
  export class MemoryUserSource {
5
5
  users = new Map();
6
6
  async findByEmail(email) {
7
+ // Emails are case-insensitive identities (Auth canonicalises them; this also
8
+ // matches rows written before that, in whatever case they were stored).
9
+ const wanted = email.trim().toLowerCase();
7
10
  for (const user of this.users.values()) {
8
- if (user.email === email)
11
+ if (user.email.toLowerCase() === wanted)
9
12
  return user;
10
13
  }
11
14
  return null;
@@ -98,6 +101,26 @@ export class MemoryMfaStore {
98
101
  async delete(userId) {
99
102
  this.records.delete(userId);
100
103
  }
104
+ // Synchronous check-and-set: no await between the read and the write.
105
+ async consumeTotpStep(userId, step) {
106
+ const record = this.records.get(userId);
107
+ if (!record || !record.enabled)
108
+ return false;
109
+ if (record.lastUsedStep !== undefined && step <= record.lastUsedStep)
110
+ return false;
111
+ record.lastUsedStep = step;
112
+ return true;
113
+ }
114
+ async consumeRecoveryCode(userId, hash) {
115
+ const record = this.records.get(userId);
116
+ if (!record || !record.enabled)
117
+ return false;
118
+ const index = record.recoveryCodes.indexOf(hash);
119
+ if (index === -1)
120
+ return false;
121
+ record.recoveryCodes.splice(index, 1);
122
+ return true;
123
+ }
101
124
  }
102
125
  export class MemoryTokenVersionStore {
103
126
  versions = new Map();
@@ -5,28 +5,125 @@ export declare class AccountLockedError extends BasaltError {
5
5
  readonly status = 429;
6
6
  constructor(retryAfterMs: number);
7
7
  }
8
+ /** A throttle counter's state within its current window. */
9
+ export interface ThrottleWindow {
10
+ /** Attempts counted in the current window. */
11
+ count: number;
12
+ /** Milliseconds until the window closes and the counter starts over. */
13
+ retryAfterMs: number;
14
+ }
15
+ /**
16
+ * Where throttle counters live. The default {@link MemoryThrottleStore} is per
17
+ * process; pass a shared one ({@link RedisThrottleStore}) so every replica of a
18
+ * cluster spends ONE budget — otherwise an attacker gets `maxAttempts` guesses
19
+ * per replica, and a lockout on one replica is not seen by the others.
20
+ *
21
+ * Methods may be sync or async: an in-process store stays synchronous (so the
22
+ * count moves before any await), a network store returns promises. `hit` MUST
23
+ * be atomic — increment and read in one step — since it is what bounds a
24
+ * parallel burst. Keys arrive already digested (never a raw email).
25
+ */
26
+ export interface ThrottleStore {
27
+ /**
28
+ * Atomically counts one attempt and returns the new state. The first hit of
29
+ * a key opens a fixed window of `windowMs`; later hits do not extend it.
30
+ */
31
+ hit(key: string, windowMs: number): ThrottleWindow | Promise<ThrottleWindow>;
32
+ /** The current state without counting; null when the key has no live window. */
33
+ peek(key: string): ThrottleWindow | null | Promise<ThrottleWindow | null>;
34
+ /** Gives one attempt back (a successful attempt must not consume budget). */
35
+ release(key: string): void | Promise<void>;
36
+ /** Forgets the key. */
37
+ reset(key: string): void | Promise<void>;
38
+ }
39
+ export interface MemoryThrottleStoreOptions {
40
+ /**
41
+ * Upper bound on tracked keys. When full, expired entries are swept and then
42
+ * the oldest ones are evicted, so failed logins with unique identifiers
43
+ * cannot grow the heap without limit. Default 100 000.
44
+ */
45
+ maxEntries?: number;
46
+ /** Injectable clock for tests. */
47
+ clock?: () => number;
48
+ }
49
+ /** In-process {@link ThrottleStore} (the default): synchronous and bounded. */
50
+ export declare class MemoryThrottleStore implements ThrottleStore {
51
+ private readonly entries;
52
+ private readonly maxEntries;
53
+ private readonly clock;
54
+ constructor(options?: MemoryThrottleStoreOptions);
55
+ /** Number of keys currently tracked. */
56
+ get size(): number;
57
+ /** Total characters retained in keys — diagnostics for memory bounds. */
58
+ retainedKeyChars(): number;
59
+ private live;
60
+ private store;
61
+ hit(key: string, windowMs: number): ThrottleWindow;
62
+ peek(key: string): ThrottleWindow | null;
63
+ release(key: string): void;
64
+ reset(key: string): void;
65
+ }
8
66
  export interface LoginThrottleOptions {
9
67
  /** Failed attempts allowed within the window. Default 5. */
10
68
  maxAttempts?: number;
11
- /** Rolling window in ms. Default 15 minutes. */
69
+ /** Fixed window in ms, opened by the first attempt. Default 15 minutes. */
12
70
  windowMs?: number;
13
- /** Injectable clock for tests. */
71
+ /**
72
+ * Where the counters live. Default: a private {@link MemoryThrottleStore}
73
+ * (per process). Pass a shared store — e.g. {@link RedisThrottleStore} — to
74
+ * enforce one budget across every replica.
75
+ */
76
+ store?: ThrottleStore;
77
+ /**
78
+ * Key prefix separating this throttle's counters from others sharing the
79
+ * same store (Auth uses `login`, `login-ip` and `email-request`).
80
+ */
81
+ namespace?: string;
82
+ /** Bound of the default in-memory store (ignored with `store`). Default 100 000. */
83
+ maxEntries?: number;
84
+ /** Injectable clock for the default in-memory store (ignored with `store`). */
14
85
  clock?: () => number;
15
86
  }
87
+ type Awaitable<T> = T | Promise<T>;
16
88
  /**
17
89
  * Brute-force guard: counts failed logins per identifier (email) within a
18
- * rolling window and locks the account once the budget is spent. A successful
19
- * login clears the counter. In-memory per process; back it with Redis for a
20
- * cluster by supplying the same behavior.
90
+ * fixed window and locks the account once the budget is spent. A successful
91
+ * login clears the counter. Counters live in a {@link ThrottleStore}: in memory
92
+ * per process by default, or shared across replicas (Redis).
93
+ *
94
+ * Identifiers are handed to the store as SHA-256 digests (fixed size, never
95
+ * the raw email).
96
+ *
97
+ * Use {@link reserve} before verifying credentials: it counts the attempt
98
+ * atomically (synchronously with the memory store, in one Redis script with a
99
+ * shared one), so a parallel burst cannot run more verifications than the
100
+ * budget allows. {@link release} gives the reservation back on success.
101
+ *
102
+ * Every method returns synchronously with a synchronous store (the default)
103
+ * and a promise otherwise; `await` the result when the store may be async.
21
104
  */
22
105
  export declare class LoginThrottle {
23
- private readonly failures;
106
+ private readonly store;
24
107
  private readonly maxAttempts;
25
108
  private readonly windowMs;
26
- private readonly clock;
109
+ private readonly prefix;
27
110
  constructor(options?: LoginThrottleOptions);
111
+ /** Number of identifiers currently tracked (in-memory store only; 0 otherwise). */
112
+ get size(): number;
113
+ /** Total characters retained in keys — diagnostics for memory bounds (in-memory store only). */
114
+ retainedKeyChars(): number;
115
+ private key;
28
116
  /** Throws {@link AccountLockedError} when the key is currently locked. */
29
- assertAllowed(key: string): void;
30
- recordFailure(key: string): void;
31
- reset(key: string): void;
117
+ assertAllowed(key: string): Awaitable<void>;
118
+ recordFailure(key: string): Awaitable<void>;
119
+ /**
120
+ * Atomically counts this attempt and throws {@link AccountLockedError} when
121
+ * it exceeds the budget. Pair with {@link release} on success; a failure
122
+ * simply keeps the reservation.
123
+ */
124
+ reserve(key: string): Awaitable<void>;
125
+ /** Returns one reservation (a successful attempt must not consume budget). */
126
+ release(key: string): Awaitable<void>;
127
+ reset(key: string): Awaitable<void>;
32
128
  }
129
+ export {};
package/dist/throttle.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { BasaltError } from '@basaltkit/core';
2
3
  /** Raised when an identifier has exceeded the failed-login budget. */
3
4
  export class AccountLockedError extends BasaltError {
@@ -8,38 +9,147 @@ export class AccountLockedError extends BasaltError {
8
9
  this.retryAfterMs = retryAfterMs;
9
10
  }
10
11
  }
12
+ /** In-process {@link ThrottleStore} (the default): synchronous and bounded. */
13
+ export class MemoryThrottleStore {
14
+ entries = new Map();
15
+ maxEntries;
16
+ clock;
17
+ constructor(options = {}) {
18
+ this.maxEntries = Math.max(1, options.maxEntries ?? 100_000);
19
+ this.clock = options.clock ?? (() => Date.now());
20
+ }
21
+ /** Number of keys currently tracked. */
22
+ get size() {
23
+ return this.entries.size;
24
+ }
25
+ /** Total characters retained in keys — diagnostics for memory bounds. */
26
+ retainedKeyChars() {
27
+ let n = 0;
28
+ for (const key of this.entries.keys())
29
+ n += key.length;
30
+ return n;
31
+ }
32
+ live(key, now) {
33
+ const entry = this.entries.get(key);
34
+ if (entry && now >= entry.resetAt) {
35
+ this.entries.delete(key);
36
+ return undefined;
37
+ }
38
+ return entry;
39
+ }
40
+ store(key, entry, now) {
41
+ if (!this.entries.has(key) && this.entries.size >= this.maxEntries) {
42
+ for (const [k, e] of this.entries)
43
+ if (now >= e.resetAt)
44
+ this.entries.delete(k);
45
+ // Still full: evict the oldest entries (Map iterates in insertion order).
46
+ for (const k of this.entries.keys()) {
47
+ if (this.entries.size < this.maxEntries)
48
+ break;
49
+ this.entries.delete(k);
50
+ }
51
+ }
52
+ this.entries.set(key, entry);
53
+ }
54
+ hit(key, windowMs) {
55
+ const now = this.clock();
56
+ const entry = this.live(key, now) ?? { count: 0, resetAt: now + windowMs };
57
+ entry.count += 1;
58
+ this.store(key, entry, now);
59
+ return { count: entry.count, retryAfterMs: entry.resetAt - now };
60
+ }
61
+ peek(key) {
62
+ const now = this.clock();
63
+ const entry = this.live(key, now);
64
+ return entry ? { count: entry.count, retryAfterMs: entry.resetAt - now } : null;
65
+ }
66
+ release(key) {
67
+ const entry = this.live(key, this.clock());
68
+ if (!entry)
69
+ return;
70
+ entry.count -= 1;
71
+ if (entry.count <= 0)
72
+ this.entries.delete(key);
73
+ }
74
+ reset(key) {
75
+ this.entries.delete(key);
76
+ }
77
+ }
78
+ const isPromise = (value) => typeof value?.then === 'function';
79
+ /** Runs `next` on a value that may or may not be a promise — sync in, sync out. */
80
+ function chain(value, next) {
81
+ return isPromise(value) ? value.then(next) : next(value);
82
+ }
11
83
  /**
12
84
  * Brute-force guard: counts failed logins per identifier (email) within a
13
- * rolling window and locks the account once the budget is spent. A successful
14
- * login clears the counter. In-memory per process; back it with Redis for a
15
- * cluster by supplying the same behavior.
85
+ * fixed window and locks the account once the budget is spent. A successful
86
+ * login clears the counter. Counters live in a {@link ThrottleStore}: in memory
87
+ * per process by default, or shared across replicas (Redis).
88
+ *
89
+ * Identifiers are handed to the store as SHA-256 digests (fixed size, never
90
+ * the raw email).
91
+ *
92
+ * Use {@link reserve} before verifying credentials: it counts the attempt
93
+ * atomically (synchronously with the memory store, in one Redis script with a
94
+ * shared one), so a parallel burst cannot run more verifications than the
95
+ * budget allows. {@link release} gives the reservation back on success.
96
+ *
97
+ * Every method returns synchronously with a synchronous store (the default)
98
+ * and a promise otherwise; `await` the result when the store may be async.
16
99
  */
17
100
  export class LoginThrottle {
18
- failures = new Map();
101
+ store;
19
102
  maxAttempts;
20
103
  windowMs;
21
- clock;
104
+ prefix;
22
105
  constructor(options = {}) {
23
106
  this.maxAttempts = options.maxAttempts ?? 5;
24
107
  this.windowMs = options.windowMs ?? 15 * 60_000;
25
- this.clock = options.clock ?? (() => Date.now());
108
+ this.prefix = options.namespace ? `${options.namespace}:` : '';
109
+ this.store =
110
+ options.store ??
111
+ new MemoryThrottleStore({
112
+ ...(options.maxEntries !== undefined ? { maxEntries: options.maxEntries } : {}),
113
+ ...(options.clock ? { clock: options.clock } : {}),
114
+ });
115
+ }
116
+ /** Number of identifiers currently tracked (in-memory store only; 0 otherwise). */
117
+ get size() {
118
+ return this.store instanceof MemoryThrottleStore ? this.store.size : 0;
119
+ }
120
+ /** Total characters retained in keys — diagnostics for memory bounds (in-memory store only). */
121
+ retainedKeyChars() {
122
+ return this.store instanceof MemoryThrottleStore ? this.store.retainedKeyChars() : 0;
123
+ }
124
+ key(key) {
125
+ return `${this.prefix}${createHash('sha256').update(key).digest('base64url')}`;
26
126
  }
27
127
  /** Throws {@link AccountLockedError} when the key is currently locked. */
28
128
  assertAllowed(key) {
29
- const entry = this.failures.get(key);
30
- if (entry && this.clock() < entry.resetAt && entry.count >= this.maxAttempts) {
31
- throw new AccountLockedError(entry.resetAt - this.clock());
32
- }
129
+ return chain(this.store.peek(this.key(key)), (window) => {
130
+ if (window && window.count >= this.maxAttempts)
131
+ throw new AccountLockedError(window.retryAfterMs);
132
+ });
33
133
  }
34
134
  recordFailure(key) {
35
- const now = this.clock();
36
- let entry = this.failures.get(key);
37
- if (!entry || now >= entry.resetAt)
38
- entry = { count: 0, resetAt: now + this.windowMs };
39
- entry.count += 1;
40
- this.failures.set(key, entry);
135
+ return chain(this.store.hit(this.key(key), this.windowMs), () => undefined);
136
+ }
137
+ /**
138
+ * Atomically counts this attempt and throws {@link AccountLockedError} when
139
+ * it exceeds the budget. Pair with {@link release} on success; a failure
140
+ * simply keeps the reservation.
141
+ */
142
+ reserve(key) {
143
+ return chain(this.store.hit(this.key(key), this.windowMs), (window) => {
144
+ if (window.count > this.maxAttempts)
145
+ throw new AccountLockedError(window.retryAfterMs);
146
+ });
147
+ }
148
+ /** Returns one reservation (a successful attempt must not consume budget). */
149
+ release(key) {
150
+ return this.store.release(this.key(key));
41
151
  }
42
152
  reset(key) {
43
- this.failures.delete(key);
153
+ return this.store.reset(this.key(key));
44
154
  }
45
155
  }
@@ -5,7 +5,15 @@ export const WEBAUTHN = createToken('auth:webauthn');
5
5
  export function webauthnPlugin(options) {
6
6
  return definePlugin({
7
7
  name: 'basalt:auth-webauthn',
8
- register({ container }) {
8
+ register({ container, hooks }) {
9
+ // Passkeys enrolled on a never-verified account by whoever registered it
10
+ // are login credentials too: a verified social login adopting the account
11
+ // removes them with the rest.
12
+ hooks.on('auth:social_account_adopted', async ({ user }) => {
13
+ const service = container.get(WEBAUTHN);
14
+ for (const credential of await service.list(user.id))
15
+ await service.remove(credential.id);
16
+ });
9
17
  container.singleton(WEBAUTHN, () => new WebAuthnService({
10
18
  config: options.config,
11
19
  verifier: options.verifier,