@basaltkit/auth 2.1.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/auth.js CHANGED
@@ -76,6 +76,30 @@ export class MfaInvalidCodeError extends BasaltError {
76
76
  super('AUTH_MFA_INVALID', 'The authentication code is incorrect.');
77
77
  }
78
78
  }
79
+ /** MFA is already active: re-enrolling would silently switch it off. Disable it (with a code) first. */
80
+ export class MfaAlreadyEnabledError extends BasaltError {
81
+ status = 409;
82
+ constructor() {
83
+ super('AUTH_MFA_ALREADY_ENABLED', 'MFA is already enabled. Disable it with a valid code before enrolling again.');
84
+ }
85
+ }
86
+ /**
87
+ * A social / SSO login matched an existing account by email, but the provider
88
+ * did not vouch for that email (unverified), so linking would let anyone who
89
+ * can create an IdP account with the address take the account over.
90
+ */
91
+ export class SocialLinkRefusedError extends BasaltError {
92
+ status = 403;
93
+ constructor() {
94
+ super('AUTH_SOCIAL_LINK_REFUSED', 'An account with this email already exists and the identity provider did not verify the email. Sign in with your password instead.');
95
+ }
96
+ }
97
+ /**
98
+ * Canonical form of an email identity: trimmed and lowercased. Every lookup,
99
+ * create and throttle key goes through it, so `Bob@acme.test` and
100
+ * `bob@acme.test` are one account.
101
+ */
102
+ export const canonicalEmail = (email) => email.trim().toLowerCase();
79
103
  /** An MFA action needed an enrollment that doesn't exist. */
80
104
  export class MfaNotEnrolledError extends BasaltError {
81
105
  status = 400;
@@ -101,6 +125,7 @@ export class Auth {
101
125
  hooks;
102
126
  throttle;
103
127
  ipThrottle;
128
+ requestThrottle;
104
129
  tokens;
105
130
  verificationTtl;
106
131
  resetTtl;
@@ -138,6 +163,10 @@ export class Auth {
138
163
  options.ipLoginThrottle === false
139
164
  ? undefined
140
165
  : options.ipLoginThrottle ?? new LoginThrottle({ maxAttempts: 50, windowMs: 15 * 60_000 });
166
+ this.requestThrottle =
167
+ options.emailRequestThrottle === false
168
+ ? undefined
169
+ : options.emailRequestThrottle ?? new LoginThrottle({ maxAttempts: 3, windowMs: 15 * 60_000 });
141
170
  this.tokens = options.tokens ?? new MemoryAuthTokenStore();
142
171
  this.verificationTtl = options.verificationTtl ?? '24h';
143
172
  this.resetTtl = options.resetTtl ?? '1h';
@@ -147,7 +176,8 @@ export class Auth {
147
176
  this.tokenVersions = options.tokenVersions;
148
177
  this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
149
178
  }
150
- async register(email, password) {
179
+ async register(rawEmail, password) {
180
+ const email = canonicalEmail(rawEmail);
151
181
  if (await this.users.findByEmail(email))
152
182
  throw new EmailTakenError();
153
183
  const user = await this.users.create({
@@ -163,8 +193,18 @@ export class Auth {
163
193
  * (a random, unusable password hash), so password login won't work for it
164
194
  * until a password is set. A provider-verified email flips `emailVerified`.
165
195
  * Returns the tokens and whether the account was just created.
196
+ *
197
+ * Linking to an EXISTING account is refused ({@link SocialLinkRefusedError})
198
+ * unless `emailVerified` is `true` — an unverified provider email proves
199
+ * nothing about who owns the address. When the existing account had never
200
+ * verified its email, whoever registered it first is not trusted either: its
201
+ * password, sessions, refresh tokens and MFA are revoked before it is adopted
202
+ * (`auth:social_account_adopted`). An account with MFA enabled requires
203
+ * `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'` is passed
204
+ * explicitly (only for an IdP that enforces its own second factor).
166
205
  */
167
- async socialLogin(email, options = {}) {
206
+ async socialLogin(rawEmail, options = {}) {
207
+ const email = canonicalEmail(rawEmail);
168
208
  let user = await this.users.findByEmail(email);
169
209
  let created = false;
170
210
  if (!user) {
@@ -174,14 +214,51 @@ export class Auth {
174
214
  });
175
215
  created = true;
176
216
  await this.hooks?.emit('auth:registered', { user: publicUser(user) });
217
+ if (options.emailVerified === true && this.users.update) {
218
+ user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
219
+ }
177
220
  }
178
- if (options.emailVerified && !user.emailVerified && this.users.update) {
179
- user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
221
+ else {
222
+ if (options.emailVerified !== true)
223
+ throw new SocialLinkRefusedError();
224
+ if (!user.emailVerified) {
225
+ user = await this.adoptUnverifiedAccount(user);
226
+ }
227
+ else if (options.mfa !== 'skip' && (await this.isMfaEnabled(user.id))) {
228
+ if (!options.mfaCode)
229
+ throw new MfaRequiredError();
230
+ const key = user.email;
231
+ this.throttle?.reserve(key);
232
+ if (!(await this.verifyMfaCode(user.id, options.mfaCode))) {
233
+ await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
234
+ throw new MfaInvalidCodeError();
235
+ }
236
+ this.throttle?.reset(key);
237
+ }
180
238
  }
181
239
  const tokens = await this.issueTokens(user.id);
182
240
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
183
241
  return { user: publicUser(user), tokens, created };
184
242
  }
243
+ /**
244
+ * A provider-verified login is taking over an account whose email was never
245
+ * verified: whoever registered it could be anyone (pre-account hijacking), so
246
+ * every credential they may hold is revoked before the verified owner gets in.
247
+ */
248
+ async adoptUnverifiedAccount(user) {
249
+ if (!this.users.update)
250
+ throw new SocialLinkRefusedError();
251
+ const adopted = (await this.users.update(user.id, {
252
+ passwordHash: await this.hasher.hash(randomBytes(32).toString('hex')),
253
+ emailVerified: true,
254
+ })) ?? user;
255
+ await this.refreshTokens.revokeAllForUser?.(user.id);
256
+ await this.sessions.deleteAllForUser?.(user.id);
257
+ await this.tokenVersions?.increment(user.id);
258
+ await this.mfa.delete(user.id);
259
+ await this.hooks?.emit('auth:social_account_adopted', { user: publicUser(adopted) });
260
+ return adopted;
261
+ }
185
262
  /**
186
263
  * Enumeration-safe registration for the public endpoint: creates the account
187
264
  * for a new email, or — when the email is already taken — does equivalent work
@@ -192,7 +269,8 @@ export class Auth {
192
269
  * With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
193
270
  * duplicate instead (the classic, enumerable behavior).
194
271
  */
195
- async registerSafely(email, password) {
272
+ async registerSafely(rawEmail, password) {
273
+ const email = canonicalEmail(rawEmail);
196
274
  const existing = await this.users.findByEmail(email);
197
275
  if (existing) {
198
276
  if (!this.enumerationSafeRegister)
@@ -211,7 +289,7 @@ export class Auth {
211
289
  }
212
290
  /** Verifies credentials without side effects. Null on failure. */
213
291
  async attempt(email, password) {
214
- const user = await this.users.findByEmail(email);
292
+ const user = await this.users.findByEmail(canonicalEmail(email));
215
293
  if (!user) {
216
294
  // Equalize timing: a missing account must cost the same as a wrong
217
295
  // password, or the response time reveals which emails are registered
@@ -237,31 +315,51 @@ export class Auth {
237
315
  * wrong code throws {@link MfaInvalidCodeError}.
238
316
  */
239
317
  async login(email, password, mfaCode, context = {}) {
240
- const key = email.toLowerCase();
318
+ const key = canonicalEmail(email);
241
319
  const ipKey = context.ip ? `ip:${context.ip}` : undefined;
242
- this.throttle?.assertAllowed(key);
243
- if (ipKey)
244
- this.ipThrottle?.assertAllowed(ipKey);
245
- const recordFailure = () => {
246
- this.throttle?.recordFailure(key);
320
+ // Reserve the attempt BEFORE the (async) verification: the counter moves
321
+ // synchronously, so a parallel burst cannot run more password or MFA
322
+ // guesses than the budget allows. Success gives the reservation back.
323
+ try {
324
+ this.throttle?.reserve(key);
325
+ }
326
+ catch (error) {
327
+ await this.hooks?.emit('auth:locked_out', { email: key });
328
+ throw error;
329
+ }
330
+ if (ipKey && this.ipThrottle) {
331
+ try {
332
+ this.ipThrottle.reserve(ipKey);
333
+ }
334
+ catch (error) {
335
+ this.throttle?.release(key);
336
+ await this.hooks?.emit('auth:locked_out', { email: key, ip: context.ip });
337
+ throw error;
338
+ }
339
+ }
340
+ const release = () => {
341
+ this.throttle?.release(key);
247
342
  if (ipKey)
248
- this.ipThrottle?.recordFailure(ipKey);
343
+ this.ipThrottle?.release(ipKey);
249
344
  };
250
- const user = await this.attempt(email, password);
345
+ const user = await this.attempt(key, password);
251
346
  if (!user) {
252
- recordFailure();
253
- await this.hooks?.emit('auth:login_failed', { email });
347
+ await this.hooks?.emit('auth:login_failed', { email: key });
254
348
  throw new InvalidCredentialsError();
255
349
  }
256
350
  if (await this.isMfaEnabled(user.id)) {
257
- if (!mfaCode)
258
- throw new MfaRequiredError(); // password was correct — not a failure
351
+ if (!mfaCode) {
352
+ release(); // password was correct — not a failure
353
+ throw new MfaRequiredError();
354
+ }
259
355
  if (!(await this.verifyMfaCode(user.id, mfaCode))) {
260
- recordFailure();
356
+ await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
261
357
  throw new MfaInvalidCodeError();
262
358
  }
263
359
  }
264
360
  this.throttle?.reset(key);
361
+ if (ipKey)
362
+ this.ipThrottle?.release(ipKey);
265
363
  const tokens = await this.issueTokens(user.id);
266
364
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
267
365
  return { user: publicUser(user), tokens };
@@ -276,19 +374,36 @@ export class Auth {
276
374
  const record = await this.refreshTokens.find(hashed);
277
375
  if (!record)
278
376
  throw new RefreshInvalidError();
279
- if (record.usedAt !== undefined) {
280
- await this.refreshTokens.revokeFamily(record.familyId);
281
- throw new RefreshReusedError();
282
- }
377
+ if (record.usedAt !== undefined)
378
+ return this.reuseDetected(record.userId, record.familyId);
283
379
  if (Date.now() >= record.expiresAt)
284
380
  throw new RefreshInvalidError();
381
+ // A deleted account must not keep minting tokens from a leftover refresh token.
382
+ if (!(await this.users.findById(record.userId))) {
383
+ await this.refreshTokens.revokeFamily(record.familyId);
384
+ throw new RefreshInvalidError();
385
+ }
285
386
  // Compare-and-swap: `false` means another caller consumed this exact token
286
387
  // between our read and this write — the very race reuse detection exists for.
287
388
  if ((await this.refreshTokens.markUsed(hashed)) === false) {
389
+ return this.reuseDetected(record.userId, record.familyId);
390
+ }
391
+ const pair = await this.issueTokens(record.userId, record.familyId);
392
+ // The consumed token is the witness that the family is still alive:
393
+ // revokeFamily/revokeAllForUser delete every row of it. If a concurrent
394
+ // revocation (a reuse loser, a logout, a logout-everywhere) ran between our
395
+ // CAS and the insert above, the row is gone — revoke again so the token we
396
+ // just stored does not outlive its family, and refuse.
397
+ if (!(await this.refreshTokens.find(hashed))) {
288
398
  await this.refreshTokens.revokeFamily(record.familyId);
289
399
  throw new RefreshReusedError();
290
400
  }
291
- return this.issueTokens(record.userId, record.familyId);
401
+ return pair;
402
+ }
403
+ async reuseDetected(userId, familyId) {
404
+ await this.refreshTokens.revokeFamily(familyId);
405
+ await this.hooks?.emit('auth:refresh_reused', { userId, familyId });
406
+ throw new RefreshReusedError();
292
407
  }
293
408
  /** Revokes a refresh family — logout for token-based clients. */
294
409
  async revoke(refreshToken) {
@@ -317,10 +432,14 @@ export class Auth {
317
432
  }
318
433
  /**
319
434
  * Revokes every access token issued so far for the user (logout-everywhere),
320
- * by bumping the token version. No-op unless a {@link TokenVersionStore} is
321
- * configured. Pair with refresh/session revocation for a full logout.
435
+ * revoking every refresh token and server-side session (when the stores
436
+ * implement `revokeAllForUser` / `deleteAllForUser`, as the bundled ones do)
437
+ * and bumping the token version so outstanding access tokens die too (needs a
438
+ * {@link TokenVersionStore}; without one, access tokens live until their TTL).
322
439
  */
323
440
  async revokeAllTokens(userId) {
441
+ await this.refreshTokens.revokeAllForUser?.(userId);
442
+ await this.sessions.deleteAllForUser?.(userId);
324
443
  await this.tokenVersions?.increment(userId);
325
444
  }
326
445
  async createSession(userId) {
@@ -368,8 +487,8 @@ export class Auth {
368
487
  * whether the email exists.
369
488
  */
370
489
  async requestEmailVerification(email) {
371
- const user = await this.users.findByEmail(email);
372
- if (!user)
490
+ const user = await this.users.findByEmail(canonicalEmail(email));
491
+ if (!user || !this.allowEmailRequest('verify_email', user.id))
373
492
  return null;
374
493
  const token = await this.issueOneTimeToken(user.id, 'verify_email', this.verificationTtl);
375
494
  await this.hooks?.emit('auth:verify_requested', { user: publicUser(user), token });
@@ -382,15 +501,28 @@ export class Auth {
382
501
  await this.hooks?.emit('auth:email_verified', { user: publicUser(user) });
383
502
  return publicUser(user);
384
503
  }
504
+ /** Per-account budget for reset/verification mails; false = drop silently. */
505
+ allowEmailRequest(purpose, userId) {
506
+ if (!this.requestThrottle)
507
+ return true;
508
+ try {
509
+ this.requestThrottle.reserve(`${purpose}:${userId}`);
510
+ return true;
511
+ }
512
+ catch {
513
+ return false;
514
+ }
515
+ }
385
516
  // --- password reset ------------------------------------------------------
386
517
  /**
387
518
  * Starts a password reset: mints a single-use token and emits
388
- * `auth:password_reset_requested`. Returns null when no account matches, so
389
- * the caller always responds 200 (no account enumeration).
519
+ * `auth:password_reset_requested`. Returns null when no account matches (or
520
+ * the per-account request budget is spent — the live link then stays valid),
521
+ * so the caller always responds 200 (no account enumeration).
390
522
  */
391
523
  async requestPasswordReset(email) {
392
- const user = await this.users.findByEmail(email);
393
- if (!user)
524
+ const user = await this.users.findByEmail(canonicalEmail(email));
525
+ if (!user || !this.allowEmailRequest('reset_password', user.id))
394
526
  return null;
395
527
  const token = await this.issueOneTimeToken(user.id, 'reset_password', this.resetTtl);
396
528
  await this.hooks?.emit('auth:password_reset_requested', { user: publicUser(user), token });
@@ -440,6 +572,10 @@ export class Auth {
440
572
  const user = await this.users.findById(userId);
441
573
  if (!user)
442
574
  throw new AuthRequiredError();
575
+ // Overwriting an active record would switch MFA off without a code —
576
+ // exactly what disableMfa() refuses to do.
577
+ if ((await this.mfa.get(userId))?.enabled)
578
+ throw new MfaAlreadyEnabledError();
443
579
  const secret = generateTotpSecret();
444
580
  await this.mfa.set(userId, { secret: this.encryptMfaSecret(secret), enabled: false, recoveryCodes: [] });
445
581
  return {
@@ -494,6 +630,10 @@ export class Auth {
494
630
  // its ~90s window (an intercepted code is single-use).
495
631
  if (record.lastUsedStep !== undefined && step <= record.lastUsedStep)
496
632
  return false;
633
+ // Atomic consume when the store supports it: two parallel requests with
634
+ // the same code must not both pass the read-then-write above.
635
+ if (this.mfa.consumeTotpStep)
636
+ return this.mfa.consumeTotpStep(userId, step);
497
637
  record.lastUsedStep = step;
498
638
  await this.mfa.set(userId, record);
499
639
  return true;
@@ -502,6 +642,8 @@ export class Auth {
502
642
  const index = record.recoveryCodes.indexOf(hash);
503
643
  if (index === -1)
504
644
  return false;
645
+ if (this.mfa.consumeRecoveryCode)
646
+ return this.mfa.consumeRecoveryCode(userId, hash);
505
647
  record.recoveryCodes.splice(index, 1); // consume it
506
648
  await this.mfa.set(userId, record);
507
649
  return true;
package/dist/index.d.ts CHANGED
@@ -7,12 +7,12 @@ declare module '@basaltkit/http' {
7
7
  auth?: boolean;
8
8
  }
9
9
  }
10
- export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
10
+ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
11
11
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
12
- export { authPlugin, AUTH, type AuthPluginOptions } from './plugin.js';
13
- export { ApiKeys, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
14
- export { apiKeysPlugin, API_KEYS, type ApiKeysPluginOptions } from './apikeys-plugin.js';
15
- export { authRoutes, apiKeyRoutes, mfaRoutes, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
12
+ export { authPlugin, AUTH, CsrfRejectedError, type AuthPluginOptions, type CsrfOptions } from './plugin.js';
13
+ export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
14
+ export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
15
+ export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
16
16
  export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
17
17
  export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
18
18
  export { LoginThrottle, AccountLockedError, type LoginThrottleOptions } from './throttle.js';
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  export { ScryptPasswordHasher } from './hashing.js';
2
2
  export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, } from './jwt.js';
3
3
  export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, } from './stores.js';
4
- export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, } from './auth.js';
4
+ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, } from './auth.js';
5
5
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
6
- export { authPlugin, AUTH } from './plugin.js';
7
- export { ApiKeys, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
8
- export { apiKeysPlugin, API_KEYS } from './apikeys-plugin.js';
9
- export { authRoutes, apiKeyRoutes, mfaRoutes, } from './routes.js';
6
+ export { authPlugin, AUTH, CsrfRejectedError } from './plugin.js';
7
+ export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
8
+ export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, } from './apikeys-plugin.js';
9
+ export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, } from './routes.js';
10
10
  export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
11
11
  export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.js';
12
12
  export { LoginThrottle, AccountLockedError } from './throttle.js';
@@ -23,6 +23,15 @@ export interface OAuthRoutesOptions {
23
23
  * When omitted, the callback responds with JSON `{ user, accessToken, refreshToken }`.
24
24
  */
25
25
  successRedirect?: string;
26
+ /**
27
+ * The HttpOnly cookie that binds a login to the browser that started it.
28
+ * `secure` defaults to production-only; when secure, the cookie is named
29
+ * `__Host-basalt_oauth` (host-only, so a sibling subdomain cannot plant it).
30
+ */
31
+ bindingCookie?: {
32
+ secure?: boolean;
33
+ maxAgeSeconds?: number;
34
+ };
26
35
  }
27
36
  /**
28
37
  * Ready-made OAuth routes:
@@ -18,6 +18,22 @@ export function oauthPlugin(options) {
18
18
  },
19
19
  });
20
20
  }
21
+ const readCookie = (header, name) => {
22
+ if (typeof header !== 'string')
23
+ return undefined;
24
+ for (const part of header.split(';')) {
25
+ const [key, ...rest] = part.trim().split('=');
26
+ if (key === name && rest.length > 0) {
27
+ try {
28
+ return decodeURIComponent(rest.join('='));
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ }
35
+ return undefined;
36
+ };
21
37
  /**
22
38
  * Ready-made OAuth routes:
23
39
  * - `GET /auth/oauth/:provider` → 302 to the provider's authorize URL.
@@ -27,26 +43,34 @@ export function oauthRoutes(options) {
27
43
  const oauth = () => ctx().container.get(OAUTH);
28
44
  const base = stripTrailingSlashes(options.callbackBaseUrl);
29
45
  const redirectUri = (provider) => `${base}/auth/oauth/${provider}/callback`;
46
+ const secure = options.bindingCookie?.secure ?? process.env['NODE_ENV'] === 'production';
47
+ const cookieName = secure ? '__Host-basalt_oauth' : 'basalt_oauth';
48
+ const maxAge = options.bindingCookie?.maxAgeSeconds ?? 15 * 60;
49
+ // SameSite=Lax: the provider redirects back with a top-level GET, which Lax allows.
50
+ const cookie = (value, age) => `${cookieName}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${age}${secure ? '; Secure' : ''}`;
30
51
  return [
31
52
  route({
32
53
  method: 'GET',
33
54
  url: '/auth/oauth/:provider',
34
55
  params: z.object({ provider: z.string() }),
35
56
  async handler({ params, reply }) {
36
- const url = oauth().authorizeUrl(params.provider, redirectUri(params.provider));
37
- return reply.code(302).header('location', url).send();
57
+ const { url, binding } = oauth().authorize(params.provider, redirectUri(params.provider));
58
+ return reply.code(302).header('set-cookie', cookie(binding, maxAge)).header('location', url).send();
38
59
  },
39
60
  }),
40
61
  route({
41
62
  method: 'GET',
42
63
  url: '/auth/oauth/:provider/callback',
43
64
  params: z.object({ provider: z.string() }),
44
- query: z.object({ code: z.string(), state: z.string() }),
45
- async handler({ params, query, reply }) {
65
+ query: z.object({ code: z.string().max(4096), state: z.string().max(4096) }),
66
+ async handler({ params, query, request, reply }) {
67
+ // Single-use: the binding cookie is cleared whatever the outcome.
68
+ reply.header('set-cookie', cookie('', 0));
46
69
  const { user, tokens } = await oauth().callback(params.provider, {
47
70
  code: query.code,
48
71
  state: query.state,
49
72
  redirectUri: redirectUri(params.provider),
73
+ binding: readCookie(request.headers.cookie, cookieName),
50
74
  });
51
75
  if (options.successRedirect) {
52
76
  const url = new URL(options.successRedirect);
package/dist/oauth.d.ts CHANGED
@@ -79,12 +79,25 @@ export interface OAuthOptions {
79
79
  now?: () => number;
80
80
  /** How long a signed `state` stays valid, in ms. Default: 10 minutes. */
81
81
  stateTtlMs?: number;
82
+ /**
83
+ * MFA for an existing account that has it enabled. `'required'` (default)
84
+ * refuses the social login with `AUTH_MFA_REQUIRED` — the callback cannot
85
+ * collect a code. `'skip'` trusts the provider's own second factor; choose it
86
+ * only for an IdP that enforces MFA.
87
+ */
88
+ mfa?: 'required' | 'skip';
82
89
  }
83
90
  /**
84
91
  * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
85
92
  * build an authorize URL with a signed, expiring `state`, then exchange the code
86
93
  * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
87
- * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
94
+ *
95
+ * The flow is bound to the browser that started it: {@link authorize} returns a
96
+ * random `binding` the caller stores in an HttpOnly cookie ({@link oauthRoutes}
97
+ * does). The signed `state` carries its hash, the PKCE verifier (S256) and the
98
+ * OIDC nonce are derived from it, and the callback requires it back — so an
99
+ * attacker's callback URL opened in a victim's browser (login CSRF) or an
100
+ * injected authorization code is refused. Each `state` is single-use.
88
101
  */
89
102
  export declare class OAuth {
90
103
  private readonly auth;
@@ -96,18 +109,42 @@ export declare class OAuth {
96
109
  constructor(auth: Auth, providers: OAuthProvider[], options: OAuthOptions);
97
110
  names(): string[];
98
111
  private provider;
99
- /** The provider's authorization URL to redirect the browser to. */
100
- authorizeUrl(name: string, redirectUri: string): string;
101
- /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
112
+ /**
113
+ * Starts a login: returns the provider's authorization URL to redirect the
114
+ * browser to, and the `binding` to keep in an HttpOnly cookie until the
115
+ * callback (pass it back to {@link callback}).
116
+ */
117
+ authorize(name: string, redirectUri: string): {
118
+ url: string;
119
+ binding: string;
120
+ };
121
+ /**
122
+ * The provider's authorization URL for a caller-managed `binding` (at least
123
+ * 32 characters of randomness, stored where only the initiating browser can
124
+ * present it). Prefer {@link authorize}, which generates one.
125
+ */
126
+ authorizeUrl(name: string, redirectUri: string, binding: string): string;
127
+ /**
128
+ * Verifies `state` against the browser `binding`, consumes it (single-use),
129
+ * exchanges the code with the PKCE verifier, fetches the profile, and logs in.
130
+ */
102
131
  callback(name: string, input: {
103
132
  code: string;
104
133
  state: string | undefined;
105
134
  redirectUri: string;
135
+ binding: string | undefined;
106
136
  }): Promise<{
107
137
  user: PublicUser;
108
138
  tokens: TokenPair;
109
139
  created: boolean;
110
140
  }>;
141
+ /** A per-flow secret derived from the binding (PKCE verifier, OIDC nonce): 43 url-safe chars. */
142
+ private derive;
143
+ /** Single-use: a state nonce is remembered until it expires. */
144
+ private readonly consumed;
145
+ private consumeState;
146
+ /** The id_token (received directly from the token endpoint over TLS) must echo our nonce. */
147
+ private checkNonce;
111
148
  private exchangeCode;
112
149
  private signState;
113
150
  private verifyState;