@basaltkit/auth 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -38,6 +38,8 @@ interface JwtClaims {
38
38
  sub: string;
39
39
  iat: number;
40
40
  exp?: number;
41
+ /** Access-token version — checked against TokenVersionStore for revocation. */
42
+ tv?: number;
41
43
  [claim: string]: unknown;
42
44
  }
43
45
  /** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
@@ -163,6 +165,12 @@ interface MfaRecord {
163
165
  secret: string;
164
166
  enabled: boolean;
165
167
  recoveryCodes: string[];
168
+ /**
169
+ * The last TOTP step (counter) accepted for this user. Codes at a step ≤ this
170
+ * are rejected, so an intercepted 6-digit code cannot be replayed within its
171
+ * validity window (RFC 6238 §5.2). Undefined until the first accepted code.
172
+ */
173
+ lastUsedStep?: number;
166
174
  }
167
175
  interface MfaStore {
168
176
  get(userId: string): Promise<MfaRecord | null>;
@@ -175,6 +183,23 @@ declare class MemoryMfaStore implements MfaStore {
175
183
  set(userId: string, record: MfaRecord): Promise<void>;
176
184
  delete(userId: string): Promise<void>;
177
185
  }
186
+ /**
187
+ * Per-user access-token version. Access tokens carry the version they were
188
+ * minted at; bumping it (on password reset or an explicit "log out everywhere")
189
+ * invalidates every access token issued before the bump — the missing piece for
190
+ * revoking stateless JWTs before they expire. Opt-in via `authPlugin`.
191
+ */
192
+ interface TokenVersionStore {
193
+ /** Current version for the user (0 if never bumped). */
194
+ get(userId: string): Promise<number>;
195
+ /** Bump the version and return the new value. */
196
+ increment(userId: string): Promise<number>;
197
+ }
198
+ declare class MemoryTokenVersionStore implements TokenVersionStore {
199
+ private readonly versions;
200
+ get(userId: string): Promise<number>;
201
+ increment(userId: string): Promise<number>;
202
+ }
178
203
  interface SessionRecord {
179
204
  id: string;
180
205
  userId: string;
@@ -264,6 +289,15 @@ declare class EmailTakenError extends BasaltError {
264
289
  readonly status = 409;
265
290
  constructor();
266
291
  }
292
+ /**
293
+ * Thrown at construction when the JWT signing secret is missing or too weak. A
294
+ * short/low-entropy HS256 key can be brute-forced offline, letting an attacker
295
+ * forge access tokens for any account — so this fails closed rather than boot
296
+ * with a guessable key. Use `@basaltkit/env`'s `secret({ minLength: 32 })`.
297
+ */
298
+ declare class WeakJwtSecretError extends BasaltError {
299
+ constructor(reason: string);
300
+ }
267
301
  declare class RefreshInvalidError extends BasaltError {
268
302
  readonly status = 401;
269
303
  constructor();
@@ -316,8 +350,23 @@ interface AuthOptions {
316
350
  refreshTtl?: DurationInput;
317
351
  sessionTtl?: DurationInput;
318
352
  hooks?: HookBus;
319
- /** Brute-force lockout. Enabled by default; pass `false` to disable. */
353
+ /** Brute-force lockout (per email). Enabled by default; pass `false` to disable. */
320
354
  loginThrottle?: LoginThrottle | false;
355
+ /**
356
+ * Per-IP login throttle — blunts password spraying (1 attempt across many
357
+ * accounts) and lockout-DoS that a per-email counter alone misses. Enabled by
358
+ * default with a higher budget than the per-email one; pass `false` to disable.
359
+ * Only applies when the caller passes the client ip to `login`.
360
+ */
361
+ ipLoginThrottle?: LoginThrottle | false;
362
+ /**
363
+ * Make the public registration endpoint enumeration-safe: a request for an
364
+ * email that already exists returns the same response (and does equivalent
365
+ * work) as a fresh signup, instead of a 409 that reveals the account exists.
366
+ * Applies to {@link Auth.registerSafely} (used by the register route); the
367
+ * lower-level {@link Auth.register} always throws on a duplicate. Default true.
368
+ */
369
+ enumerationSafeRegister?: boolean;
321
370
  /** Store for verification/reset tokens. Default: in-memory. */
322
371
  tokens?: AuthTokenStore;
323
372
  /** Email-verification link lifetime. Default 24h. */
@@ -326,6 +375,20 @@ interface AuthOptions {
326
375
  resetTtl?: DurationInput;
327
376
  /** Store for MFA (TOTP) enrollment state. Default: in-memory. */
328
377
  mfa?: MfaStore;
378
+ /**
379
+ * Enables access-token revocation. When set, access tokens carry a version
380
+ * (`tv`) and `resetPassword`/`revokeAllTokens` bump it — invalidating every
381
+ * token issued before the bump, even before its TTL expires. Opt-in; access
382
+ * verification then costs one store read per request. Default: off.
383
+ */
384
+ tokenVersions?: TokenVersionStore;
385
+ /**
386
+ * Key for encrypting TOTP secrets at rest (AES-256-GCM). When set, secrets are
387
+ * stored as `v1:` envelopes so a database leak can't recover a live second
388
+ * factor; existing plaintext records keep working and are encrypted on next
389
+ * write. Any length — derived to 32 bytes. Omit to store secrets in plaintext.
390
+ */
391
+ mfaEncryptionKey?: string | Buffer;
329
392
  /** Issuer name shown in authenticator apps. Default 'Basalt'. */
330
393
  mfaIssuer?: string;
331
394
  }
@@ -341,13 +404,28 @@ declare class Auth {
341
404
  private readonly sessionTtl;
342
405
  private readonly hooks;
343
406
  private readonly throttle;
407
+ private readonly ipThrottle;
344
408
  private readonly tokens;
345
409
  private readonly verificationTtl;
346
410
  private readonly resetTtl;
347
411
  private readonly mfa;
348
412
  private readonly mfaIssuer;
413
+ private readonly mfaKey;
414
+ private readonly tokenVersions;
415
+ private readonly enumerationSafeRegister;
349
416
  constructor(options: AuthOptions);
350
417
  register(email: string, password: string): Promise<PublicUser>;
418
+ /**
419
+ * Enumeration-safe registration for the public endpoint: creates the account
420
+ * for a new email, or — when the email is already taken — does equivalent work
421
+ * (so timing doesn't leak) and emits `auth:register_existing_email` so the app
422
+ * can send an out-of-band "you already have an account" email. Returns nothing
423
+ * either way, so the response can't reveal whether the account existed.
424
+ *
425
+ * With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
426
+ * duplicate instead (the classic, enumerable behavior).
427
+ */
428
+ registerSafely(email: string, password: string): Promise<void>;
351
429
  /** Verifies credentials without side effects. Null on failure. */
352
430
  attempt(email: string, password: string): Promise<AuthUser | null>;
353
431
  private dummyHashPromise?;
@@ -363,7 +441,9 @@ declare class Auth {
363
441
  * {@link MfaRequiredError} (without counting as a failed attempt), and a
364
442
  * wrong code throws {@link MfaInvalidCodeError}.
365
443
  */
366
- login(email: string, password: string, mfaCode?: string): Promise<{
444
+ login(email: string, password: string, mfaCode?: string, context?: {
445
+ ip?: string;
446
+ }): Promise<{
367
447
  user: PublicUser;
368
448
  tokens: TokenPair;
369
449
  }>;
@@ -375,7 +455,21 @@ declare class Auth {
375
455
  refresh(refreshToken: string): Promise<TokenPair>;
376
456
  /** Revokes a refresh family — logout for token-based clients. */
377
457
  revoke(refreshToken: string): Promise<void>;
458
+ /** Structural JWT verification only (signature + expiry). */
378
459
  verifyAccess(accessToken: string): JwtClaims;
460
+ /**
461
+ * Verifies the access token AND, when token-version revocation is enabled,
462
+ * rejects a token minted before the user's version was last bumped (i.e.
463
+ * revoked by a password reset / `revokeAllTokens`). Prefer this over
464
+ * {@link verifyAccess} on the request path.
465
+ */
466
+ verifyAccessToken(accessToken: string): Promise<JwtClaims>;
467
+ /**
468
+ * Revokes every access token issued so far for the user (logout-everywhere),
469
+ * by bumping the token version. No-op unless a {@link TokenVersionStore} is
470
+ * configured. Pair with refresh/session revocation for a full logout.
471
+ */
472
+ revokeAllTokens(userId: string): Promise<void>;
379
473
  createSession(userId: string): Promise<SessionRecord>;
380
474
  sessionUser(sessionId: string): Promise<AuthUser | null>;
381
475
  logout(sessionId: string): Promise<void>;
@@ -415,6 +509,10 @@ declare class Auth {
415
509
  * returns it plus an `otpauth://` URI to render as a QR code. Call
416
510
  * {@link activateMfa} with a code from the app to switch it on.
417
511
  */
512
+ /** Encrypt a TOTP secret for storage (no-op when no key is configured). */
513
+ private encryptMfaSecret;
514
+ /** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
515
+ private decryptMfaSecret;
418
516
  enrollMfa(userId: string): Promise<{
419
517
  secret: string;
420
518
  otpauthUri: string;
@@ -464,6 +562,13 @@ interface VerifyTotpOptions extends TotpOptions {
464
562
  /** Accept codes ±`window` steps to absorb clock drift. Default 1. */
465
563
  window?: number;
466
564
  }
565
+ /**
566
+ * The TOTP step (counter) that `token` matches within the allowed window, or
567
+ * null. Constant-time over the window (no early exit → no timing side channel).
568
+ * The step is what enables replay prevention: persist the last-accepted step and
569
+ * reject any code whose step is ≤ it (RFC 6238 §5.2).
570
+ */
571
+ declare function matchTotpStep(secret: string, token: string, options?: VerifyTotpOptions): number | null;
467
572
  /** True when `token` matches the TOTP within the allowed time window (constant-time). */
468
573
  declare function verifyTotp(secret: string, token: string, options?: VerifyTotpOptions): boolean;
469
574
  interface OtpauthUriInput {
@@ -487,6 +592,15 @@ declare module '@basaltkit/core' {
487
592
  'auth:registered': {
488
593
  user: PublicUser;
489
594
  };
595
+ /**
596
+ * Someone tried to register an email that already has an account. Emitted by
597
+ * the enumeration-safe register endpoint so the app can email the address
598
+ * ("you already have an account — sign in or reset your password") instead of
599
+ * revealing existence in the HTTP response. Only the email is provided.
600
+ */
601
+ 'auth:register_existing_email': {
602
+ email: string;
603
+ };
490
604
  'auth:login': {
491
605
  user: PublicUser;
492
606
  };
@@ -636,4 +750,4 @@ declare function apiKeyRoutes(): BasaltRoute[];
636
750
  */
637
751
  declare function mfaRoutes(): BasaltRoute[];
638
752
 
639
- export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryUserSource, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, type OtpauthUriInput, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifyTotpOptions, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, generateTotpSecret, mfaRoutes, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp };
753
+ export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryTokenVersionStore, MemoryUserSource, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, type OtpauthUriInput, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TokenVersionStore, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifyTotpOptions, WeakJwtSecretError, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, generateTotpSecret, matchTotpStep, mfaRoutes, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp };
package/dist/index.js CHANGED
@@ -168,6 +168,17 @@ var MemoryMfaStore = class {
168
168
  this.records.delete(userId);
169
169
  }
170
170
  };
171
+ var MemoryTokenVersionStore = class {
172
+ versions = /* @__PURE__ */ new Map();
173
+ async get(userId) {
174
+ return this.versions.get(userId) ?? 0;
175
+ }
176
+ async increment(userId) {
177
+ const next = (this.versions.get(userId) ?? 0) + 1;
178
+ this.versions.set(userId, next);
179
+ return next;
180
+ }
181
+ };
171
182
  var MemorySessionStore = class {
172
183
  sessions = /* @__PURE__ */ new Map();
173
184
  async create(userId, ttlMs) {
@@ -221,7 +232,7 @@ var MemoryRefreshTokenStore = class {
221
232
  };
222
233
 
223
234
  // src/auth.ts
224
- import { createHash as createHash2, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
235
+ import { createHash as createHash3, randomBytes as randomBytes5, randomUUID as randomUUID2 } from "crypto";
225
236
  import { BasaltError as BasaltError3, parseDuration as parseDuration2 } from "@basaltkit/core";
226
237
 
227
238
  // src/throttle.ts
@@ -320,23 +331,27 @@ function totp(secret, options = {}) {
320
331
  const counter = Math.floor(now / 1e3 / period);
321
332
  return hotp(base32Decode(secret), counter, digits);
322
333
  }
323
- function verifyTotp(secret, token, options = {}) {
334
+ function matchTotpStep(secret, token, options = {}) {
324
335
  const period = options.period ?? 30;
325
336
  const digits = options.digits ?? 6;
326
337
  const now = options.now ?? Date.now();
327
338
  const window = options.window ?? 1;
328
339
  const cleaned = token.replace(/\s/g, "");
329
- if (cleaned.length !== digits) return false;
340
+ if (cleaned.length !== digits) return null;
330
341
  const key = base32Decode(secret);
331
342
  const base = Math.floor(now / 1e3 / period);
332
- let ok = false;
343
+ let matched = -1;
333
344
  for (let error = -window; error <= window; error++) {
334
- const candidate = hotp(key, base + error, digits);
345
+ const step = base + error;
346
+ const candidate = hotp(key, step, digits);
335
347
  if (candidate.length === cleaned.length && timingSafeEqual3(Buffer.from(candidate), Buffer.from(cleaned))) {
336
- ok = true;
348
+ matched = step;
337
349
  }
338
350
  }
339
- return ok;
351
+ return matched === -1 ? null : matched;
352
+ }
353
+ function verifyTotp(secret, token, options = {}) {
354
+ return matchTotpStep(secret, token, options) !== null;
340
355
  }
341
356
  function otpauthUri(input) {
342
357
  const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`;
@@ -350,6 +365,28 @@ function otpauthUri(input) {
350
365
  return `otpauth://totp/${label}?${params.toString()}`;
351
366
  }
352
367
 
368
+ // src/secret-box.ts
369
+ import { createCipheriv, createDecipheriv, createHash as createHash2, randomBytes as randomBytes4 } from "crypto";
370
+ var PREFIX = "v1:";
371
+ function deriveKey(key) {
372
+ return createHash2("sha256").update(key).digest();
373
+ }
374
+ function encryptSecret(plaintext, key) {
375
+ const iv = randomBytes4(12);
376
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
377
+ const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
378
+ const tag = cipher.getAuthTag();
379
+ return `${PREFIX}${iv.toString("base64")}:${tag.toString("base64")}:${ct.toString("base64")}`;
380
+ }
381
+ function decryptSecret(value, key) {
382
+ if (!value.startsWith(PREFIX)) return value;
383
+ const [, ivB64, tagB64, ctB64] = value.split(":");
384
+ if (!ivB64 || !tagB64 || !ctB64) throw new Error("Malformed encrypted secret.");
385
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"));
386
+ decipher.setAuthTag(Buffer.from(tagB64, "base64"));
387
+ return Buffer.concat([decipher.update(Buffer.from(ctB64, "base64")), decipher.final()]).toString("utf8");
388
+ }
389
+
353
390
  // src/auth.ts
354
391
  var InvalidCredentialsError = class extends BasaltError3 {
355
392
  status = 401;
@@ -363,6 +400,11 @@ var EmailTakenError = class extends BasaltError3 {
363
400
  super("AUTH_EMAIL_TAKEN", "An account with this email already exists.");
364
401
  }
365
402
  };
403
+ var WeakJwtSecretError = class extends BasaltError3 {
404
+ constructor(reason) {
405
+ super("AUTH_WEAK_SECRET", `The auth signing secret is ${reason}. Set a strong APP_SECRET (>= 32 chars).`);
406
+ }
407
+ };
366
408
  var RefreshInvalidError = class extends BasaltError3 {
367
409
  status = 401;
368
410
  constructor() {
@@ -427,14 +469,22 @@ var Auth = class {
427
469
  sessionTtl;
428
470
  hooks;
429
471
  throttle;
472
+ ipThrottle;
430
473
  tokens;
431
474
  verificationTtl;
432
475
  resetTtl;
433
476
  mfa;
434
477
  mfaIssuer;
478
+ mfaKey;
479
+ tokenVersions;
480
+ enumerationSafeRegister;
435
481
  constructor(options) {
436
482
  this.users = options.users;
437
483
  this.secret = options.secret;
484
+ if (!this.secret) throw new WeakJwtSecretError("missing");
485
+ if (process.env["NODE_ENV"] === "production" && this.secret.length < 32) {
486
+ throw new WeakJwtSecretError("too short");
487
+ }
438
488
  this.hasher = options.hasher ?? new ScryptPasswordHasher();
439
489
  this.sessions = options.sessions ?? new MemorySessionStore();
440
490
  this.refreshTokens = options.refreshTokens ?? new MemoryRefreshTokenStore();
@@ -443,11 +493,15 @@ var Auth = class {
443
493
  this.sessionTtl = options.sessionTtl ?? "30d";
444
494
  this.hooks = options.hooks;
445
495
  this.throttle = options.loginThrottle === false ? void 0 : options.loginThrottle ?? new LoginThrottle();
496
+ this.ipThrottle = options.ipLoginThrottle === false ? void 0 : options.ipLoginThrottle ?? new LoginThrottle({ maxAttempts: 50, windowMs: 15 * 6e4 });
446
497
  this.tokens = options.tokens ?? new MemoryAuthTokenStore();
447
498
  this.verificationTtl = options.verificationTtl ?? "24h";
448
499
  this.resetTtl = options.resetTtl ?? "1h";
449
500
  this.mfa = options.mfa ?? new MemoryMfaStore();
450
501
  this.mfaIssuer = options.mfaIssuer ?? "Basalt";
502
+ this.mfaKey = options.mfaEncryptionKey ? deriveKey(options.mfaEncryptionKey) : void 0;
503
+ this.tokenVersions = options.tokenVersions;
504
+ this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
451
505
  }
452
506
  async register(email, password) {
453
507
  if (await this.users.findByEmail(email)) throw new EmailTakenError();
@@ -458,6 +512,30 @@ var Auth = class {
458
512
  await this.hooks?.emit("auth:registered", { user: publicUser(user) });
459
513
  return publicUser(user);
460
514
  }
515
+ /**
516
+ * Enumeration-safe registration for the public endpoint: creates the account
517
+ * for a new email, or — when the email is already taken — does equivalent work
518
+ * (so timing doesn't leak) and emits `auth:register_existing_email` so the app
519
+ * can send an out-of-band "you already have an account" email. Returns nothing
520
+ * either way, so the response can't reveal whether the account existed.
521
+ *
522
+ * With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
523
+ * duplicate instead (the classic, enumerable behavior).
524
+ */
525
+ async registerSafely(email, password) {
526
+ const existing = await this.users.findByEmail(email);
527
+ if (existing) {
528
+ if (!this.enumerationSafeRegister) throw new EmailTakenError();
529
+ await this.hasher.hash(password);
530
+ await this.hooks?.emit("auth:register_existing_email", { email });
531
+ return;
532
+ }
533
+ const user = await this.users.create({
534
+ email,
535
+ passwordHash: await this.hasher.hash(password)
536
+ });
537
+ await this.hooks?.emit("auth:registered", { user: publicUser(user) });
538
+ }
461
539
  /** Verifies credentials without side effects. Null on failure. */
462
540
  async attempt(email, password) {
463
541
  const user = await this.users.findByEmail(email);
@@ -482,19 +560,25 @@ var Auth = class {
482
560
  * {@link MfaRequiredError} (without counting as a failed attempt), and a
483
561
  * wrong code throws {@link MfaInvalidCodeError}.
484
562
  */
485
- async login(email, password, mfaCode) {
563
+ async login(email, password, mfaCode, context = {}) {
486
564
  const key = email.toLowerCase();
565
+ const ipKey = context.ip ? `ip:${context.ip}` : void 0;
487
566
  this.throttle?.assertAllowed(key);
567
+ if (ipKey) this.ipThrottle?.assertAllowed(ipKey);
568
+ const recordFailure = () => {
569
+ this.throttle?.recordFailure(key);
570
+ if (ipKey) this.ipThrottle?.recordFailure(ipKey);
571
+ };
488
572
  const user = await this.attempt(email, password);
489
573
  if (!user) {
490
- this.throttle?.recordFailure(key);
574
+ recordFailure();
491
575
  await this.hooks?.emit("auth:login_failed", { email });
492
576
  throw new InvalidCredentialsError();
493
577
  }
494
578
  if (await this.isMfaEnabled(user.id)) {
495
579
  if (!mfaCode) throw new MfaRequiredError();
496
580
  if (!await this.verifyMfaCode(user.id, mfaCode)) {
497
- this.throttle?.recordFailure(key);
581
+ recordFailure();
498
582
  throw new MfaInvalidCodeError();
499
583
  }
500
584
  }
@@ -525,9 +609,32 @@ var Auth = class {
525
609
  const record = await this.refreshTokens.find(this.hashToken(refreshToken));
526
610
  if (record) await this.refreshTokens.revokeFamily(record.familyId);
527
611
  }
612
+ /** Structural JWT verification only (signature + expiry). */
528
613
  verifyAccess(accessToken) {
529
614
  return verifyJwt(accessToken, this.secret);
530
615
  }
616
+ /**
617
+ * Verifies the access token AND, when token-version revocation is enabled,
618
+ * rejects a token minted before the user's version was last bumped (i.e.
619
+ * revoked by a password reset / `revokeAllTokens`). Prefer this over
620
+ * {@link verifyAccess} on the request path.
621
+ */
622
+ async verifyAccessToken(accessToken) {
623
+ const claims = this.verifyAccess(accessToken);
624
+ if (this.tokenVersions) {
625
+ const current = await this.tokenVersions.get(claims.sub);
626
+ if ((claims.tv ?? 0) < current) throw new AuthTokenInvalidError();
627
+ }
628
+ return claims;
629
+ }
630
+ /**
631
+ * Revokes every access token issued so far for the user (logout-everywhere),
632
+ * by bumping the token version. No-op unless a {@link TokenVersionStore} is
633
+ * configured. Pair with refresh/session revocation for a full logout.
634
+ */
635
+ async revokeAllTokens(userId) {
636
+ await this.tokenVersions?.increment(userId);
637
+ }
531
638
  async createSession(userId) {
532
639
  return this.sessions.create(userId, parseDuration2(this.sessionTtl));
533
640
  }
@@ -588,6 +695,7 @@ var Auth = class {
588
695
  });
589
696
  await this.refreshTokens.revokeAllForUser?.(user.id);
590
697
  await this.sessions.deleteAllForUser?.(user.id);
698
+ await this.tokenVersions?.increment(user.id);
591
699
  await this.hooks?.emit("auth:password_reset", { user: publicUser(user) });
592
700
  return publicUser(user);
593
701
  }
@@ -604,11 +712,19 @@ var Auth = class {
604
712
  * returns it plus an `otpauth://` URI to render as a QR code. Call
605
713
  * {@link activateMfa} with a code from the app to switch it on.
606
714
  */
715
+ /** Encrypt a TOTP secret for storage (no-op when no key is configured). */
716
+ encryptMfaSecret(secret) {
717
+ return this.mfaKey ? encryptSecret(secret, this.mfaKey) : secret;
718
+ }
719
+ /** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
720
+ decryptMfaSecret(stored) {
721
+ return this.mfaKey ? decryptSecret(stored, this.mfaKey) : stored;
722
+ }
607
723
  async enrollMfa(userId) {
608
724
  const user = await this.users.findById(userId);
609
725
  if (!user) throw new AuthRequiredError();
610
726
  const secret = generateTotpSecret();
611
- await this.mfa.set(userId, { secret, enabled: false, recoveryCodes: [] });
727
+ await this.mfa.set(userId, { secret: this.encryptMfaSecret(secret), enabled: false, recoveryCodes: [] });
612
728
  return {
613
729
  secret,
614
730
  otpauthUri: otpauthUri({ secret, account: user.email, issuer: this.mfaIssuer })
@@ -621,7 +737,8 @@ var Auth = class {
621
737
  async activateMfa(userId, code) {
622
738
  const record = await this.mfa.get(userId);
623
739
  if (!record || record.enabled) throw new MfaNotEnrolledError();
624
- if (!verifyTotp(record.secret, code)) throw new MfaInvalidCodeError();
740
+ const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
741
+ if (step === null) throw new MfaInvalidCodeError();
625
742
  const recoveryCodes = Array.from({ length: 10 }, () => this.generateRecoveryCode());
626
743
  await this.mfa.set(userId, {
627
744
  secret: record.secret,
@@ -647,7 +764,13 @@ var Auth = class {
647
764
  async verifyMfaCode(userId, code) {
648
765
  const record = await this.mfa.get(userId);
649
766
  if (!record || !record.enabled) return false;
650
- if (verifyTotp(record.secret, code)) return true;
767
+ const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
768
+ if (step !== null) {
769
+ if (record.lastUsedStep !== void 0 && step <= record.lastUsedStep) return false;
770
+ record.lastUsedStep = step;
771
+ await this.mfa.set(userId, record);
772
+ return true;
773
+ }
651
774
  const hash = this.hashRecoveryCode(code);
652
775
  const index = record.recoveryCodes.indexOf(hash);
653
776
  if (index === -1) return false;
@@ -656,21 +779,21 @@ var Auth = class {
656
779
  return true;
657
780
  }
658
781
  generateRecoveryCode() {
659
- const raw = randomBytes4(5).toString("hex");
660
- return `${raw.slice(0, 5)}-${raw.slice(5)}`;
782
+ const raw = randomBytes5(10).toString("hex");
783
+ return `${raw.slice(0, 5)}-${raw.slice(5, 10)}-${raw.slice(10, 15)}-${raw.slice(15)}`;
661
784
  }
662
785
  hashRecoveryCode(code) {
663
- return createHash2("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
786
+ return createHash3("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
664
787
  }
665
788
  // --- token helpers -------------------------------------------------------
666
789
  /** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
667
790
  * persisted, so a leak of the token/session table can't be replayed. */
668
791
  hashToken(token) {
669
- return createHash2("sha256").update(token).digest("hex");
792
+ return createHash3("sha256").update(token).digest("hex");
670
793
  }
671
794
  async issueOneTimeToken(userId, purpose, ttl) {
672
795
  await this.tokens.deleteForUser(userId, purpose);
673
- const token = randomBytes4(32).toString("base64url");
796
+ const token = randomBytes5(32).toString("base64url");
674
797
  await this.tokens.create({
675
798
  token: this.hashToken(token),
676
799
  userId,
@@ -695,7 +818,7 @@ var Auth = class {
695
818
  return user;
696
819
  }
697
820
  async issueTokens(userId, familyId = randomUUID2()) {
698
- const refreshToken = randomBytes4(32).toString("base64url");
821
+ const refreshToken = randomBytes5(32).toString("base64url");
699
822
  await this.refreshTokens.create({
700
823
  // Persist only the hash; the raw token is returned to the client below.
701
824
  token: this.hashToken(refreshToken),
@@ -703,8 +826,12 @@ var Auth = class {
703
826
  userId,
704
827
  expiresAt: Date.now() + parseDuration2(this.refreshTtl)
705
828
  });
829
+ const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : void 0;
706
830
  return {
707
- accessToken: signJwt({ sub: userId }, { secret: this.secret, expiresIn: this.accessTtl }),
831
+ accessToken: signJwt(
832
+ { sub: userId, ...tv !== void 0 ? { tv } : {} },
833
+ { secret: this.secret, expiresIn: this.accessTtl }
834
+ ),
708
835
  refreshToken
709
836
  };
710
837
  }
@@ -724,7 +851,7 @@ function authPlugin(options) {
724
851
  const header = request.headers.authorization;
725
852
  const bearer = typeof header === "string" && header.startsWith("Bearer ") ? header.slice("Bearer ".length) : void 0;
726
853
  if (bearer && !bearer.startsWith("mk_")) {
727
- const claims = auth2.verifyAccess(bearer);
854
+ const claims = await auth2.verifyAccessToken(bearer);
728
855
  const user = await auth2.users.findById(claims.sub);
729
856
  if (user) context.user = publicUser(user);
730
857
  return;
@@ -745,7 +872,7 @@ function authPlugin(options) {
745
872
  }
746
873
 
747
874
  // src/apikeys.ts
748
- import { createHash as createHash3, randomBytes as randomBytes5, randomUUID as randomUUID3 } from "crypto";
875
+ import { createHash as createHash4, randomBytes as randomBytes6, randomUUID as randomUUID3 } from "crypto";
749
876
  import { BasaltError as BasaltError4 } from "@basaltkit/core";
750
877
  var ScopeRequiredError = class extends BasaltError4 {
751
878
  status = 403;
@@ -754,7 +881,7 @@ var ScopeRequiredError = class extends BasaltError4 {
754
881
  }
755
882
  };
756
883
  var KEY_PREFIX = "mk_live_";
757
- var hashKey = (key) => createHash3("sha256").update(key).digest("hex");
884
+ var hashKey = (key) => createHash4("sha256").update(key).digest("hex");
758
885
  var strip = (record) => {
759
886
  const { hash: _hash, ...info } = record;
760
887
  return info;
@@ -771,7 +898,7 @@ var ApiKeys = class {
771
898
  }
772
899
  /** Mints a key. Returns the record plus the plaintext `key` (shown once). */
773
900
  async issue(input) {
774
- const secret = randomBytes5(24).toString("base64url");
901
+ const secret = randomBytes6(24).toString("base64url");
775
902
  const key = `${KEY_PREFIX}${secret}`;
776
903
  const record = {
777
904
  id: randomUUID3(),
@@ -876,17 +1003,24 @@ function authRoutes() {
876
1003
  method: "POST",
877
1004
  url: "/auth/register",
878
1005
  body: credentials,
1006
+ // Enumeration-safe: the same 202 whether the email is new or already taken
1007
+ // (a collision is signalled out-of-band via auth:register_existing_email).
879
1008
  async handler({ body, reply }) {
880
- const user = await auth().register(body.email, body.password);
881
- return reply.code(201).send(user);
1009
+ await auth().registerSafely(body.email, body.password);
1010
+ return reply.code(202).send({ ok: true });
882
1011
  }
883
1012
  }),
884
1013
  route({
885
1014
  method: "POST",
886
1015
  url: "/auth/login",
887
1016
  body: credentials.extend({ mfaCode: z.string().optional() }),
888
- async handler({ body }) {
889
- const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode);
1017
+ async handler({ body, request }) {
1018
+ const { user, tokens } = await auth().login(
1019
+ body.email,
1020
+ body.password,
1021
+ body.mfaCode,
1022
+ request.ip ? { ip: request.ip } : {}
1023
+ );
890
1024
  return { user, ...tokens };
891
1025
  }
892
1026
  }),
@@ -1073,6 +1207,7 @@ export {
1073
1207
  MemoryMfaStore,
1074
1208
  MemoryRefreshTokenStore,
1075
1209
  MemorySessionStore,
1210
+ MemoryTokenVersionStore,
1076
1211
  MemoryUserSource,
1077
1212
  MfaInvalidCodeError,
1078
1213
  MfaNotEnrolledError,
@@ -1084,6 +1219,7 @@ export {
1084
1219
  TokenExpiredError,
1085
1220
  TokenInvalidError,
1086
1221
  UserUpdateUnsupportedError,
1222
+ WeakJwtSecretError,
1087
1223
  apiKeyRoutes,
1088
1224
  apiKeysPlugin,
1089
1225
  authPlugin,
@@ -1091,6 +1227,7 @@ export {
1091
1227
  base32Decode,
1092
1228
  base32Encode,
1093
1229
  generateTotpSecret,
1230
+ matchTotpStep,
1094
1231
  mfaRoutes,
1095
1232
  otpauthUri,
1096
1233
  publicUser,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -15,7 +15,7 @@
15
15
  ],
16
16
  "dependencies": {
17
17
  "@basaltkit/core": "^1.0.0",
18
- "@basaltkit/fastify": "^1.1.0"
18
+ "@basaltkit/fastify": "^1.3.0"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "zod": "^3.24.0 || ^4.0.0"