@basaltkit/auth 3.0.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/README.md CHANGED
@@ -197,6 +197,18 @@ Flow (all routes require login):
197
197
  3. From then on, `POST /auth/login` requires the extra `mfaCode` field (TOTP code or a recovery code). Correct password without a code → `AUTH_MFA_REQUIRED` error.
198
198
  4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
199
199
 
200
+ **Requiring MFA.** `authPlugin({ requireMfa: true })` — or a policy
201
+ `requireMfa: (user, context) => boolean | Promise<boolean>` — refuses every
202
+ authenticated request whose credential was not obtained with a second factor:
203
+ `403 AUTH_MFA_ENROLLMENT_REQUIRED` (no MFA yet: enrol, then sign in again) or
204
+ `403 AUTH_MFA_REQUIRED` (sign in again with a code). Routes with
205
+ `meta.mfa: false` are exempt — all of `authRoutes()` and MFA
206
+ enroll/activate/status. `meta: { mfa: true }` requires MFA on one route
207
+ (step-up) even without the policy. Tokens carry an `amr` claim (`['pwd']`,
208
+ `['pwd', 'mfa']`, `['fed', …]` for social login), refreshes keep it, the
209
+ session cookie carries it HMAC-signed, and the request exposes it as
210
+ `ctx().amr`. API-key requests are not subject to the policy. Off by default.
211
+
200
212
  ### Passkeys — WebAuthn (`webauthnPlugin`)
201
213
 
202
214
  Passkeys let users sign in with Face ID / Touch ID / a security key — no password.
@@ -412,6 +424,12 @@ authPlugin({
412
424
  })
413
425
  ```
414
426
 
427
+ Counters live in memory per process by default. For several replicas, share
428
+ them: `authPlugin({ throttleStore: new RedisThrottleStore(redis) })` backs the
429
+ login/MFA, per-IP and email-request throttles with one atomic Redis script per
430
+ attempt. `redis` is any ioredis-compatible client — only `eval` and `del` are
431
+ used, no Redis dependency. Implement `ThrottleStore` for another backend.
432
+
415
433
  ### Hooks (events)
416
434
 
417
435
  The application can react to authentication events: `auth:registered`, `auth:login`, `auth:login_failed`, `auth:logout`, `auth:verify_requested`, `auth:email_verified`, `auth:password_reset_requested`, `auth:password_reset`, `auth:mfa_enabled`, `auth:mfa_disabled`, `auth:apikey_issued`, `auth:apikey_revoked`.
@@ -434,6 +452,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
434
452
  | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
435
453
  | `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults to production only. |
436
454
  | `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
455
+ | `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
456
+ | `requireMfa` | `boolean \| (user, context) => boolean \| Promise<boolean>` | No | off | Plugin only. Require a sign-in with MFA on every authenticated route except `meta.mfa: false` ones. |
437
457
  | `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. `markUsed` must be a **compare-and-swap** — see below. |
438
458
  | `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
439
459
  | `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
@@ -446,12 +466,12 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
446
466
  | Method | Description |
447
467
  |---|---|
448
468
  | `register(email, password)` | Creates the account; throws `EmailTakenError` if the email already exists. |
449
- | `login(email, password, mfaCode?)` | Returns `{ user, tokens }`; applies throttle and MFA. |
469
+ | `login(email, password, mfaCode?)` | Returns `{ user, tokens, amr }`; applies throttle and MFA. |
450
470
  | `attempt(email, password)` | Checks credentials without side effects; `null` on failure. |
451
471
  | `refresh(refreshToken)` | New token pair; detects reuse and revokes the family. |
452
472
  | `revoke(refreshToken)` | Logout for token-based clients. |
453
473
  | `verifyAccess(accessToken)` | Validates the JWT and returns the claims. |
454
- | `createSession(userId)` / `sessionUser(sessionId)` / `logout(sessionId)` | Cookie/header-based sessions. |
474
+ | `createSession(userId, { amr? })` / `sessionUser(sessionId)` / `sessionAuth(sessionId)` / `logout(sessionId)` | Cookie/header-based sessions; `amr` is carried HMAC-signed in the session id, `sessionAuth` returns `{ user, amr? }`. |
455
475
  | `requestEmailVerification(email)` / `verifyEmail(token)` | Email verification. |
456
476
  | `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
457
477
  | `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
@@ -460,7 +480,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
460
480
 
461
481
  ### Ready-made routes
462
482
 
463
- - `authRoutes()`: `POST /auth/register`, `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/verify/request`, `POST /auth/verify`, `POST /auth/password/forgot`, `POST /auth/password/reset`. These are regular routes — you can omit or replace any of them.
483
+ - `authRoutes()`: `POST /auth/register`, `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/verify/request`, `POST /auth/verify`, `POST /auth/password/forgot`, `POST /auth/password/reset`. These are regular routes — you can omit or replace any of them. `POST /auth/logout` takes an optional `{ refreshToken }`: with none (or no body) it ends the cookie / `x-session-id` session and expires the cookie — a cross-site cookie-only logout is refused (`403 AUTH_CSRF_REJECTED`).
484
+ - Every `authRoutes()`, `mfaRoutes()` and `oauthRoutes()` route declares `meta.account: true` (about the caller, not a tenant's data — `@basaltkit/teams`' membership guard lets non-members through) and, except MFA disable, `meta.mfa: false` (reachable under `requireMfa`). `ACCOUNT_META` exports the pair for your own profile routes.
464
485
  - `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (login session only — API keys are refused; scoped to the current tenant/user). `POST /apikeys` accepts an optional `expiresAt` Unix timestamp in milliseconds; expired keys are rejected and omitted from listings.
465
486
  - `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
466
487
  - `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
@@ -484,7 +505,8 @@ Options (`ApiKeysPluginOptions`):
484
505
  |---|---|
485
506
  | `signJwt(claims, { secret, expiresIn? })` / `verifyJwt(token, secret)` | Dependency-free HS256 JWT. Advanced. |
486
507
  | `ScryptPasswordHasher` / `PasswordHasher` | Password hashing (scrypt, memory-hard). Advanced. |
487
- | `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `clock`) | Anti brute-force. |
508
+ | `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `store`, `namespace`, `clock`) | Anti brute-force. |
509
+ | `ThrottleStore` / `MemoryThrottleStore` / `RedisThrottleStore` (`RedisThrottleClient`: `eval` + `del`) | Where throttle counters live; Redis shares them across replicas. |
488
510
  | `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
489
511
  | `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
490
512
  | `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
@@ -512,6 +534,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
512
534
  | `AuthTokenInvalidError` (verification/reset links) | `AUTH_TOKEN_INVALID` | 400 |
513
535
  | `UserUpdateUnsupportedError` | `AUTH_UPDATE_UNSUPPORTED` | 500 |
514
536
  | `MfaRequiredError` / `MfaInvalidCodeError` / `MfaNotEnrolledError` | `AUTH_MFA_*` | 401/401/400 |
537
+ | `MfaStepUpRequiredError` / `MfaEnrollmentRequiredError` | `AUTH_MFA_REQUIRED` / `AUTH_MFA_ENROLLMENT_REQUIRED` | 403/403 |
515
538
  | `AccountLockedError` | `AUTH_LOCKED` | 429 |
516
539
  | `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
517
540
  | `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BasaltError, type DurationInput, type HookBus } from '@basaltkit/core';
2
2
  import { type PasswordHasher } from './hashing.js';
3
- import { LoginThrottle } from './throttle.js';
3
+ import { LoginThrottle, type ThrottleStore } from './throttle.js';
4
4
  import { type JwtClaims } from './jwt.js';
5
5
  import { type AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
6
6
  export declare class InvalidCredentialsError extends BasaltError {
@@ -48,6 +48,24 @@ export declare class MfaRequiredError extends BasaltError {
48
48
  readonly status = 401;
49
49
  constructor();
50
50
  }
51
+ /**
52
+ * The route needs a credential obtained with a second factor (MFA policy or
53
+ * `meta.mfa: true`), and the account has MFA enabled: sign in again with a
54
+ * code. Distinct from the 401 {@link MfaRequiredError} of the login itself.
55
+ */
56
+ export declare class MfaStepUpRequiredError extends BasaltError {
57
+ readonly status = 403;
58
+ constructor();
59
+ }
60
+ /**
61
+ * The route needs a credential obtained with a second factor, and the account
62
+ * has not enabled MFA yet: enrol (`/auth/mfa/enroll` + `/activate`), then sign
63
+ * in again with a code.
64
+ */
65
+ export declare class MfaEnrollmentRequiredError extends BasaltError {
66
+ readonly status = 403;
67
+ constructor();
68
+ }
51
69
  /** The supplied MFA (or recovery) code was wrong. */
52
70
  export declare class MfaInvalidCodeError extends BasaltError {
53
71
  readonly status = 401;
@@ -82,6 +100,8 @@ export interface TokenPair {
82
100
  accessToken: string;
83
101
  refreshToken: string;
84
102
  }
103
+ /** Whether a value is a well-formed `amr` list (non-empty, short lowercase words). */
104
+ export declare const isAmr: (value: unknown) => value is string[];
85
105
  export interface SessionCookieOptions {
86
106
  /** Cookie name. Default: `basalt_session`. */
87
107
  name?: string;
@@ -122,6 +142,15 @@ export interface AuthOptions {
122
142
  * and purpose; pass `false` to disable.
123
143
  */
124
144
  emailRequestThrottle?: LoginThrottle | false;
145
+ /**
146
+ * Where the DEFAULT throttles above (login, per-ip login, email requests)
147
+ * keep their counters. Default: in memory, per process — each replica then
148
+ * grants its own budget. Pass a shared store (e.g. `RedisThrottleStore`) so a
149
+ * cluster enforces one budget; each throttle uses its own namespace
150
+ * (`login`, `login-ip`, `email-request`). Ignored for a throttle passed
151
+ * explicitly (give that one its own `store`).
152
+ */
153
+ throttleStore?: ThrottleStore;
125
154
  /**
126
155
  * Make the public registration endpoint enumeration-safe: a request for an
127
156
  * email that already exists returns the same response (and does equivalent
@@ -204,6 +233,7 @@ export declare class Auth {
204
233
  user: PublicUser;
205
234
  tokens: TokenPair;
206
235
  created: boolean;
236
+ amr: string[];
207
237
  }>;
208
238
  /**
209
239
  * A provider-verified login is taking over an account whose email was never
@@ -236,12 +266,18 @@ export declare class Auth {
236
266
  * required: a correct password with a missing code throws
237
267
  * {@link MfaRequiredError} (without counting as a failed attempt), and a
238
268
  * wrong code throws {@link MfaInvalidCodeError}.
269
+ *
270
+ * `amr` lists the authentication methods used — `['pwd']`, or
271
+ * `['pwd', 'mfa']` when a second factor was verified. It is also embedded in
272
+ * the access token (`amr` claim) and carried by every refresh of this login;
273
+ * pass it to {@link createSession} so a cookie session carries it too.
239
274
  */
240
275
  login(email: string, password: string, mfaCode?: string, context?: {
241
276
  ip?: string;
242
277
  }): Promise<{
243
278
  user: PublicUser;
244
279
  tokens: TokenPair;
280
+ amr: string[];
245
281
  }>;
246
282
  /**
247
283
  * Refresh rotation with reuse detection: every refresh consumes the token
@@ -269,11 +305,31 @@ export declare class Auth {
269
305
  * {@link TokenVersionStore}; without one, access tokens live until their TTL).
270
306
  */
271
307
  revokeAllTokens(userId: string): Promise<void>;
272
- createSession(userId: string): Promise<SessionRecord>;
308
+ /**
309
+ * Creates a server-side session. With `amr` (from {@link login}), the
310
+ * returned id — the value to put in the cookie — also carries those
311
+ * authentication methods, HMAC-signed with the auth secret so a client cannot
312
+ * add `mfa` to a password-only session. Stores are unaffected: they only
313
+ * ever see the random part.
314
+ */
315
+ createSession(userId: string, options?: {
316
+ amr?: readonly string[];
317
+ }): Promise<SessionRecord>;
318
+ private sessionTagSignature;
319
+ /** Splits a session id minted by {@link createSession} into the store id and its signed `amr`. */
320
+ private parseSessionId;
273
321
  sessionCookieHeader(sessionId: string): string;
274
322
  sessionIdFromCookie(cookieHeader?: string): string | null;
275
323
  expiredSessionCookieHeader(): string;
276
324
  sessionUser(sessionId: string): Promise<AuthUser | null>;
325
+ /**
326
+ * The user of a session plus the authentication methods it was created with
327
+ * (`amr` is absent for sessions created without them, e.g. before this option).
328
+ */
329
+ sessionAuth(sessionId: string): Promise<{
330
+ user: AuthUser;
331
+ amr?: string[];
332
+ } | null>;
277
333
  logout(sessionId: string): Promise<void>;
278
334
  /**
279
335
  * Starts email verification: mints a single-use token and emits
package/dist/auth.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash, randomBytes, randomUUID } from 'node:crypto';
1
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
2
  import { BasaltError, parseDuration } from '@basaltkit/core';
3
3
  import { ScryptPasswordHasher } from './hashing.js';
4
4
  import { LoginThrottle } from './throttle.js';
@@ -69,6 +69,28 @@ export class MfaRequiredError extends BasaltError {
69
69
  super('AUTH_MFA_REQUIRED', 'A multi-factor authentication code is required.');
70
70
  }
71
71
  }
72
+ /**
73
+ * The route needs a credential obtained with a second factor (MFA policy or
74
+ * `meta.mfa: true`), and the account has MFA enabled: sign in again with a
75
+ * code. Distinct from the 401 {@link MfaRequiredError} of the login itself.
76
+ */
77
+ export class MfaStepUpRequiredError extends BasaltError {
78
+ status = 403;
79
+ constructor() {
80
+ super('AUTH_MFA_REQUIRED', 'This action requires a sign-in with multi-factor authentication. Sign in again with your code.');
81
+ }
82
+ }
83
+ /**
84
+ * The route needs a credential obtained with a second factor, and the account
85
+ * has not enabled MFA yet: enrol (`/auth/mfa/enroll` + `/activate`), then sign
86
+ * in again with a code.
87
+ */
88
+ export class MfaEnrollmentRequiredError extends BasaltError {
89
+ status = 403;
90
+ constructor() {
91
+ super('AUTH_MFA_ENROLLMENT_REQUIRED', 'Multi-factor authentication is required for this account. Enable it, then sign in again.');
92
+ }
93
+ }
72
94
  /** The supplied MFA (or recovery) code was wrong. */
73
95
  export class MfaInvalidCodeError extends BasaltError {
74
96
  status = 401;
@@ -107,6 +129,13 @@ export class MfaNotEnrolledError extends BasaltError {
107
129
  super('AUTH_MFA_NOT_ENROLLED', 'No MFA enrollment is in progress for this account.');
108
130
  }
109
131
  }
132
+ /** Authentication methods (`amr`) values Basalt issues. */
133
+ const AMR_VALUE = /^[a-z]{1,16}$/;
134
+ /** Whether a value is a well-formed `amr` list (non-empty, short lowercase words). */
135
+ export const isAmr = (value) => Array.isArray(value) &&
136
+ value.length > 0 &&
137
+ value.length <= 8 &&
138
+ value.every((v) => typeof v === 'string' && AMR_VALUE.test(v));
110
139
  export const publicUser = (user) => ({
111
140
  id: user.id,
112
141
  email: user.email,
@@ -158,15 +187,21 @@ export class Auth {
158
187
  secure: options.sessionCookie?.secure ?? process.env['NODE_ENV'] === 'production',
159
188
  };
160
189
  this.hooks = options.hooks;
161
- this.throttle = options.loginThrottle === false ? undefined : options.loginThrottle ?? new LoginThrottle();
190
+ const shared = options.throttleStore ? { store: options.throttleStore } : {};
191
+ this.throttle =
192
+ options.loginThrottle === false
193
+ ? undefined
194
+ : options.loginThrottle ?? new LoginThrottle({ ...shared, namespace: 'login' });
162
195
  this.ipThrottle =
163
196
  options.ipLoginThrottle === false
164
197
  ? undefined
165
- : options.ipLoginThrottle ?? new LoginThrottle({ maxAttempts: 50, windowMs: 15 * 60_000 });
198
+ : options.ipLoginThrottle ??
199
+ new LoginThrottle({ ...shared, namespace: 'login-ip', maxAttempts: 50, windowMs: 15 * 60_000 });
166
200
  this.requestThrottle =
167
201
  options.emailRequestThrottle === false
168
202
  ? undefined
169
- : options.emailRequestThrottle ?? new LoginThrottle({ maxAttempts: 3, windowMs: 15 * 60_000 });
203
+ : options.emailRequestThrottle ??
204
+ new LoginThrottle({ ...shared, namespace: 'email-request', maxAttempts: 3, windowMs: 15 * 60_000 });
170
205
  this.tokens = options.tokens ?? new MemoryAuthTokenStore();
171
206
  this.verificationTtl = options.verificationTtl ?? '24h';
172
207
  this.resetTtl = options.resetTtl ?? '1h';
@@ -207,6 +242,7 @@ export class Auth {
207
242
  const email = canonicalEmail(rawEmail);
208
243
  let user = await this.users.findByEmail(email);
209
244
  let created = false;
245
+ const amr = ['fed'];
210
246
  if (!user) {
211
247
  user = await this.users.create({
212
248
  email,
@@ -228,17 +264,18 @@ export class Auth {
228
264
  if (!options.mfaCode)
229
265
  throw new MfaRequiredError();
230
266
  const key = user.email;
231
- this.throttle?.reserve(key);
267
+ await this.throttle?.reserve(key);
232
268
  if (!(await this.verifyMfaCode(user.id, options.mfaCode))) {
233
269
  await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
234
270
  throw new MfaInvalidCodeError();
235
271
  }
236
- this.throttle?.reset(key);
272
+ await this.throttle?.reset(key);
273
+ amr.push('mfa');
237
274
  }
238
275
  }
239
- const tokens = await this.issueTokens(user.id);
276
+ const tokens = await this.issueTokens(user.id, undefined, amr);
240
277
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
241
- return { user: publicUser(user), tokens, created };
278
+ return { user: publicUser(user), tokens, created, amr };
242
279
  }
243
280
  /**
244
281
  * A provider-verified login is taking over an account whose email was never
@@ -313,6 +350,11 @@ export class Auth {
313
350
  * required: a correct password with a missing code throws
314
351
  * {@link MfaRequiredError} (without counting as a failed attempt), and a
315
352
  * wrong code throws {@link MfaInvalidCodeError}.
353
+ *
354
+ * `amr` lists the authentication methods used — `['pwd']`, or
355
+ * `['pwd', 'mfa']` when a second factor was verified. It is also embedded in
356
+ * the access token (`amr` claim) and carried by every refresh of this login;
357
+ * pass it to {@link createSession} so a cookie session carries it too.
316
358
  */
317
359
  async login(email, password, mfaCode, context = {}) {
318
360
  const key = canonicalEmail(email);
@@ -321,7 +363,7 @@ export class Auth {
321
363
  // synchronously, so a parallel burst cannot run more password or MFA
322
364
  // guesses than the budget allows. Success gives the reservation back.
323
365
  try {
324
- this.throttle?.reserve(key);
366
+ await this.throttle?.reserve(key);
325
367
  }
326
368
  catch (error) {
327
369
  await this.hooks?.emit('auth:locked_out', { email: key });
@@ -329,40 +371,42 @@ export class Auth {
329
371
  }
330
372
  if (ipKey && this.ipThrottle) {
331
373
  try {
332
- this.ipThrottle.reserve(ipKey);
374
+ await this.ipThrottle.reserve(ipKey);
333
375
  }
334
376
  catch (error) {
335
- this.throttle?.release(key);
377
+ await this.throttle?.release(key);
336
378
  await this.hooks?.emit('auth:locked_out', { email: key, ip: context.ip });
337
379
  throw error;
338
380
  }
339
381
  }
340
- const release = () => {
341
- this.throttle?.release(key);
382
+ const release = async () => {
383
+ await this.throttle?.release(key);
342
384
  if (ipKey)
343
- this.ipThrottle?.release(ipKey);
385
+ await this.ipThrottle?.release(ipKey);
344
386
  };
345
387
  const user = await this.attempt(key, password);
346
388
  if (!user) {
347
389
  await this.hooks?.emit('auth:login_failed', { email: key });
348
390
  throw new InvalidCredentialsError();
349
391
  }
392
+ const amr = ['pwd'];
350
393
  if (await this.isMfaEnabled(user.id)) {
351
394
  if (!mfaCode) {
352
- release(); // password was correct — not a failure
395
+ await release(); // password was correct — not a failure
353
396
  throw new MfaRequiredError();
354
397
  }
355
398
  if (!(await this.verifyMfaCode(user.id, mfaCode))) {
356
399
  await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
357
400
  throw new MfaInvalidCodeError();
358
401
  }
402
+ amr.push('mfa');
359
403
  }
360
- this.throttle?.reset(key);
404
+ await this.throttle?.reset(key);
361
405
  if (ipKey)
362
- this.ipThrottle?.release(ipKey);
363
- const tokens = await this.issueTokens(user.id);
406
+ await this.ipThrottle?.release(ipKey);
407
+ const tokens = await this.issueTokens(user.id, undefined, amr);
364
408
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
365
- return { user: publicUser(user), tokens };
409
+ return { user: publicUser(user), tokens, amr };
366
410
  }
367
411
  /**
368
412
  * Refresh rotation with reuse detection: every refresh consumes the token
@@ -388,7 +432,7 @@ export class Auth {
388
432
  if ((await this.refreshTokens.markUsed(hashed)) === false) {
389
433
  return this.reuseDetected(record.userId, record.familyId);
390
434
  }
391
- const pair = await this.issueTokens(record.userId, record.familyId);
435
+ const pair = await this.issueTokens(record.userId, record.familyId, amrOfFamily(record.familyId));
392
436
  // The consumed token is the witness that the family is still alive:
393
437
  // revokeFamily/revokeAllForUser delete every row of it. If a concurrent
394
438
  // revocation (a reuse loser, a logout, a logout-everywhere) ran between our
@@ -442,8 +486,39 @@ export class Auth {
442
486
  await this.sessions.deleteAllForUser?.(userId);
443
487
  await this.tokenVersions?.increment(userId);
444
488
  }
445
- async createSession(userId) {
446
- return this.sessions.create(userId, parseDuration(this.sessionTtl));
489
+ /**
490
+ * Creates a server-side session. With `amr` (from {@link login}), the
491
+ * returned id — the value to put in the cookie — also carries those
492
+ * authentication methods, HMAC-signed with the auth secret so a client cannot
493
+ * add `mfa` to a password-only session. Stores are unaffected: they only
494
+ * ever see the random part.
495
+ */
496
+ async createSession(userId, options = {}) {
497
+ const record = await this.sessions.create(userId, parseDuration(this.sessionTtl));
498
+ const amr = options.amr ? [...options.amr] : undefined;
499
+ if (!amr || !isAmr(amr))
500
+ return record;
501
+ const tag = amr.join('+');
502
+ return { ...record, id: `${record.id}.${tag}.${this.sessionTagSignature(record.id, tag)}` };
503
+ }
504
+ sessionTagSignature(rawId, tag) {
505
+ return createHmac('sha256', this.secret).update(`basalt-session-amr\u0000${rawId}.${tag}`).digest('base64url');
506
+ }
507
+ /** Splits a session id minted by {@link createSession} into the store id and its signed `amr`. */
508
+ parseSessionId(sessionId) {
509
+ const parts = sessionId.split('.');
510
+ if (parts.length !== 3)
511
+ return { rawId: sessionId };
512
+ const [rawId, tag, signature] = parts;
513
+ const expected = Buffer.from(this.sessionTagSignature(rawId, tag));
514
+ const received = Buffer.from(signature);
515
+ const amr = tag.split('+');
516
+ if (expected.length !== received.length || !timingSafeEqual(expected, received) || !isAmr(amr)) {
517
+ // Not a signed composite: treat the whole value as an opaque store id
518
+ // (a tampered composite then simply matches no session).
519
+ return { rawId: sessionId };
520
+ }
521
+ return { rawId, amr };
447
522
  }
448
523
  sessionCookieHeader(sessionId) {
449
524
  const ttlMs = parseDuration(this.sessionTtl);
@@ -467,12 +542,24 @@ export class Auth {
467
542
  return `${cookie.name}=; Path=${cookie.path};${cookie.httpOnly ? ' HttpOnly;' : ''} SameSite=${cookie.sameSite}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT${cookie.secure ? '; Secure' : ''}`;
468
543
  }
469
544
  async sessionUser(sessionId) {
470
- const session = await this.sessions.find(sessionId);
471
- return session ? this.users.findById(session.userId) : null;
545
+ return (await this.sessionAuth(sessionId))?.user ?? null;
546
+ }
547
+ /**
548
+ * The user of a session plus the authentication methods it was created with
549
+ * (`amr` is absent for sessions created without them, e.g. before this option).
550
+ */
551
+ async sessionAuth(sessionId) {
552
+ const { rawId, amr } = this.parseSessionId(sessionId);
553
+ const session = await this.sessions.find(rawId);
554
+ const user = session ? await this.users.findById(session.userId) : null;
555
+ if (!user)
556
+ return null;
557
+ return amr ? { user, amr } : { user };
472
558
  }
473
559
  async logout(sessionId) {
474
- const session = await this.sessions.find(sessionId);
475
- await this.sessions.delete(sessionId);
560
+ const { rawId } = this.parseSessionId(sessionId);
561
+ const session = await this.sessions.find(rawId);
562
+ await this.sessions.delete(rawId);
476
563
  if (session) {
477
564
  const user = await this.users.findById(session.userId);
478
565
  if (user)
@@ -488,7 +575,7 @@ export class Auth {
488
575
  */
489
576
  async requestEmailVerification(email) {
490
577
  const user = await this.users.findByEmail(canonicalEmail(email));
491
- if (!user || !this.allowEmailRequest('verify_email', user.id))
578
+ if (!user || !(await this.allowEmailRequest('verify_email', user.id)))
492
579
  return null;
493
580
  const token = await this.issueOneTimeToken(user.id, 'verify_email', this.verificationTtl);
494
581
  await this.hooks?.emit('auth:verify_requested', { user: publicUser(user), token });
@@ -502,11 +589,11 @@ export class Auth {
502
589
  return publicUser(user);
503
590
  }
504
591
  /** Per-account budget for reset/verification mails; false = drop silently. */
505
- allowEmailRequest(purpose, userId) {
592
+ async allowEmailRequest(purpose, userId) {
506
593
  if (!this.requestThrottle)
507
594
  return true;
508
595
  try {
509
- this.requestThrottle.reserve(`${purpose}:${userId}`);
596
+ await this.requestThrottle.reserve(`${purpose}:${userId}`);
510
597
  return true;
511
598
  }
512
599
  catch {
@@ -522,7 +609,7 @@ export class Auth {
522
609
  */
523
610
  async requestPasswordReset(email) {
524
611
  const user = await this.users.findByEmail(canonicalEmail(email));
525
- if (!user || !this.allowEmailRequest('reset_password', user.id))
612
+ if (!user || !(await this.allowEmailRequest('reset_password', user.id)))
526
613
  return null;
527
614
  const token = await this.issueOneTimeToken(user.id, 'reset_password', this.resetTtl);
528
615
  await this.hooks?.emit('auth:password_reset_requested', { user: publicUser(user), token });
@@ -696,7 +783,10 @@ export class Auth {
696
783
  throw new AuthTokenInvalidError(); // user vanished between issue and consume
697
784
  return user;
698
785
  }
699
- async issueTokens(userId, familyId = randomUUID()) {
786
+ async issueTokens(userId, family, amr) {
787
+ // A new family records the login's authentication methods in its id, so
788
+ // every rotation carries them forward without a store schema change.
789
+ const familyId = family ?? (amr && isAmr(amr) ? `${randomUUID()}.${amr.join('+')}` : randomUUID());
700
790
  const refreshToken = randomBytes(32).toString('base64url');
701
791
  await this.refreshTokens.create({
702
792
  // Persist only the hash; the raw token is returned to the client below.
@@ -707,8 +797,16 @@ export class Auth {
707
797
  });
708
798
  const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : undefined;
709
799
  return {
710
- accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
800
+ accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}), ...(amr && isAmr(amr) ? { amr } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
711
801
  refreshToken,
712
802
  };
713
803
  }
714
804
  }
805
+ /** The `amr` recorded in a refresh family id by {@link Auth} (undefined for older families). */
806
+ function amrOfFamily(familyId) {
807
+ const dot = familyId.lastIndexOf('.');
808
+ if (dot === -1)
809
+ return undefined;
810
+ const amr = familyId.slice(dot + 1).split('+');
811
+ return isAmr(amr) ? amr : undefined;
812
+ }
package/dist/index.d.ts CHANGED
@@ -5,16 +5,28 @@ declare module '@basaltkit/http' {
5
5
  interface RouteMeta {
6
6
  /** `true` requires a session; `false` opts a route out. */
7
7
  auth?: boolean;
8
+ /**
9
+ * `true`: the route requires a credential obtained with a second factor
10
+ * (step-up). `false`: exempt from `authPlugin({ requireMfa })`.
11
+ */
12
+ mfa?: boolean;
13
+ /**
14
+ * The route is about the caller's own account (sign-in, profile, MFA,
15
+ * accepting an invitation), not a tenant's data: tenant-membership guards
16
+ * (`@basaltkit/teams`' `tenantMembershipPlugin`) let non-members through.
17
+ */
18
+ account?: boolean;
8
19
  }
9
20
  }
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';
21
+ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
11
22
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
12
23
  export { authPlugin, AUTH, CsrfRejectedError, type AuthPluginOptions, type CsrfOptions } from './plugin.js';
13
24
  export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
14
25
  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';
26
+ export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
16
27
  export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
17
28
  export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
18
- export { LoginThrottle, AccountLockedError, type LoginThrottleOptions } from './throttle.js';
29
+ export { LoginThrottle, MemoryThrottleStore, AccountLockedError, type LoginThrottleOptions, type MemoryThrottleStoreOptions, type ThrottleStore, type ThrottleWindow, } from './throttle.js';
30
+ export { RedisThrottleStore, type RedisThrottleClient, type RedisThrottleStoreOptions } from './redis-throttle.js';
19
31
  export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, type PasskeyCredential, type StoredChallenge, type PasskeyStore, type WebAuthnChallengeStore, type WebAuthnVerifier, type VerifyRegistrationInput, type VerifiedRegistration, type VerifyAuthenticationInput, type VerifiedAuthentication, type WebAuthnConfig, type WebAuthnServiceOptions, type RegistrationOptions, type AuthenticationOptions, } from './webauthn.js';
20
32
  export { webauthnPlugin, WEBAUTHN, type WebAuthnPluginOptions } from './webauthn-plugin.js';
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
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, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, } from './auth.js';
4
+ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, } from './auth.js';
5
5
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
6
6
  export { authPlugin, AUTH, CsrfRejectedError } from './plugin.js';
7
7
  export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
8
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';
9
+ export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, 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
- export { LoginThrottle, AccountLockedError } from './throttle.js';
12
+ export { LoginThrottle, MemoryThrottleStore, AccountLockedError, } from './throttle.js';
13
+ export { RedisThrottleStore } from './redis-throttle.js';
13
14
  export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, } from './webauthn.js';
14
15
  export { webauthnPlugin, WEBAUTHN } from './webauthn-plugin.js';
package/dist/jwt.d.ts CHANGED
@@ -13,6 +13,11 @@ export interface JwtClaims {
13
13
  exp?: number;
14
14
  /** Access-token version — checked against TokenVersionStore for revocation. */
15
15
  tv?: number;
16
+ /**
17
+ * Authentication methods used at sign-in (RFC 8176 style): `pwd` (password),
18
+ * `fed` (social / SSO provider), `mfa` (a second factor was verified).
19
+ */
20
+ amr?: string[];
16
21
  [claim: string]: unknown;
17
22
  }
18
23
  /** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
@@ -2,6 +2,7 @@ import { createToken, ctx, definePlugin } from '@basaltkit/core';
2
2
  import { route } from '@basaltkit/http';
3
3
  import { z } from 'zod';
4
4
  import { AUTH } from './plugin.js';
5
+ import { ACCOUNT_META } from './routes.js';
5
6
  import { OAuth, stripTrailingSlashes } from './oauth.js';
6
7
  export const OAUTH = createToken('auth.oauth');
7
8
  /**
@@ -52,6 +53,7 @@ export function oauthRoutes(options) {
52
53
  route({
53
54
  method: 'GET',
54
55
  url: '/auth/oauth/:provider',
56
+ meta: { ...ACCOUNT_META },
55
57
  params: z.object({ provider: z.string() }),
56
58
  async handler({ params, reply }) {
57
59
  const { url, binding } = oauth().authorize(params.provider, redirectUri(params.provider));
@@ -61,6 +63,7 @@ export function oauthRoutes(options) {
61
63
  route({
62
64
  method: 'GET',
63
65
  url: '/auth/oauth/:provider/callback',
66
+ meta: { ...ACCOUNT_META },
64
67
  params: z.object({ provider: z.string() }),
65
68
  query: z.object({ code: z.string().max(4096), state: z.string().max(4096) }),
66
69
  async handler({ params, query, request, reply }) {