@lenne.tech/nest-server 12.5.0 → 12.6.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.
Files changed (51) hide show
  1. package/.claude/rules/better-auth.md +29 -0
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/testing.md +5 -4
  4. package/CLAUDE.md +4 -0
  5. package/FRAMEWORK-API.md +1 -1
  6. package/dist/core/common/services/rate-limit-store.d.ts +1 -0
  7. package/dist/core/common/services/rate-limit-store.js +3 -3
  8. package/dist/core/common/services/rate-limit-store.js.map +1 -1
  9. package/dist/core/modules/better-auth/core-better-auth-api.middleware.d.ts +1 -0
  10. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +27 -4
  11. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  12. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +31 -1
  13. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +96 -14
  14. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  15. package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js +8 -1
  16. package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js.map +1 -1
  17. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +8 -0
  18. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +93 -0
  19. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -0
  20. package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.d.ts +3 -0
  21. package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js +29 -0
  22. package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js.map +1 -0
  23. package/dist/core/modules/better-auth/core-better-auth.controller.d.ts +8 -0
  24. package/dist/core/modules/better-auth/core-better-auth.controller.js +53 -2
  25. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  26. package/dist/core/modules/better-auth/core-better-auth.module.d.ts +1 -0
  27. package/dist/core/modules/better-auth/core-better-auth.module.js +10 -1
  28. package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
  29. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +4 -0
  30. package/dist/core/modules/better-auth/core-better-auth.service.js +27 -2
  31. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  32. package/dist/core/modules/system-setup/core-system-setup.service.d.ts +59 -2
  33. package/dist/core/modules/system-setup/core-system-setup.service.js +157 -28
  34. package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
  35. package/docs/REQUEST-LIFECYCLE.md +12 -0
  36. package/migration-guides/12.5.x-to-12.6.x.md +213 -0
  37. package/migration-guides/12.6.0-to-12.6.1.md +66 -0
  38. package/package.json +5 -4
  39. package/src/core/common/interfaces/server-options.interface.ts +6 -5
  40. package/src/core/common/services/rate-limit-store.ts +9 -3
  41. package/src/core/modules/better-auth/README.md +27 -0
  42. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +39 -5
  43. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +218 -35
  44. package/src/core/modules/better-auth/core-better-auth-openapi.helper.ts +8 -1
  45. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +157 -0
  46. package/src/core/modules/better-auth/core-better-auth-verification-link.helper.ts +53 -0
  47. package/src/core/modules/better-auth/core-better-auth.controller.ts +64 -2
  48. package/src/core/modules/better-auth/core-better-auth.module.ts +18 -2
  49. package/src/core/modules/better-auth/core-better-auth.service.ts +60 -2
  50. package/src/core/modules/system-setup/README.md +20 -4
  51. package/src/core/modules/system-setup/core-system-setup.service.ts +290 -45
@@ -551,11 +551,12 @@ export interface IBetterAuthEmailVerificationConfig {
551
551
  * When not set, the verification link points directly to the backend
552
552
  * endpoint which handles verification and redirects.
553
553
  *
554
- * Since 11.38.0 the generated link carries the recipient's address as well —
555
- * `{callbackURL}?token=<token>&email=<address>`. The verification page needs it to offer
556
- * "send a new email" once the token has expired, and it cannot recover the address itself:
557
- * that value lives inside the token's JWT payload, and reading it there would mean rendering
558
- * data from an unverified signature.
554
+ * Since 12.6.0 the link carries the token only, and sealed — `{callbackURL}?token=<sealed>`: no `email`
555
+ * parameter, and the token is encrypted, because Better-Auth's own token is a readable JWT with the
556
+ * address in it. Pass the token on unchanged: `GET /iam/verify-email?token=…` opens it, and for an expired
557
+ * link `POST /iam/resend-verification-email` with `{ token }` sends a new mail and answers the address
558
+ * masked (`GET /iam/features` → `resendVerificationByToken`). From 11.38.0 to 12.5.x the link carried
559
+ * `&email=<address>`.
559
560
  *
560
561
  * @default undefined (backend-handled verification)
561
562
  * @since 11.13.0
@@ -59,6 +59,12 @@ export interface RateLimitStoreHit {
59
59
  count: number;
60
60
  /** Seconds until the window resets */
61
61
  resetIn: number;
62
+ /**
63
+ * `true` when the key did not fit into the store and {@link count} is that of a shared overflow bucket — i.e. it
64
+ * counts other clients too. A caller for whom refusing a stranger's share is worse than not counting may let such a
65
+ * hit through; most limiters must not, or filling the keyspace would switch them off.
66
+ */
67
+ overflow?: boolean;
62
68
  }
63
69
 
64
70
  /**
@@ -198,11 +204,11 @@ export class InMemoryRateLimitStore implements RateLimitStore {
198
204
 
199
205
  if (!entry || now >= entry.resetTime) {
200
206
  this.overflow.set(slot, { count: 1, resetTime: now + windowSeconds * 1000 });
201
- return { count: 1, resetIn: windowSeconds };
207
+ return { count: 1, overflow: true, resetIn: windowSeconds };
202
208
  }
203
209
 
204
210
  entry.count++;
205
- return { count: entry.count, resetIn: Math.ceil((entry.resetTime - now) / 1000) };
211
+ return { count: entry.count, overflow: true, resetIn: Math.ceil((entry.resetTime - now) / 1000) };
206
212
  }
207
213
 
208
214
  size(): number {
@@ -382,7 +388,7 @@ export class RedisRateLimitStore implements RateLimitStore {
382
388
  'over, so they may be limited earlier than their own traffic warrants. Existing limits are unaffected.',
383
389
  );
384
390
  }
385
- return { count, resetIn: ttl };
391
+ return overflow ? { count, overflow: true, resetIn: ttl } : { count, resetIn: ttl };
386
392
  },
387
393
  () => this.fallback.hit(key, windowSeconds),
388
394
  );
@@ -557,6 +557,33 @@ in to their account, and what the recipient enters there lands with them (login
557
557
  signs in once, as in Better-Auth's own default. Switch it on (`emailVerification: { autoSignInAfterVerification: true }`)
558
558
  only where a verification link reaches nobody but its owner.
559
559
 
560
+ **The link carries the token only, sealed, and an expired link is recovered with it (12.6.0).** The verification link
561
+ ends in `?token=…`. Until then it also carried the address (`&email=`), so the page could offer "send a new email", and
562
+ the address stood in the mail, the browser history and the access logs. Better-Auth's own token is a signed but
563
+ readable JWT with the address and the user id in it, so the link carries it encrypted (compact JWE, key derived from
564
+ Better-Auth's secret, `core-better-auth-verification-link.helper.ts`): the API middleware opens it for
565
+ `GET /iam/verify-email`, and Better-Auth verifies the token it signed. A plain token from a mail sent before the update
566
+ still works. A page passes the token on unchanged, and for an expired link sends it to
567
+ `POST /iam/resend-verification-email` (`{ "token": "…" }`):
568
+
569
+ - the server checks Better-Auth's signature (an expired token is fine, a forged one sends nothing) and has
570
+ Better-Auth's own `sendVerificationEmail` send a new mail to the address in the token, which goes out only to an
571
+ existing, unverified account; the resend cooldown applies on top, and the token of an address change sends nothing;
572
+ - the answer is always `200 { "email": "k***@example.com", "success": true }` — the masked address of the token, or
573
+ `null` for an invalid token — whether the account exists, is verified, or a mail went out;
574
+ - it never verifies, signs in or creates a session;
575
+ - 3 requests an hour with valid links for one address (sealed or plain, older or newer, they count together), and 10
576
+ invalid tokens per client address an hour; past either `429 LTNS_0020`. The token is checked first: an invalid one
577
+ is counted only per client address, a valid one only per address it names, each in a counter store of its own. Junk
578
+ therefore never reaches the counters of real tokens, and behind a proxy without `trustProxy`, where every client
579
+ shares the proxy's address, it can only lock out more junk. Once the store of valid-token counters is full (someone
580
+ signed up thousands of addresses and replays their links), a valid token is answered rather than refused for
581
+ traffic that is not its own; the per-address cooldown of the verification mail still bounds what goes out. Shared
582
+ across replicas through Redis when `redis` is configured.
583
+
584
+ `GET /iam/features` reports `resendVerificationByToken: true` while email verification is enabled, so a page can fall
585
+ back to asking for the address against an older server.
586
+
560
587
  ### Sign-Up Checks (v11.13.0+)
561
588
 
562
589
  Sign-up validation is **enabled by default** requiring `termsAndPrivacyAccepted: true`.
@@ -9,8 +9,9 @@ import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.help
9
9
  import { isControllerHandledPath } from './core-better-auth-openapi.helper.js';
10
10
  import { runWithResetPassword } from './core-better-auth-password-reset.registry.js';
11
11
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
12
- import { extractSessionToken, sendWebResponse, signCookieValue, toWebRequest } from './core-better-auth-web.helper.js';
12
+ import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper.js';
13
13
  import { CoreBetterAuthService } from './core-better-auth.service.js';
14
+ import { openVerificationToken } from './core-better-auth-verification-link.helper.js';
14
15
 
15
16
  /**
16
17
  * Native Better-Auth routes that set a NEW password from a token or OTP, with the body
@@ -355,6 +356,10 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
355
356
  }
356
357
  }
357
358
 
359
+ // The verification link carries Better-Auth's token sealed (it is a readable JWT with the address in it);
360
+ // Better-Auth verifies the token it signed, so open it before the request is built.
361
+ await this.openVerificationLinkToken(req, relativePath);
362
+
358
363
  // Put a reset password into the shape sign-in expects BEFORE the body is
359
364
  // serialized, and keep the value for the legacy mirror below.
360
365
  const resetPassword = this.normalizeResetPassword(req, relativePath);
@@ -453,7 +458,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
453
458
  this.logger.debug(`Stored challenge mapping with ID: ${challengeId.substring(0, 8)}...`);
454
459
 
455
460
  // Send the enhanced response
456
- await sendWebResponse(res, enhancedResponse);
461
+ await this.betterAuthService.sendBetterAuthResponse(res, enhancedResponse);
457
462
 
458
463
  return;
459
464
  } else {
@@ -514,7 +519,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
514
519
  });
515
520
 
516
521
  this.logger.debug('Enriched passkey verify response with user data');
517
- await sendWebResponse(res, enrichedResponse);
522
+ await this.betterAuthService.sendBetterAuthResponse(res, enrichedResponse);
518
523
  return;
519
524
  }
520
525
  }
@@ -532,8 +537,9 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
532
537
  return next();
533
538
  }
534
539
 
535
- // Convert Web Standard Response to Express response using shared helper
536
- await sendWebResponse(res, response);
540
+ // Convert Web Standard Response to Express response, through the token policy (12.6.1): a forwarded route must
541
+ // not hand out what the framework's own sign-in would not
542
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
537
543
  } catch (error) {
538
544
  // A refused request (the password length policy) is an answer, not a handler failure. Nest's middleware
539
545
  // proxy hands a thrown exception to the exception filters, so it is rendered like the same refusal from a
@@ -559,4 +565,32 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
559
565
  }
560
566
  }
561
567
  }
568
+
569
+ /**
570
+ * Replace the sealed token of a verification link (`GET /verify-email?token=…`) by the token Better-Auth signed, so
571
+ * Better-Auth verifies it unchanged (core-better-auth-verification-link.helper.ts). A plain token (a link mailed
572
+ * before the seal) and a value that does not open go on as they are: Better-Auth answers the latter like any
573
+ * invalid token.
574
+ */
575
+ protected async openVerificationLinkToken(req: Request, relativePath: string): Promise<void> {
576
+ if (relativePath !== '/verify-email') {
577
+ return;
578
+ }
579
+ const sealed = new URL(req.originalUrl || req.url, 'http://local').searchParams.get('token');
580
+ if (!sealed) {
581
+ return;
582
+ }
583
+ const secret = (await this.betterAuthService.getInstance()?.$context)?.secret;
584
+ const opened = secret ? await openVerificationToken(secret, sealed) : undefined;
585
+ if (!opened || opened === sealed) {
586
+ return;
587
+ }
588
+ const withToken = (url: string): string => {
589
+ const parsed = new URL(url, 'http://local');
590
+ parsed.searchParams.set('token', opened);
591
+ return `${parsed.pathname}${parsed.search}`;
592
+ };
593
+ req.originalUrl = withToken(req.originalUrl || req.url);
594
+ req.url = withToken(req.url);
595
+ }
562
596
  }
@@ -1,18 +1,27 @@
1
- import { Inject, Injectable, Logger, Optional } from '@nestjs/common';
2
- import { randomUUID } from 'node:crypto';
1
+ import { HttpException, HttpStatus, Inject, Injectable, Logger, Optional } from '@nestjs/common';
2
+ import { jwtVerify } from 'jose';
3
+ import { JWTExpired } from 'jose/errors';
4
+ import { createHash, randomUUID } from 'node:crypto';
3
5
  import ejs from 'ejs';
4
6
  import * as fs from 'fs';
5
7
  import * as path from 'path';
6
8
 
7
- import { isLocalEnv, isProductionLikeEnv, resolveAppUrlFromConfig } from '../../common/helpers/cookies.helper.js';
9
+ import { isLocalEnv, resolveAppUrlFromConfig } from '../../common/helpers/cookies.helper.js';
8
10
  import { maskEmail } from '../../common/helpers/logging.helper.js';
9
11
  import { IBetterAuthEmailVerificationConfig } from '../../common/interfaces/server-options.interface.js';
10
12
  import { BrevoService } from '../../common/services/brevo.service.js';
11
13
  import { ConfigService } from '../../common/services/config.service.js';
12
14
  import { CoreRedisService } from '../../common/services/core-redis.service.js';
15
+ import {
16
+ InMemoryRateLimitStore,
17
+ type RateLimitStore,
18
+ RedisRateLimitStore,
19
+ } from '../../common/services/rate-limit-store.js';
20
+ import { ErrorCode } from '../error-code/error-codes.js';
13
21
  import { EmailService } from '../../common/services/email.service.js';
14
22
  import { TemplateService } from '../../common/services/template.service.js';
15
23
  import { AuthEmailCallbackOptions, formatProjectName } from './better-auth.config.js';
24
+ import { openVerificationToken } from './core-better-auth-verification-link.helper.js';
16
25
  import { callerDirectory } from '../../common/helpers/module-location.helper.js';
17
26
 
18
27
  /**
@@ -226,7 +235,7 @@ export class CoreBetterAuthEmailVerificationService {
226
235
  try {
227
236
  // Override URL if callbackURL is configured (frontend-based verification)
228
237
  if (this.config.callbackURL) {
229
- url = this.buildFrontendVerificationUrl(token, user.email);
238
+ url = this.buildFrontendVerificationUrl(token);
230
239
  }
231
240
 
232
241
  this.logAuthUrlForDevelopment('EMAIL VERIFICATION', user.email, url);
@@ -728,7 +737,7 @@ export class CoreBetterAuthEmailVerificationService {
728
737
  * @param token - The verification token from Better-Auth
729
738
  * @returns The full frontend URL with token query parameter
730
739
  */
731
- protected buildFrontendVerificationUrl(token: string, email?: string): string {
740
+ protected buildFrontendVerificationUrl(token: string): string {
732
741
  let baseUrl = this.config.callbackURL!;
733
742
 
734
743
  // Resolve relative paths against appUrl
@@ -737,30 +746,189 @@ export class CoreBetterAuthEmailVerificationService {
737
746
  baseUrl = `${appUrl.replace(/\/$/, '')}${baseUrl}`;
738
747
  }
739
748
 
740
- // Append token as query parameter
749
+ // The token only — and the token arrives here SEALED (CoreBetterAuthModule's mail callback,
750
+ // core-better-auth-verification-link.helper.ts), because Better-Auth's own token is a readable JWT with the address
751
+ // in it. Until DEV-4056 the address also travelled as `&email=`, so the page could offer "send a new email" for an
752
+ // expired link; it stood in the mail, in the browser history and in every access log the app keeps. The page now
753
+ // asks for a new mail WITH the token (POST /iam/resend-verification-email): the server opens it, reads the address
754
+ // and answers with a masked form, so the address never leaves it.
741
755
  const separator = baseUrl.includes('?') ? '&' : '?';
742
- let url = `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
756
+ return `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
757
+ }
743
758
 
744
- // The address travels alongside the token so the page can offer "send a new email" when the
745
- // token turns out to be expired — which is the ONLY moment that button matters, and precisely
746
- // the moment the page has nothing else to work with. The verification page shipped by
747
- // nuxt-base-starter gates that button on `route.query.email`, so without this the user is told
748
- // correctly what went wrong and left with no way to fix it.
749
- //
750
- // The frontend cannot recover the address itself. It is inside the token's JWT payload, and
751
- // reading it there would mean trusting an unverified signature for display — not a pattern to
752
- // put in a starter.
753
- //
754
- // The cost, stated plainly: the address appears in the URL, so it reaches browser history and
755
- // any access log the app keeps. It is the recipient's OWN address, arriving in their own
756
- // mailbox next to a token that is far more sensitive, so this widens nothing that the link did
757
- // not already carry. Encoded, because a `+` in an address (Gmail tags, and therefore most test
758
- // addresses) would otherwise arrive as a space.
759
- if (email) {
760
- url += `&email=${encodeURIComponent(email)}`;
759
+ // ===================================================================================================================
760
+ // Resend by token (POST /iam/resend-verification-email)
761
+ // ===================================================================================================================
762
+
763
+ /**
764
+ * Requests with a VALID token for one address per {@link resendByTokenWindowSeconds}, counted under the address the
765
+ * token names: the sealed and the plain form of a link, and every other link for that address, share the counter
766
+ */
767
+ protected readonly resendByTokenMaxPerToken = 3;
768
+
769
+ /**
770
+ * Requests with an INVALID token one client address may make per {@link resendByTokenWindowSeconds}. Valid tokens
771
+ * are not counted here: behind a reverse proxy without `trustProxy` every client has the proxy's address, and a
772
+ * bucket shared by everyone would let one anonymous caller lock the resend for all users with ten junk requests.
773
+ */
774
+ protected readonly resendByTokenMaxPerIp = 10;
775
+
776
+ protected readonly resendByTokenWindowSeconds = 3600;
777
+
778
+ /**
779
+ * Keys each resend counter store holds before new keys fold into its shared overflow buckets (see
780
+ * `InMemoryRateLimitStore` / `RedisRateLimitStore`)
781
+ */
782
+ protected readonly resendLimitStoreCapacity: number = 10_000;
783
+
784
+ /**
785
+ * The counters behind the two limits, one store each, shared through Redis when configured and process-local
786
+ * otherwise. Separate on purpose: invalid tokens cost nothing to make, and in a shared store a flood of them fills
787
+ * the capacity until every valid token lands in an overflow bucket that is already past its limit.
788
+ */
789
+ protected resendByTokenStore?: RateLimitStore;
790
+ protected resendByAddressStore?: RateLimitStore;
791
+
792
+ /**
793
+ * Send a new verification mail for the address a verification token belongs to — the token of an EXPIRED link
794
+ * included, which is the case this exists for. The caller types nothing, and the address never leaves the server:
795
+ * the answer carries it masked ({@link maskEmailForDisplay}).
796
+ *
797
+ * - The token is the one the link carries: sealed (core-better-auth-verification-link.helper.ts), or plain from a
798
+ * link mailed before the seal. It must carry Better-Auth's signature (HS256 with its secret) once opened; a forged
799
+ * or garbled token sends nothing.
800
+ * - A new mail goes out only through Better-Auth's own `sendVerificationEmail`, which sends to an existing,
801
+ * unverified account and to nothing else; the per-address cooldown of {@link sendVerificationEmail} applies on
802
+ * top. A token of an address change (`updateTo`) sends nothing.
803
+ * - The answer is the same whatever happened: `{ email: <masked address of the token>, success: true }`, `email`
804
+ * null for an invalid token. Whoever holds a valid token received it at that address, so the masked form tells
805
+ * them nothing new, and nothing in the answer says whether an account exists, is verified, or was mailed.
806
+ * - It never verifies, signs in or creates a session.
807
+ *
808
+ * @throws HttpException 429 `RATE_LIMIT_EXCEEDED` past {@link resendByTokenMaxPerToken} requests with valid tokens
809
+ * for one address or past {@link resendByTokenMaxPerIp} invalid tokens from one client address within the window.
810
+ * The token is checked first: an invalid one is counted only per client address, so junk never creates a counter
811
+ * in the store valid tokens use (the answer already says it is invalid, so the order tells nobody anything more)
812
+ */
813
+ async resendVerificationByToken(
814
+ authInstance:
815
+ | null
816
+ | undefined
817
+ | {
818
+ $context: Promise<{ secret: string }>;
819
+ // Better-Auth's own endpoint function; typed loosely because its declared type is an overload set
820
+ api: { sendVerificationEmail: (request: { body: { email: string } }) => Promise<unknown> };
821
+ },
822
+ token: unknown,
823
+ clientAddress: string | undefined,
824
+ ): Promise<{ email: null | string; success: true }> {
825
+ const tokenValue = typeof token === 'string' ? token : '';
826
+
827
+ let claims: undefined | { email: string; updateTo?: string };
828
+ if (authInstance && tokenValue) {
829
+ const { secret } = await authInstance.$context;
830
+ const opened = await openVerificationToken(secret, tokenValue);
831
+ claims = opened ? await this.readVerificationTokenClaims(secret, opened) : undefined;
832
+ }
833
+ if (!claims) {
834
+ // The answer already says the token is invalid (`email: null`), so counting only these per address tells
835
+ // nobody anything more, and a valid token cannot be locked out by a stranger behind the same proxy
836
+ await this.assertResendAddressLimit(clientAddress);
837
+ return { email: null, success: true };
761
838
  }
839
+ await this.assertResendTokenLimit(claims.email);
762
840
 
763
- return url;
841
+ if (!claims.updateTo) {
842
+ try {
843
+ await authInstance.api.sendVerificationEmail({ body: { email: claims.email } });
844
+ } catch (error) {
845
+ // The answer must not differ: a failed send (verification switched off, an SMTP outage) is logged, not told
846
+ this.logger.debug(
847
+ `Resend by token for ${maskEmail(claims.email)} sent nothing: ${
848
+ error instanceof Error ? error.message : 'Unknown error'
849
+ }`,
850
+ );
851
+ }
852
+ }
853
+ return { email: this.maskEmailForDisplay(claims.email), success: true };
854
+ }
855
+
856
+ /** The counter store of one resend limit, created on first use */
857
+ protected resendLimitStore(scope: 'address' | 'token'): RateLimitStore {
858
+ const create = (namespace: string): RateLimitStore =>
859
+ this.coreRedisService?.enabled
860
+ ? new RedisRateLimitStore(this.coreRedisService, namespace, this.resendLimitStoreCapacity)
861
+ : new InMemoryRateLimitStore(this.resendLimitStoreCapacity);
862
+ if (scope === 'token') {
863
+ this.resendByTokenStore ??= create('email-verification-resend-token');
864
+ return this.resendByTokenStore;
865
+ }
866
+ this.resendByAddressStore ??= create('email-verification-resend-address');
867
+ return this.resendByAddressStore;
868
+ }
869
+
870
+ /**
871
+ * Count a request with a valid token against the address it names, by the address's hash (no PII in the key).
872
+ *
873
+ * A count from a shared overflow bucket (the store is full) never refuses: valid tokens cost a sign-up each, so an
874
+ * attacker who signs up ten thousand addresses of their own and replays the links could otherwise fill the store
875
+ * and push every other user's resend into a bucket past its limit. Mail volume stays bounded without it — the
876
+ * per-address cooldown of {@link sendVerificationEmail} applies to every resend.
877
+ */
878
+ protected async assertResendTokenLimit(email: string): Promise<void> {
879
+ const tokenKey = createHash('sha256').update(email.trim().toLowerCase()).digest('hex');
880
+ const perToken = await this.resendLimitStore('token').hit(`token:${tokenKey}`, this.resendByTokenWindowSeconds);
881
+ if (perToken.count > this.resendByTokenMaxPerToken && !perToken.overflow) {
882
+ throw new HttpException(ErrorCode.RATE_LIMIT_EXCEEDED, HttpStatus.TOO_MANY_REQUESTS);
883
+ }
884
+ }
885
+
886
+ /** Count an invalid token against the client address it came from */
887
+ protected async assertResendAddressLimit(clientAddress: string | undefined): Promise<void> {
888
+ const key = `ip:${clientAddress || 'unknown'}`;
889
+ const perAddress = await this.resendLimitStore('address').hit(key, this.resendByTokenWindowSeconds);
890
+ if (perAddress.count > this.resendByTokenMaxPerIp) {
891
+ throw new HttpException(ErrorCode.RATE_LIMIT_EXCEEDED, HttpStatus.TOO_MANY_REQUESTS);
892
+ }
893
+ }
894
+
895
+ /**
896
+ * The claims of a verification token Better-Auth signed (`createEmailVerificationToken`: HS256 with its secret,
897
+ * `{ email, updateTo?, userId? }`), expired or not. `undefined` for anything without a valid signature.
898
+ */
899
+ protected async readVerificationTokenClaims(
900
+ secret: string,
901
+ token: string,
902
+ ): Promise<undefined | { email: string; updateTo?: string }> {
903
+ let payload: Record<string, unknown>;
904
+ try {
905
+ ({ payload } = await jwtVerify(token, new TextEncoder().encode(secret), { algorithms: ['HS256'] }));
906
+ } catch (error) {
907
+ // jose checks the signature before the expiry, so an expired token carries its verified claims
908
+ if (!(error instanceof JWTExpired)) {
909
+ return undefined;
910
+ }
911
+ payload = error.payload;
912
+ }
913
+ if (typeof payload.email !== 'string' || !payload.email.includes('@')) {
914
+ return undefined;
915
+ }
916
+ return {
917
+ email: payload.email,
918
+ updateTo: typeof payload.updateTo === 'string' && payload.updateTo ? payload.updateTo : undefined,
919
+ };
920
+ }
921
+
922
+ /**
923
+ * The address as the page may show it: the first character, `***`, the domain — `k***@lenne.tech`. Enough to
924
+ * recognise one's own mailbox, not enough to learn an address.
925
+ */
926
+ protected maskEmailForDisplay(email: string): string {
927
+ const at = email.lastIndexOf('@');
928
+ if (at < 1) {
929
+ return '***';
930
+ }
931
+ return `${email[0]}***${email.slice(at)}`;
764
932
  }
765
933
 
766
934
  /**
@@ -858,32 +1026,47 @@ export class CoreBetterAuthEmailVerificationService {
858
1026
  * passed it and wrote live reset links into their log pipeline, where log access alone was
859
1027
  * enough to take over an account.
860
1028
  *
861
- * `LT_LOG_AUTH_URLS=1` opts in for another environment that runs on a developer machine (this
862
- * repository's own `development`, for one); `LT_LOG_AUTH_URLS=0` suppresses it everywhere. A
863
- * production-like environment never prints, whatever the variable says: the opt-in exists for
864
- * laptops, and a hard floor keeps it from being the thing that reopens a deployment.
1029
+ * Nothing opens it elsewhere (12.6.0): until then `LT_LOG_AUTH_URLS=1` printed it in any
1030
+ * environment but `production` and `staging`, and an environment name says nothing reliable about
1031
+ * whether it is a laptop — `development` names a deployed stage as often as a machine. A live token
1032
+ * and the line's `UserKey` (a pseudonym of the address) must never reach a deployment's logs.
1033
+ * `LT_LOG_AUTH_URLS=0` still suppresses the line in the local environments.
1034
+ *
1035
+ * The process's own `NODE_ENV` must agree (12.6.0): `getEnvironmentConfig()` answers a `NODE_ENV` without a
1036
+ * configuration key (`development`, `dev`, `staging` in a project that defines none of them) with the `local`
1037
+ * block, whose `env` then claims `local` on a deployed stage, and so does an EMPTY `NODE_ENV` (`'' || 'local'`). So
1038
+ * the line needs both a local `env` and a `NODE_ENV` that is unset (not empty: the `local` default) or itself
1039
+ * `local`, `ci` or `e2e`.
865
1040
  *
866
1041
  * The address is masked (PII, and the rest of this file already masks it); the URL is printed in
867
- * full because following it without a mail server is the whole point locally.
1042
+ * full because following it without a mail server is the whole point locally. `UserKey` tells a
1043
+ * test which line is its own when many runs sign up in parallel: the first 16 hex characters of
1044
+ * SHA-256 over the trimmed, lower-cased address, so a helper that knows its test address computes
1045
+ * the same key. It replaces reading the address from the token's JWT payload, which the sealed
1046
+ * verification token (DEV-4056) no longer allows. Format:
1047
+ * `[<LABEL>] User: <masked>, UserKey: <16 hex>, URL: <url>`.
868
1048
  *
869
1049
  * `console.log` rather than the NestJS logger, deliberately and for two reasons: the logger
870
1050
  * buffers, which makes interception unreliable under Vitest, and a logger call would route the
871
1051
  * token into `HubLogBufferService`'s ring buffer, which is readable over HTTP by any ADMIN.
872
1052
  */
873
1053
  protected logAuthUrlForDevelopment(label: string, email: string, url: string): void {
874
- const optIn = process.env.LT_LOG_AUTH_URLS;
875
- if (optIn === '0') {
1054
+ if (process.env.LT_LOG_AUTH_URLS === '0') {
876
1055
  return;
877
1056
  }
878
1057
  const env = this.configService?.getFastButReadOnly<string>('env') ?? process.env.NODE_ENV;
879
- if (isProductionLikeEnv(env)) {
1058
+ if (!isLocalEnv(env)) {
880
1059
  return;
881
1060
  }
882
- if (!isLocalEnv(env) && optIn !== '1') {
1061
+ // `!== undefined`, not truthiness: an empty NODE_ENV (`NODE_ENV=${NODE_ENV}` in a compose file on a host without
1062
+ // the variable) is read as `local` by getEnvironmentConfig(), and `isLocalEnv('')` is false
1063
+ const nodeEnv = process.env.NODE_ENV;
1064
+ if (nodeEnv !== undefined && !isLocalEnv(nodeEnv)) {
883
1065
  return;
884
1066
  }
1067
+ const userKey = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 16);
885
1068
  // oxlint-disable-next-line no-console
886
- console.log(`[${label}] User: ${this.maskEmail(email)}, URL: ${url}`);
1069
+ console.log(`[${label}] User: ${maskEmail(email)}, UserKey: ${userKey}, URL: ${url}`);
887
1070
  }
888
1071
 
889
1072
  protected getAppName(): string {
@@ -24,7 +24,14 @@ import type { IBetterAuth } from '../../common/interfaces/server-options.interfa
24
24
  * - session: custom response format with mapped user
25
25
  * - features: nest-server's own feature report
26
26
  */
27
- export const CONTROLLER_HANDLED_PATHS = ['/features', '/sign-in/email', '/sign-up/email', '/sign-out', '/session'];
27
+ export const CONTROLLER_HANDLED_PATHS = [
28
+ '/features',
29
+ '/sign-in/email',
30
+ '/sign-up/email',
31
+ '/sign-out',
32
+ '/session',
33
+ '/resend-verification-email',
34
+ ];
28
35
 
29
36
  /**
30
37
  * Routes Better-Auth guards with a session check in the HANDLER instead of a session middleware: the