@basaltkit/auth 2.2.0 → 3.0.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/oauth.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { BasaltError } from '@basaltkit/core';
3
3
  /** Strip trailing '/' without a backtracking regex (avoids ReDoS on long runs). */
4
4
  export function stripTrailingSlashes(s) {
@@ -136,11 +136,25 @@ export async function discoverOidcProvider(config) {
136
136
  ...(config.scopes ? { scopes: config.scopes } : {}),
137
137
  });
138
138
  }
139
+ const sha256 = (value) => createHash('sha256').update(value).digest('base64url');
140
+ const safeEqual = (a, b) => {
141
+ const x = Buffer.from(a);
142
+ const y = Buffer.from(b);
143
+ return x.length === y.length && timingSafeEqual(x, y);
144
+ };
145
+ /** Cap on remembered (consumed) states; each lives only until its expiry. */
146
+ const MAX_CONSUMED_STATES = 100_000;
139
147
  /**
140
148
  * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
141
149
  * build an authorize URL with a signed, expiring `state`, then exchange the code
142
150
  * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
143
- * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
151
+ *
152
+ * The flow is bound to the browser that started it: {@link authorize} returns a
153
+ * random `binding` the caller stores in an HttpOnly cookie ({@link oauthRoutes}
154
+ * does). The signed `state` carries its hash, the PKCE verifier (S256) and the
155
+ * OIDC nonce are derived from it, and the callback requires it back — so an
156
+ * attacker's callback URL opened in a victim's browser (login CSRF) or an
157
+ * injected authorization code is refused. Each `state` is single-use.
144
158
  */
145
159
  export class OAuth {
146
160
  auth;
@@ -166,32 +180,103 @@ export class OAuth {
166
180
  throw new OAuthProviderUnknownError(name);
167
181
  return p;
168
182
  }
169
- /** The provider's authorization URL to redirect the browser to. */
170
- authorizeUrl(name, redirectUri) {
183
+ /**
184
+ * Starts a login: returns the provider's authorization URL to redirect the
185
+ * browser to, and the `binding` to keep in an HttpOnly cookie until the
186
+ * callback (pass it back to {@link callback}).
187
+ */
188
+ authorize(name, redirectUri) {
189
+ const binding = randomBytes(32).toString('base64url');
190
+ return { url: this.authorizeUrl(name, redirectUri, binding), binding };
191
+ }
192
+ /**
193
+ * The provider's authorization URL for a caller-managed `binding` (at least
194
+ * 32 characters of randomness, stored where only the initiating browser can
195
+ * present it). Prefer {@link authorize}, which generates one.
196
+ */
197
+ authorizeUrl(name, redirectUri, binding) {
198
+ if (typeof binding !== 'string' || binding.length < 32)
199
+ throw new OAuthStateInvalidError();
171
200
  const p = this.provider(name);
172
- const state = this.signState({ n: randomBytes(16).toString('hex'), e: this.now() + this.stateTtl, p: name });
201
+ const state = this.signState({
202
+ n: randomBytes(16).toString('hex'),
203
+ e: this.now() + this.stateTtl,
204
+ p: name,
205
+ b: sha256(binding),
206
+ });
173
207
  const params = new URLSearchParams({
174
208
  client_id: p.clientId,
175
209
  redirect_uri: redirectUri,
176
210
  response_type: 'code',
177
211
  scope: p.scopes.join(' '),
178
212
  state,
213
+ code_challenge: sha256(this.derive('pkce', binding)),
214
+ code_challenge_method: 'S256',
179
215
  });
216
+ if (p.scopes.includes('openid'))
217
+ params.set('nonce', this.derive('nonce', binding));
180
218
  return `${p.authorizeUrl}?${params.toString()}`;
181
219
  }
182
- /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
220
+ /**
221
+ * Verifies `state` against the browser `binding`, consumes it (single-use),
222
+ * exchanges the code with the PKCE verifier, fetches the profile, and logs in.
223
+ */
183
224
  async callback(name, input) {
184
225
  const payload = this.verifyState(input.state);
185
226
  if (payload.p !== name)
186
227
  throw new OAuthStateInvalidError();
228
+ if (!input.binding || typeof payload.b !== 'string' || !safeEqual(sha256(input.binding), payload.b)) {
229
+ throw new OAuthStateInvalidError();
230
+ }
231
+ this.consumeState(payload);
187
232
  const p = this.provider(name);
188
- const accessToken = await this.exchangeCode(p, input.code, input.redirectUri);
233
+ const { accessToken, idToken } = await this.exchangeCode(p, input.code, input.redirectUri, this.derive('pkce', input.binding));
234
+ if (p.scopes.includes('openid') && idToken !== undefined)
235
+ this.checkNonce(idToken, this.derive('nonce', input.binding));
189
236
  const profile = await p.fetchProfile(accessToken, this.doFetch);
190
237
  if (!profile.email)
191
238
  throw new OAuthExchangeError('provider returned no email');
192
- return this.auth.socialLogin(profile.email, { emailVerified: profile.emailVerified === true });
239
+ return this.auth.socialLogin(profile.email, {
240
+ emailVerified: profile.emailVerified === true,
241
+ ...(this.options.mfa ? { mfa: this.options.mfa } : {}),
242
+ });
243
+ }
244
+ /** A per-flow secret derived from the binding (PKCE verifier, OIDC nonce): 43 url-safe chars. */
245
+ derive(label, binding) {
246
+ return createHmac('sha256', this.options.secret).update(`oauth:${label}:${binding}`).digest('base64url');
247
+ }
248
+ /** Single-use: a state nonce is remembered until it expires. */
249
+ consumed = new Map();
250
+ consumeState(payload) {
251
+ const now = this.now();
252
+ if (this.consumed.size >= MAX_CONSUMED_STATES) {
253
+ for (const [n, exp] of this.consumed)
254
+ if (now > exp)
255
+ this.consumed.delete(n);
256
+ for (const n of this.consumed.keys()) {
257
+ if (this.consumed.size < MAX_CONSUMED_STATES)
258
+ break;
259
+ this.consumed.delete(n);
260
+ }
261
+ }
262
+ if (this.consumed.has(payload.n))
263
+ throw new OAuthStateInvalidError();
264
+ this.consumed.set(payload.n, payload.e);
265
+ }
266
+ /** The id_token (received directly from the token endpoint over TLS) must echo our nonce. */
267
+ checkNonce(idToken, expected) {
268
+ let claims;
269
+ try {
270
+ claims = JSON.parse(Buffer.from(idToken.split('.')[1] ?? '', 'base64url').toString('utf8'));
271
+ }
272
+ catch {
273
+ throw new OAuthExchangeError('malformed id_token');
274
+ }
275
+ if (typeof claims.nonce !== 'string' || !safeEqual(claims.nonce, expected)) {
276
+ throw new OAuthExchangeError('id_token nonce mismatch');
277
+ }
193
278
  }
194
- async exchangeCode(p, code, redirectUri) {
279
+ async exchangeCode(p, code, redirectUri, codeVerifier) {
195
280
  const res = await this.doFetch(p.tokenUrl, {
196
281
  method: 'POST',
197
282
  headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
@@ -201,14 +286,17 @@ export class OAuth {
201
286
  redirect_uri: redirectUri,
202
287
  client_id: p.clientId,
203
288
  client_secret: p.clientSecret,
289
+ code_verifier: codeVerifier,
204
290
  }).toString(),
205
291
  });
206
292
  const text = await res.text();
207
- const json = text ? JSON.parse(text) : {};
293
+ const json = text
294
+ ? JSON.parse(text)
295
+ : {};
208
296
  if (!res.ok || !json.access_token) {
209
297
  throw new OAuthExchangeError(json.error_description ?? json.error ?? `token endpoint HTTP ${res.status}`);
210
298
  }
211
- return json.access_token;
299
+ return { accessToken: json.access_token, ...(typeof json.id_token === 'string' ? { idToken: json.id_token } : {}) };
212
300
  }
213
301
  signState(payload) {
214
302
  const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
package/dist/plugin.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { BasaltError } from '@basaltkit/core';
1
2
  import { Auth, type AuthOptions } from './auth.js';
2
3
  import type { PublicUser } from './stores.js';
3
4
  declare module '@basaltkit/core' {
@@ -49,8 +50,54 @@ declare module '@basaltkit/core' {
49
50
  'auth:mfa_disabled': {
50
51
  user: PublicUser;
51
52
  };
53
+ /** A wrong MFA code was presented for this user (login or social login). */
54
+ 'auth:mfa_failed': {
55
+ userId: string;
56
+ };
57
+ /** A login was refused because the account (or the client ip) is locked. */
58
+ 'auth:locked_out': {
59
+ email: string;
60
+ ip?: string;
61
+ };
62
+ /** A consumed refresh token came back; its whole family was revoked (theft indicator). */
63
+ 'auth:refresh_reused': {
64
+ userId: string;
65
+ familyId: string;
66
+ };
67
+ /**
68
+ * A provider-verified social login took over an account whose email had
69
+ * never been verified; its previous password, sessions, refresh tokens and
70
+ * MFA were revoked.
71
+ */
72
+ 'auth:social_account_adopted': {
73
+ user: PublicUser;
74
+ };
52
75
  }
53
76
  }
54
77
  export declare const AUTH: import("@basaltkit/core").Token<Auth>;
55
- export type AuthPluginOptions = Omit<AuthOptions, 'hooks'>;
56
- export declare function authPlugin(options: AuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
78
+ /** A cookie-authenticated, state-changing request came from another origin. */
79
+ export declare class CsrfRejectedError extends BasaltError {
80
+ readonly status = 403;
81
+ constructor();
82
+ }
83
+ export interface CsrfOptions {
84
+ /**
85
+ * Extra origins (scheme://host[:port]) allowed to send cookie-authenticated
86
+ * unsafe requests — e.g. a front-end on a sibling subdomain. The request's
87
+ * own origin (its Host / X-Forwarded-Host) is always allowed.
88
+ */
89
+ trustedOrigins?: string[];
90
+ }
91
+ export interface AuthPluginOptions extends Omit<AuthOptions, 'hooks'> {
92
+ /**
93
+ * CSRF defence for the session cookie (on by default). A request whose ONLY
94
+ * credential is the ambient session cookie and whose method is not
95
+ * GET/HEAD/OPTIONS is not authenticated when the browser says it is
96
+ * cross-site or same-site (`Sec-Fetch-Site`), or when its `Origin` is neither
97
+ * the request's own host nor a trusted origin; a route requiring auth then
98
+ * answers 403 `AUTH_CSRF_REJECTED`. Bearer tokens, `x-session-id` and API keys
99
+ * are not ambient and are not affected. `false` disables the check.
100
+ */
101
+ csrf?: CsrfOptions | false;
102
+ }
103
+ export declare function authPlugin(pluginOptions: AuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
package/dist/plugin.js CHANGED
@@ -1,8 +1,58 @@
1
- import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
1
+ import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
2
2
  import { Auth, AuthRequiredError } from './auth.js';
3
3
  import { publicUser } from './auth.js';
4
4
  export const AUTH = createToken('auth');
5
- export function authPlugin(options) {
5
+ /** A cookie-authenticated, state-changing request came from another origin. */
6
+ export class CsrfRejectedError extends BasaltError {
7
+ status = 403;
8
+ constructor() {
9
+ super('AUTH_CSRF_REJECTED', 'Cross-site request refused: the session cookie cannot authorize it.');
10
+ }
11
+ }
12
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
13
+ const headerOf = (request, name) => {
14
+ const value = request.headers[name];
15
+ return Array.isArray(value) ? value[0] : value;
16
+ };
17
+ const originOf = (value) => {
18
+ try {
19
+ const url = new URL(value);
20
+ return `${url.protocol}//${url.host}`.toLowerCase();
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ };
26
+ /** Whether a cookie-authenticated request may change state (CSRF check). */
27
+ function sameOriginRequest(request, trusted) {
28
+ if (SAFE_METHODS.has(request.method.toUpperCase()))
29
+ return true;
30
+ const origin = headerOf(request, 'origin');
31
+ const normalized = origin && origin !== 'null' ? originOf(origin) : null;
32
+ if (normalized && trusted.has(normalized))
33
+ return true;
34
+ // Sec-Fetch-Site is set by the browser alone (a page cannot forge it), so it
35
+ // settles the question when present — including behind a proxy that rewrites Host.
36
+ const site = headerOf(request, 'sec-fetch-site')?.toLowerCase();
37
+ if (site === 'same-origin' || site === 'none')
38
+ return true;
39
+ if (site === 'cross-site' || site === 'same-site')
40
+ return false;
41
+ if (origin === undefined)
42
+ return true; // no browser metadata: not a browser-forged request
43
+ if (!normalized)
44
+ return false; // `Origin: null` (sandboxed/opaque) or garbage
45
+ const host = normalized.slice(normalized.indexOf('//') + 2);
46
+ const own = [headerOf(request, 'host'), headerOf(request, 'x-forwarded-host')]
47
+ .filter((h) => typeof h === 'string')
48
+ .map((h) => h.split(',')[0].trim().toLowerCase());
49
+ return own.includes(host);
50
+ }
51
+ /** Requests whose session cookie was ignored by the CSRF check. */
52
+ const csrfRejected = new WeakSet();
53
+ export function authPlugin(pluginOptions) {
54
+ const { csrf, ...options } = pluginOptions;
55
+ const trustedOrigins = new Set((csrf ? (csrf.trustedOrigins ?? []) : []).map((o) => originOf(o)).filter((o) => o !== null));
6
56
  return definePlugin({
7
57
  name: 'basalt:auth',
8
58
  register({ container, hooks }) {
@@ -35,6 +85,11 @@ export function authPlugin(options) {
35
85
  const cookie = request.headers.cookie;
36
86
  if (typeof cookie === 'string') {
37
87
  const cookieSessionId = auth.sessionIdFromCookie(cookie);
88
+ if (cookieSessionId && csrf !== false && !sameOriginRequest(request, trustedOrigins)) {
89
+ // Ambient credential on a cross-origin state change: do not use it.
90
+ csrfRejected.add(context);
91
+ return;
92
+ }
38
93
  if (cookieSessionId) {
39
94
  const user = await auth.sessionUser(cookieSessionId);
40
95
  if (user)
@@ -45,8 +100,9 @@ export function authPlugin(options) {
45
100
  metadata.add('http:enrichers', enricher);
46
101
  // Guard: routes declaring meta.auth require an authenticated user.
47
102
  const guard = ({ route, context }) => {
48
- if (route.meta?.['auth'] === true && !context.user)
49
- throw new AuthRequiredError();
103
+ if (route.meta?.['auth'] === true && !context.user) {
104
+ throw csrfRejected.has(context) ? new CsrfRejectedError() : new AuthRequiredError();
105
+ }
50
106
  };
51
107
  metadata.add('http:guards', guard);
52
108
  // Claim `meta.auth` so the adapters' boot check knows this key is
package/dist/routes.d.ts CHANGED
@@ -17,9 +17,33 @@ 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
+ /** RFC 5321 caps a forward path at 254 characters. */
39
+ export declare const MAX_EMAIL_LENGTH = 254;
40
+ /** Far above any passphrase; bounds the work an unauthenticated body can cause. */
41
+ export declare const MAX_PASSWORD_LENGTH = 1024;
42
+ /** Default `meta.rateLimit` on the public auth routes: 10 requests per minute per ip and route. */
43
+ export declare const DEFAULT_AUTH_RATE_LIMIT: {
44
+ readonly limit: 10;
45
+ readonly windowMs: 60000;
46
+ };
23
47
  /**
24
48
  * Ready-made auth routes — register them in fastifyPlugin({ routes }):
25
49
  * register · login · refresh · logout · me, plus email verification
package/dist/routes.js CHANGED
@@ -3,14 +3,23 @@ import { route } from '@basaltkit/http';
3
3
  import { z } from 'zod';
4
4
  import { AUTH } from './plugin.js';
5
5
  import { API_KEYS } from './apikeys-plugin.js';
6
- const DEFAULT_PASSWORD = z.string().min(8);
6
+ /** RFC 5321 caps a forward path at 254 characters. */
7
+ export const MAX_EMAIL_LENGTH = 254;
8
+ /** Far above any passphrase; bounds the work an unauthenticated body can cause. */
9
+ export const MAX_PASSWORD_LENGTH = 1024;
10
+ /** Default `meta.rateLimit` on the public auth routes: 10 requests per minute per ip and route. */
11
+ export const DEFAULT_AUTH_RATE_LIMIT = { limit: 10, windowMs: 60_000 };
12
+ const email = () => z.string().trim().max(MAX_EMAIL_LENGTH).email();
13
+ const token = () => z.string().max(512);
14
+ const DEFAULT_PASSWORD = z.string().min(8).max(MAX_PASSWORD_LENGTH);
7
15
  const passwordSchema = (policy) => {
8
16
  if (!policy)
9
17
  return DEFAULT_PASSWORD;
10
- if (typeof policy.safeParse === 'function')
11
- return policy;
18
+ if (typeof policy.safeParse === 'function') {
19
+ return z.string().max(MAX_PASSWORD_LENGTH).pipe(policy);
20
+ }
12
21
  const { minLength } = policy;
13
- return minLength === undefined ? DEFAULT_PASSWORD : z.string().min(minLength);
22
+ return minLength === undefined ? DEFAULT_PASSWORD : z.string().min(minLength).max(MAX_PASSWORD_LENGTH);
14
23
  };
15
24
  const auth = () => ctx().container.get(AUTH);
16
25
  const apiKeys = () => ctx().container.get(API_KEYS);
@@ -23,11 +32,13 @@ const apiKeys = () => ctx().container.get(API_KEYS);
23
32
  */
24
33
  export function authRoutes(options = {}) {
25
34
  const password = passwordSchema(options.password);
26
- const credentials = z.object({ email: z.string().email(), password });
35
+ const credentials = z.object({ email: email(), password });
36
+ const limit = options.rateLimit === false ? {} : { rateLimit: options.rateLimit ?? { ...DEFAULT_AUTH_RATE_LIMIT } };
27
37
  return [
28
38
  route({
29
39
  method: 'POST',
30
40
  url: '/auth/register',
41
+ meta: { ...limit },
31
42
  body: credentials,
32
43
  // Enumeration-safe: the same 202 whether the email is new or already taken
33
44
  // (a collision is signalled out-of-band via auth:register_existing_email).
@@ -39,7 +50,8 @@ export function authRoutes(options = {}) {
39
50
  route({
40
51
  method: 'POST',
41
52
  url: '/auth/login',
42
- body: credentials.extend({ mfaCode: z.string().optional() }),
53
+ meta: { ...limit },
54
+ body: credentials.extend({ mfaCode: z.string().max(64).optional() }),
43
55
  async handler({ body, request, reply }) {
44
56
  const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
45
57
  const session = await auth().createSession(user.id);
@@ -52,7 +64,7 @@ export function authRoutes(options = {}) {
52
64
  route({
53
65
  method: 'POST',
54
66
  url: '/auth/refresh',
55
- body: z.object({ refreshToken: z.string() }),
67
+ body: z.object({ refreshToken: token() }),
56
68
  async handler({ body }) {
57
69
  return auth().refresh(body.refreshToken);
58
70
  },
@@ -60,7 +72,7 @@ export function authRoutes(options = {}) {
60
72
  route({
61
73
  method: 'POST',
62
74
  url: '/auth/logout',
63
- body: z.object({ refreshToken: z.string() }),
75
+ body: z.object({ refreshToken: token() }),
64
76
  async handler({ body, request, reply }) {
65
77
  await auth().revoke(body.refreshToken);
66
78
  const sessionId = auth().sessionIdFromCookie(request.headers.cookie);
@@ -84,7 +96,8 @@ export function authRoutes(options = {}) {
84
96
  route({
85
97
  method: 'POST',
86
98
  url: '/auth/verify/request',
87
- body: z.object({ email: z.string().email() }),
99
+ meta: { ...limit },
100
+ body: z.object({ email: email() }),
88
101
  async handler({ body }) {
89
102
  // The app emails the token (via the auth:verify_requested hook). Always
90
103
  // 200, so the response never reveals whether the email has an account.
@@ -95,7 +108,7 @@ export function authRoutes(options = {}) {
95
108
  route({
96
109
  method: 'POST',
97
110
  url: '/auth/verify',
98
- body: z.object({ token: z.string() }),
111
+ body: z.object({ token: token() }),
99
112
  async handler({ body }) {
100
113
  return { user: await auth().verifyEmail(body.token) };
101
114
  },
@@ -104,7 +117,8 @@ export function authRoutes(options = {}) {
104
117
  route({
105
118
  method: 'POST',
106
119
  url: '/auth/password/forgot',
107
- body: z.object({ email: z.string().email() }),
120
+ meta: { ...limit },
121
+ body: z.object({ email: email() }),
108
122
  async handler({ body }) {
109
123
  await auth().requestPasswordReset(body.email);
110
124
  return { ok: true };
@@ -116,7 +130,8 @@ export function authRoutes(options = {}) {
116
130
  // The same policy as register. Covering register and leaving reset behind
117
131
  // would let anyone walk a strong password back down to eight characters
118
132
  // through "forgot password" — a loophole worse than having no option.
119
- body: z.object({ token: z.string(), password }),
133
+ meta: { ...limit },
134
+ body: z.object({ token: token(), password }),
120
135
  async handler({ body }) {
121
136
  await auth().resetPassword(body.token, body.password);
122
137
  return { ok: true };
@@ -150,7 +165,9 @@ export function apiKeyRoutes() {
150
165
  route({
151
166
  method: 'POST',
152
167
  url: '/apikeys',
153
- meta: { auth: true },
168
+ // Session-only: a key must never mint, list or revoke keys (a narrow or
169
+ // expiring key could otherwise mint a permanent '*' key).
170
+ meta: { auth: true, apiKey: false },
154
171
  body: z.object({
155
172
  name: z.string().min(1).max(100),
156
173
  scopes: z.array(z.string().min(1)).optional(),
@@ -165,7 +182,9 @@ export function apiKeyRoutes() {
165
182
  route({
166
183
  method: 'GET',
167
184
  url: '/apikeys',
168
- meta: { auth: true },
185
+ // Session-only: a key must never mint, list or revoke keys (a narrow or
186
+ // expiring key could otherwise mint a permanent '*' key).
187
+ meta: { auth: true, apiKey: false },
169
188
  async handler() {
170
189
  return apiKeys().list(scope());
171
190
  },
@@ -173,7 +192,7 @@ export function apiKeyRoutes() {
173
192
  route({
174
193
  method: 'DELETE',
175
194
  url: '/apikeys/:id',
176
- meta: { auth: true },
195
+ meta: { auth: true, apiKey: false },
177
196
  params: z.object({ id: z.string() }),
178
197
  async handler({ params, reply }) {
179
198
  const record = await apiKeys().get(params.id);
@@ -211,7 +230,7 @@ export function mfaRoutes() {
211
230
  route({
212
231
  method: 'POST',
213
232
  url: '/auth/mfa/enroll',
214
- meta: { auth: true },
233
+ meta: { auth: true, apiKey: false },
215
234
  async handler() {
216
235
  return auth().enrollMfa(currentUserId());
217
236
  },
@@ -219,8 +238,8 @@ export function mfaRoutes() {
219
238
  route({
220
239
  method: 'POST',
221
240
  url: '/auth/mfa/activate',
222
- meta: { auth: true },
223
- body: z.object({ code: z.string().min(6) }),
241
+ meta: { auth: true, apiKey: false },
242
+ body: z.object({ code: z.string().min(6).max(64) }),
224
243
  async handler({ body }) {
225
244
  return auth().activateMfa(currentUserId(), body.code);
226
245
  },
@@ -228,7 +247,7 @@ export function mfaRoutes() {
228
247
  route({
229
248
  method: 'GET',
230
249
  url: '/auth/mfa/status',
231
- meta: { auth: true },
250
+ meta: { auth: true, apiKey: false },
232
251
  async handler() {
233
252
  return auth().mfaStatus(currentUserId());
234
253
  },
@@ -236,8 +255,8 @@ export function mfaRoutes() {
236
255
  route({
237
256
  method: 'POST',
238
257
  url: '/auth/mfa/disable',
239
- meta: { auth: true },
240
- body: z.object({ code: z.string().min(6) }),
258
+ meta: { auth: true, apiKey: false },
259
+ body: z.object({ code: z.string().min(6).max(64) }),
241
260
  async handler({ body, reply }) {
242
261
  await auth().disableMfa(currentUserId(), body.code);
243
262
  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();
@@ -10,6 +10,12 @@ export interface LoginThrottleOptions {
10
10
  maxAttempts?: number;
11
11
  /** Rolling window in ms. Default 15 minutes. */
12
12
  windowMs?: number;
13
+ /**
14
+ * Upper bound on tracked identifiers. When full, expired entries are swept
15
+ * and then the oldest ones are evicted, so failed logins with unique
16
+ * identifiers cannot grow the heap without limit. Default 100 000.
17
+ */
18
+ maxEntries?: number;
13
19
  /** Injectable clock for tests. */
14
20
  clock?: () => number;
15
21
  }
@@ -18,15 +24,38 @@ export interface LoginThrottleOptions {
18
24
  * rolling window and locks the account once the budget is spent. A successful
19
25
  * login clears the counter. In-memory per process; back it with Redis for a
20
26
  * cluster by supplying the same behavior.
27
+ *
28
+ * Identifiers are stored as SHA-256 digests (fixed size, never the raw email),
29
+ * and the table is bounded by {@link LoginThrottleOptions.maxEntries}.
30
+ *
31
+ * Use {@link reserve} before verifying credentials: it counts the attempt
32
+ * synchronously, so a parallel burst cannot run more verifications than the
33
+ * budget allows. {@link release} gives the reservation back on success.
21
34
  */
22
35
  export declare class LoginThrottle {
23
36
  private readonly failures;
24
37
  private readonly maxAttempts;
25
38
  private readonly windowMs;
39
+ private readonly maxEntries;
26
40
  private readonly clock;
27
41
  constructor(options?: LoginThrottleOptions);
42
+ /** Number of identifiers currently tracked. */
43
+ get size(): number;
44
+ /** Total characters retained in keys — diagnostics for memory bounds. */
45
+ retainedKeyChars(): number;
46
+ private digest;
47
+ private live;
48
+ private store;
28
49
  /** Throws {@link AccountLockedError} when the key is currently locked. */
29
50
  assertAllowed(key: string): void;
30
51
  recordFailure(key: string): void;
52
+ /**
53
+ * Atomically checks the budget and counts this attempt (synchronously, before
54
+ * any await), throwing {@link AccountLockedError} when it is spent. Pair with
55
+ * {@link release} on success; a failure simply keeps the reservation.
56
+ */
57
+ reserve(key: string): void;
58
+ /** Returns one reservation (a successful attempt must not consume budget). */
59
+ release(key: string): void;
31
60
  reset(key: string): void;
32
61
  }