@lenne.tech/nest-server 12.5.0 → 12.6.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.
Files changed (40) hide show
  1. package/.claude/rules/configurable-features.md +1 -1
  2. package/.claude/rules/testing.md +5 -4
  3. package/CLAUDE.md +4 -0
  4. package/FRAMEWORK-API.md +1 -1
  5. package/dist/core/common/services/rate-limit-store.d.ts +1 -0
  6. package/dist/core/common/services/rate-limit-store.js +3 -3
  7. package/dist/core/common/services/rate-limit-store.js.map +1 -1
  8. package/dist/core/modules/better-auth/core-better-auth-api.middleware.d.ts +1 -0
  9. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +23 -0
  10. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  11. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +31 -1
  12. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +96 -14
  13. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  14. package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js +8 -1
  15. package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js.map +1 -1
  16. package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.d.ts +3 -0
  17. package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js +29 -0
  18. package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js.map +1 -0
  19. package/dist/core/modules/better-auth/core-better-auth.controller.d.ts +8 -0
  20. package/dist/core/modules/better-auth/core-better-auth.controller.js +51 -0
  21. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  22. package/dist/core/modules/better-auth/core-better-auth.module.d.ts +1 -0
  23. package/dist/core/modules/better-auth/core-better-auth.module.js +10 -1
  24. package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
  25. package/dist/core/modules/system-setup/core-system-setup.service.d.ts +59 -2
  26. package/dist/core/modules/system-setup/core-system-setup.service.js +157 -28
  27. package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
  28. package/migration-guides/12.5.x-to-12.6.x.md +213 -0
  29. package/package.json +5 -4
  30. package/src/core/common/interfaces/server-options.interface.ts +6 -5
  31. package/src/core/common/services/rate-limit-store.ts +9 -3
  32. package/src/core/modules/better-auth/README.md +27 -0
  33. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +33 -0
  34. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +218 -35
  35. package/src/core/modules/better-auth/core-better-auth-openapi.helper.ts +8 -1
  36. package/src/core/modules/better-auth/core-better-auth-verification-link.helper.ts +53 -0
  37. package/src/core/modules/better-auth/core-better-auth.controller.ts +61 -0
  38. package/src/core/modules/better-auth/core-better-auth.module.ts +18 -2
  39. package/src/core/modules/system-setup/README.md +20 -4
  40. package/src/core/modules/system-setup/core-system-setup.service.ts +290 -45
@@ -11,6 +11,7 @@ import { runWithResetPassword } from './core-better-auth-password-reset.registry
11
11
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
12
12
  import { extractSessionToken, sendWebResponse, 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);
@@ -559,4 +564,32 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
559
564
  }
560
565
  }
561
566
  }
567
+
568
+ /**
569
+ * Replace the sealed token of a verification link (`GET /verify-email?token=…`) by the token Better-Auth signed, so
570
+ * Better-Auth verifies it unchanged (core-better-auth-verification-link.helper.ts). A plain token (a link mailed
571
+ * before the seal) and a value that does not open go on as they are: Better-Auth answers the latter like any
572
+ * invalid token.
573
+ */
574
+ protected async openVerificationLinkToken(req: Request, relativePath: string): Promise<void> {
575
+ if (relativePath !== '/verify-email') {
576
+ return;
577
+ }
578
+ const sealed = new URL(req.originalUrl || req.url, 'http://local').searchParams.get('token');
579
+ if (!sealed) {
580
+ return;
581
+ }
582
+ const secret = (await this.betterAuthService.getInstance()?.$context)?.secret;
583
+ const opened = secret ? await openVerificationToken(secret, sealed) : undefined;
584
+ if (!opened || opened === sealed) {
585
+ return;
586
+ }
587
+ const withToken = (url: string): string => {
588
+ const parsed = new URL(url, 'http://local');
589
+ parsed.searchParams.set('token', opened);
590
+ return `${parsed.pathname}${parsed.search}`;
591
+ };
592
+ req.originalUrl = withToken(req.originalUrl || req.url);
593
+ req.url = withToken(req.url);
594
+ }
562
595
  }
@@ -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
@@ -0,0 +1,53 @@
1
+ import { CompactEncrypt, compactDecrypt } from 'jose';
2
+ import { createHash } from 'node:crypto';
3
+
4
+ /**
5
+ * The verification link's token, sealed (DEV-4056).
6
+ *
7
+ * Better-Auth's email-verification token is a SIGNED JWT, not an encrypted one: its middle segment is base64url JSON
8
+ * with the address and the user id (`{ email, userId, iat, exp }`). Removing `&email=` from the link therefore removed
9
+ * nothing — anyone reading an access log, the browser history or a mail scanner's URL log decodes the address from the
10
+ * token itself. The link carries the token encrypted instead (compact JWE, `dir` + `A256GCM`, key derived from
11
+ * Better-Auth's secret), and the framework opens it where the token comes back: the API middleware before it forwards
12
+ * `GET /verify-email` to Better-Auth, and `POST /iam/resend-verification-email`. Better-Auth's own verification runs
13
+ * unchanged on the token it signed.
14
+ *
15
+ * A link mailed before the seal carries the plain token, which goes through as it is: {@link openVerificationToken}
16
+ * answers an unsealed value unchanged.
17
+ */
18
+
19
+ /** A sealed token is a compact JWE — five segments; Better-Auth's token is a JWS — three */
20
+ export function isSealedVerificationToken(value: unknown): value is string {
21
+ return typeof value === 'string' && value.split('.').length === 5;
22
+ }
23
+
24
+ /** The key of the seal: derived from Better-Auth's secret, so it rotates with it and needs no configuration */
25
+ function sealKey(secret: string): Uint8Array {
26
+ return new Uint8Array(createHash('sha256').update(`lt-email-verification-link:${secret}`).digest());
27
+ }
28
+
29
+ /** Encrypt a verification token for the link */
30
+ export async function sealVerificationToken(secret: string, token: string): Promise<string> {
31
+ return new CompactEncrypt(new TextEncoder().encode(token))
32
+ .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
33
+ .encrypt(sealKey(secret));
34
+ }
35
+
36
+ /**
37
+ * The token a link carried: decrypted when sealed, unchanged when not (a link mailed before the seal). `undefined`
38
+ * for a sealed value that does not open with this secret — forged, garbled, or sealed under a rotated secret.
39
+ */
40
+ export async function openVerificationToken(secret: string, value: string): Promise<string | undefined> {
41
+ if (!isSealedVerificationToken(value)) {
42
+ return value;
43
+ }
44
+ try {
45
+ const { plaintext } = await compactDecrypt(value, sealKey(secret), {
46
+ contentEncryptionAlgorithms: ['A256GCM'],
47
+ keyManagementAlgorithms: ['dir'],
48
+ });
49
+ return new TextDecoder().decode(plaintext);
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ }
@@ -146,6 +146,31 @@ export class CoreBetterAuthSignInInput {
146
146
  password: string;
147
147
  }
148
148
 
149
+ /**
150
+ * Input of `POST /iam/resend-verification-email`: the token of a verification link, an expired one included
151
+ */
152
+ export class CoreBetterAuthResendVerificationInput {
153
+ @ApiProperty({ description: 'The token of the verification link, also when it has expired' })
154
+ @IsNotEmpty()
155
+ @IsString()
156
+ token: string;
157
+ }
158
+
159
+ /**
160
+ * Answer of `POST /iam/resend-verification-email` — the same whatever happened, so it says nothing about the account
161
+ */
162
+ export class CoreBetterAuthResendVerificationResponse {
163
+ @ApiProperty({
164
+ description: 'The address the token belongs to, masked (k***@example.com); null for an invalid token',
165
+ nullable: true,
166
+ type: String,
167
+ })
168
+ email: null | string;
169
+
170
+ @ApiProperty({ description: 'Always true' })
171
+ success: boolean;
172
+ }
173
+
149
174
  /**
150
175
  * Sign-up input DTO
151
176
  */
@@ -321,6 +346,8 @@ export class CoreBetterAuthController {
321
346
  jwt: this.betterAuthService.isJwtEnabled(),
322
347
  passkey: this.betterAuthService.isPasskeyEnabled(),
323
348
  resendCooldownSeconds: this.emailVerificationService?.getConfig()?.resendCooldownSeconds ?? 60,
349
+ // POST /iam/resend-verification-email: a page may offer "send a new email" with the token of the link alone
350
+ resendVerificationByToken: this.emailVerificationService?.isEnabled() ?? false,
324
351
  signUpChecks: this.signUpValidator?.isEnabled() ?? false,
325
352
  signUpEnabled: this.betterAuthService.isSignUpEnabled(),
326
353
  socialProviders: this.betterAuthService.getEnabledSocialProviders(),
@@ -730,6 +757,40 @@ export class CoreBetterAuthController {
730
757
  *
731
758
  * @see README.md "Architecture: Why Custom Controllers?"
732
759
  */
760
+ /**
761
+ * Send a new verification mail for the token of a verification link — an expired one is the case this exists for.
762
+ * The address never travels: the server reads it from the token, and the answer carries it masked.
763
+ *
764
+ * Never verifies, signs in or creates a session. The answer is the same whether the account exists, is already
765
+ * verified, or a mail went out; see `CoreBetterAuthEmailVerificationService.resendVerificationByToken()` for the
766
+ * checks and the rate limits (429 `LTNS_0020`).
767
+ */
768
+ @ApiBody({ type: CoreBetterAuthResendVerificationInput })
769
+ @ApiOkResponse({
770
+ description: 'Always the same answer; email is the masked address of the token, or null for an invalid token',
771
+ type: CoreBetterAuthResendVerificationResponse,
772
+ })
773
+ @ApiOperation({
774
+ description: 'Send a new verification email for the token of a verification link, also an expired one',
775
+ summary: 'Resend Verification Email by Token',
776
+ })
777
+ @HttpCode(HttpStatus.OK)
778
+ @Post('resend-verification-email')
779
+ @Roles(RoleEnum.S_EVERYONE)
780
+ async resendVerificationEmail(
781
+ @Req() req: Request,
782
+ @Body() input: CoreBetterAuthResendVerificationInput,
783
+ ): Promise<CoreBetterAuthResendVerificationResponse> {
784
+ if (!this.emailVerificationService) {
785
+ return { email: null, success: true };
786
+ }
787
+ return this.emailVerificationService.resendVerificationByToken(
788
+ this.betterAuthService.getInstance(),
789
+ input?.token,
790
+ req.ip,
791
+ );
792
+ }
793
+
733
794
  @ApiOkResponse({ description: 'Signed out successfully', type: CoreBetterAuthResponse })
734
795
  @ApiOperation({ description: 'Sign out from Better-Auth', summary: 'Sign Out' })
735
796
  @Post('sign-out')
@@ -32,6 +32,7 @@ import {
32
32
  instantiateBetterAuth,
33
33
  OnPasswordResetCallback,
34
34
  } from './better-auth.config.js';
35
+ import { sealVerificationToken } from './core-better-auth-verification-link.helper.js';
35
36
  import { applyBetterAuthSchema } from './better-auth-sql.helper.js';
36
37
  import { getBetterAuthSqlStore, setBetterAuthSqlStore } from './core-better-auth-sql.registry.js';
37
38
  import { BetterAuthSqlStore } from './core-better-auth-sql.store.js';
@@ -926,6 +927,20 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
926
927
  }
927
928
  }
928
929
 
930
+ /**
931
+ * The verification mail's token and link with the token sealed (core-better-auth-verification-link.helper.ts). The
932
+ * API middleware opens it again for `GET /verify-email`, and `POST /iam/resend-verification-email` does too.
933
+ * Without an instance (cannot happen while Better-Auth sends) the mail goes out unsealed rather than not at all.
934
+ */
935
+ protected static async sealVerificationMail(options: AuthEmailCallbackOptions): Promise<AuthEmailCallbackOptions> {
936
+ const secret = (await this.authInstance?.$context)?.secret;
937
+ if (!secret || !options.token) {
938
+ return options;
939
+ }
940
+ const sealed = await sealVerificationToken(secret, options.token);
941
+ return { ...options, token: sealed, url: options.url?.split(options.token).join(sealed) };
942
+ }
943
+
929
944
  /**
930
945
  * `protected` rather than `private`: the callbacks it returns include `onPasswordReset`, which
931
946
  * decides what mirroring a reset into the legacy store means for a deployment. A project with a
@@ -1027,9 +1042,10 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
1027
1042
  }
1028
1043
  },
1029
1044
  sendVerificationEmail: async (options) => {
1030
- // Delegate to the NestJS service
1045
+ // Delegate to the NestJS service — with the token sealed, because Better-Auth's own token is a readable JWT
1046
+ // that carries the address, and the link goes into mails, browser histories and access logs (DEV-4056)
1031
1047
  if (this.emailVerificationService) {
1032
- await this.emailVerificationService.sendVerificationEmail(options);
1048
+ await this.emailVerificationService.sendVerificationEmail(await this.sealVerificationMail(options));
1033
1049
  } else {
1034
1050
  // Same reasoning as the password-reset branch above: the URL carries a token and this
1035
1051
  // logger feeds the ADMIN-readable Hub log buffer, so report the breakage instead.
@@ -259,7 +259,8 @@ NEST_SERVER_CONFIG='{ "systemSetup": { "initialAdmin": { "email": "admin@example
259
259
 
260
260
  ### Security Best Practices
261
261
 
262
- 1. **Remove credentials after first deployment** - Once the admin exists, the ENV vars are unused
262
+ 1. **Remove credentials after first deployment** - Once the admin exists, the ENV vars change nothing; the boot only
263
+ reads them to finish a setup that was killed halfway (see Security). Removing them closes that path too
263
264
  2. **Use secrets management** - Docker Secrets, Kubernetes Secrets, Vault, etc.
264
265
  3. **Never commit credentials** - Use `.env` files (gitignored) or external secret stores
265
266
  4. **Use strong passwords** - Minimum 8 characters, recommended 16+
@@ -277,10 +278,19 @@ NEST_SERVER_CONFIG='{ "systemSetup": { "initialAdmin": { "email": "admin@example
277
278
  3. **Rollback on failure (12.4.0)** - When a step after creating the user fails (account, sync, role),
278
279
  the user is removed again, so `needsSetup` stays `true` and the setup can be retried. Before,
279
280
  the deployment kept a user without the admin role and was locked for good
280
- 4. **Race condition protection** - MongoDB unique email index prevents duplicates; auto-creation on
281
+ 4. **A killed setup is finished at the next boot** - A process killed halfway (SIGKILL, OOM) runs no rollback.
282
+ The admin role is therefore written together with the user, so the worst a kill leaves is an administrator
283
+ without a login account. With `initialAdmin` configured, the next boot finishes the setup for that address: it
284
+ adds the credential account with the configured password and sets the role. It also finishes the leftover of an
285
+ older setup (no role, no administrator in the system, and no account or only a credential account with the
286
+ configured password). A user with another password, a social account, a second account or a legacy password (`users.password`, e.g. a
287
+ Legacy-Auth administrator who has not signed in through IAM yet) is never touched. A
288
+ restart within five minutes of the kill finds the old claim still held and tries once more after it goes stale.
289
+ The anonymous HTTP init finishes nothing: once users exist it refuses, as before
290
+ 5. **Race condition protection** - MongoDB unique email index prevents duplicates; auto-creation on
281
291
  bootstrap is additionally claimed atomically via the `system-setup-locks` marker
282
- 5. **Permanent lock** - Once any user exists, init returns 403
283
- 6. **BetterAuth required** - Returns 403 if BetterAuth is not enabled
292
+ 6. **Permanent lock** - Once any user exists, init returns 403
293
+ 7. **BetterAuth required** - Returns 403 if BetterAuth is not enabled
284
294
 
285
295
  ### How It Bypasses disableSignUp
286
296
 
@@ -345,6 +355,12 @@ the user stayed behind without the admin role. Since 12.4.0 such a user is remov
345
355
  the server log says the partially created user "could not be removed", delete that user and its `account` rows and
346
356
  retry.
347
357
 
358
+ **Cause (a killed setup):** the process was killed between creating the user and finishing it, so no rollback ran.
359
+ With `systemSetup.initialAdmin` set to that address and password, restart the instance: the boot finishes the setup
360
+ and logs `Finished an interrupted initial-admin setup`. A restart within five minutes of the kill logs that the
361
+ claim is still held and retries on its own once it has gone stale. Without `initialAdmin` (the setup ran through the
362
+ HTTP init), set it for one start, or delete the user and its `account` rows and run the init again.
363
+
348
364
  ### Init returns 403 "System setup not available"
349
365
 
350
366
  **Two different guards raise this, and the response cannot tell you which.**