@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
@@ -0,0 +1,157 @@
1
+ import { isJwtShaped } from './core-better-auth-token.helper.js';
2
+
3
+ /**
4
+ * How a response Better-Auth produced itself may carry the session token (see {@link presentSessionTokens}).
5
+ */
6
+ export interface SessionTokenPresentation {
7
+ /** Name of the session cookie Better-Auth sets (`<prefix>.session_token`, `__Secure-` prefixed with secure cookies) */
8
+ cookieName: string;
9
+ /**
10
+ * Whether a value is the token of a live session — asked only for a top-level `token` the response does not
11
+ * already identify as the session token (no session cookie set, no `session.token`). A signed-in user verifying a
12
+ * second factor gets the token of the session they already hold, with no cookie; without this check that token
13
+ * would pass as another plugin's value.
14
+ */
15
+ isSessionToken?: (token: string) => Promise<boolean>;
16
+ /**
17
+ * Turns an opaque session token into what the body should carry instead — a JWT when the JWT plugin is on
18
+ * (`CoreBetterAuthService.resolveJwtToken()`), the token itself when it is off, `undefined` when a conversion failed
19
+ */
20
+ resolveJwt: (sessionToken: string) => Promise<string | undefined>;
21
+ /**
22
+ * Whether the body may carry a token at all: cookies disabled (JWT-only mode) or `cookies.exposeTokenInBody`.
23
+ * `false` in the default cookie mode, where the session lives in an httpOnly cookie and nowhere else.
24
+ */
25
+ tokenInBody: boolean;
26
+ }
27
+
28
+ /**
29
+ * The session token a response sets in its session cookie, or `undefined` when it sets none.
30
+ *
31
+ * A Better-Auth endpoint that CREATES a session (two-factor verify, passkey verify, OTP and magic-link sign-in, …)
32
+ * sets this cookie; that is how the token in its body is recognised as the session token rather than some other
33
+ * value a plugin names `token`. The cookie value is signed (`<token>.<signature>`, URL-encoded).
34
+ */
35
+ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieName: string): string | undefined {
36
+ for (const header of response.headers.getSetCookie?.() ?? []) {
37
+ if (!header.startsWith(`${cookieName}=`)) {
38
+ continue;
39
+ }
40
+ const raw = header.split(';')[0].slice(cookieName.length + 1);
41
+ let value: string;
42
+ try {
43
+ value = decodeURIComponent(raw);
44
+ } catch {
45
+ value = raw;
46
+ }
47
+ const token = value.split('.')[0];
48
+ return token || undefined;
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ /**
54
+ * Applies the sign-in token policy to a response Better-Auth produced itself — every route the framework forwards
55
+ * to Better-Auth's handler instead of answering it in `CoreBetterAuthController` (two-factor verify-totp /
56
+ * verify-backup-code / verify-otp, passkey verify, OTP and magic-link sign-in, get-session, …).
57
+ *
58
+ * Better-Auth answers a session-creating route with `{ token: <session token>, user }`, and its session objects carry
59
+ * `session.token`. The framework's own sign-in never lets that reach a client: in the default cookie mode the token
60
+ * lives in an httpOnly cookie only, and where the body may carry a token it is a JWT (SEC-005). Forwarded routes
61
+ * bypassed both, so a frontend found the opaque 7-day session token in the body of the second factor and stored it
62
+ * where any script could read it.
63
+ *
64
+ * - Cookie mode: the session token leaves the body — top-level `token` and `session.token`.
65
+ * - Token in body: the session token becomes {@link SessionTokenPresentation.resolveJwt}'s answer; `session.token`
66
+ * leaves the body as in sign-in (`mapSession()`). A response that created a session without a top-level token
67
+ * (passkey verify answers `{ session }`) gains one.
68
+ * - Untouched: error responses, non-JSON bodies, arrays, a JWT (`/token` hands one out on purpose), and a top-level
69
+ * `token` that is not the session token (another plugin's value).
70
+ *
71
+ * Returns the response itself when nothing changes, otherwise a new one with the same status and headers.
72
+ */
73
+ export async function presentSessionTokens(
74
+ response: globalThis.Response,
75
+ options: SessionTokenPresentation,
76
+ ): Promise<globalThis.Response> {
77
+ if (!response.ok || !(response.headers.get('content-type') ?? '').includes('application/json')) {
78
+ return response;
79
+ }
80
+ let body: unknown;
81
+ try {
82
+ body = await response.clone().json();
83
+ } catch {
84
+ return response;
85
+ }
86
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
87
+ return response;
88
+ }
89
+
90
+ const record = body as Record<string, unknown>;
91
+ const session =
92
+ record.session && typeof record.session === 'object' && !Array.isArray(record.session)
93
+ ? (record.session as Record<string, unknown>)
94
+ : undefined;
95
+ const sessionFieldToken = typeof session?.token === 'string' && session.token ? session.token : undefined;
96
+ const cookieToken = sessionTokenFromSetCookie(response, options.cookieName);
97
+ const topToken = typeof record.token === 'string' && record.token ? record.token : undefined;
98
+ const topIsSessionToken =
99
+ !!topToken &&
100
+ !isJwtShaped(topToken) &&
101
+ (topToken === cookieToken ||
102
+ topToken === sessionFieldToken ||
103
+ (await isLiveSessionToken(topToken, options.isSessionToken)));
104
+
105
+ if (!topIsSessionToken && !sessionFieldToken) {
106
+ return response;
107
+ }
108
+
109
+ const next: Record<string, unknown> = { ...record };
110
+ if (session && sessionFieldToken) {
111
+ const { token: _sessionToken, ...rest } = session;
112
+ next.session = rest;
113
+ }
114
+
115
+ if (!options.tokenInBody) {
116
+ if (topIsSessionToken) {
117
+ delete next.token;
118
+ }
119
+ } else {
120
+ // The session token the body should present: the top-level one, else the one this response just set
121
+ const source = topIsSessionToken ? topToken : !topToken ? cookieToken : undefined;
122
+ if (source) {
123
+ const presented = await options.resolveJwt(source);
124
+ if (presented) {
125
+ next.token = presented;
126
+ } else {
127
+ delete next.token;
128
+ }
129
+ }
130
+ }
131
+
132
+ const headers = new Headers();
133
+ response.headers.forEach((value, key) => {
134
+ if (key.toLowerCase() !== 'content-length' && key.toLowerCase() !== 'set-cookie') {
135
+ headers.set(key, value);
136
+ }
137
+ });
138
+ for (const cookie of response.headers.getSetCookie?.() ?? []) {
139
+ headers.append('set-cookie', cookie);
140
+ }
141
+ return new Response(JSON.stringify(next), { headers, status: response.status, statusText: response.statusText });
142
+ }
143
+
144
+ /** Asks {@link SessionTokenPresentation.isSessionToken}; a lookup that fails cannot vouch for anything */
145
+ async function isLiveSessionToken(
146
+ token: string,
147
+ isSessionToken: SessionTokenPresentation['isSessionToken'],
148
+ ): Promise<boolean> {
149
+ if (!isSessionToken) {
150
+ return false;
151
+ }
152
+ try {
153
+ return (await isSessionToken(token)) === true;
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
@@ -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
+ }
@@ -47,7 +47,7 @@ import { CoreBetterAuthEmailVerificationService } from './core-better-auth-email
47
47
  import { CoreBetterAuthSignUpValidatorService } from './core-better-auth-signup-validator.service.js';
48
48
  import { isJwtShaped, isSessionToken } from './core-better-auth-token.helper.js';
49
49
  import { BetterAuthSessionUser, CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
50
- import { convertExpressHeaders, sendWebResponse, toWebRequest } from './core-better-auth-web.helper.js';
50
+ import { convertExpressHeaders, toWebRequest } from './core-better-auth-web.helper.js';
51
51
  import { CoreBetterAuthService } from './core-better-auth.service.js';
52
52
  import { registerBetterAuthHandlerClass } from './core-better-auth.registry.js';
53
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')
@@ -1093,7 +1154,8 @@ export class CoreBetterAuthController {
1093
1154
  this.logger.debug(`Better Auth handler response status: ${response.status}`);
1094
1155
 
1095
1156
  // Send the response back
1096
- await sendWebResponse(res, response);
1157
+ // Through the token policy: a forwarded route must not hand out what sign-in would not (12.6.1)
1158
+ await this.betterAuthService.sendBetterAuthResponse(res, response);
1097
1159
  } catch (error) {
1098
1160
  this.logger.error(`Better Auth handler error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1099
1161
 
@@ -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.
@@ -16,10 +16,15 @@ import {
16
16
  sessionMiddleware,
17
17
  } from 'better-auth/api';
18
18
  import { Request } from 'express';
19
+ import type { Response as ExpressResponse } from 'express';
19
20
  import { importJWK, jwtVerify } from 'jose';
20
21
  import type { Connection } from 'mongoose';
21
22
 
22
- import { shouldConvertSessionTokenToJwt } from '../../common/helpers/cookies.helper.js';
23
+ import {
24
+ isCookiesEnabled,
25
+ isExposeTokenInBodyEnabled,
26
+ shouldConvertSessionTokenToJwt,
27
+ } from '../../common/helpers/cookies.helper.js';
23
28
  import { type ExpirySweep, scheduleExpirySweep } from '../../common/persistence/expiry-sweep.js';
24
29
  import { maskEmail, maskToken } from '../../common/helpers/logging.helper.js';
25
30
  import { type IBetterAuth, ICookiesConfig } from '../../common/interfaces/server-options.interface.js';
@@ -38,7 +43,13 @@ import {
38
43
  import type { IBetterAuthOpenApiDocument, IBetterAuthRuntime } from './core-better-auth-openapi.helper.js';
39
44
  import { isJwtShaped } from './core-better-auth-token.helper.js';
40
45
  import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
41
- import { convertExpressHeaders, parseCookieHeader, signCookieValueIfNeeded } from './core-better-auth-web.helper.js';
46
+ import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
47
+ import {
48
+ convertExpressHeaders,
49
+ parseCookieHeader,
50
+ sendWebResponse,
51
+ signCookieValueIfNeeded,
52
+ } from './core-better-auth-web.helper.js';
42
53
  import {
43
54
  ACCOUNT_ISSUER_BACKFILL_ID,
44
55
  BACKFILL_MARKER_COLLECTION,
@@ -804,6 +815,53 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
804
815
  return `${this.getCookiePrefix()}.session_token`;
805
816
  }
806
817
 
818
+ /**
819
+ * Applies the sign-in token policy to a response Better-Auth's own handler produced (12.6.1).
820
+ *
821
+ * Routes the framework forwards to Better-Auth — two-factor verify, passkey verify, OTP and magic-link sign-in,
822
+ * get-session — answered with the opaque session token in the body, also in the default cookie mode, where the
823
+ * framework's own sign-in keeps it in an httpOnly cookie only, and as the raw token where sign-in hands out a JWT.
824
+ * See `presentSessionTokens()` (`core-better-auth-session-token.helper.ts`) for the rules.
825
+ *
826
+ * Override to present tokens differently; keep the cookie-mode rule, it is what keeps the session out of scripts.
827
+ */
828
+ async presentSessionTokens(response: globalThis.Response): Promise<globalThis.Response> {
829
+ const cookiesConfig = ConfigService.configFastButReadOnly?.cookies as boolean | ICookiesConfig | undefined;
830
+ return presentSessionTokens(response, {
831
+ cookieName: await this.sessionCookieNameOfInstance(),
832
+ isSessionToken: async (token) => !!(await this.getSessionByToken(token))?.session,
833
+ resolveJwt: (sessionToken) => this.resolveJwtToken(sessionToken),
834
+ tokenInBody: !isCookiesEnabled(cookiesConfig) || isExposeTokenInBodyEnabled(cookiesConfig),
835
+ });
836
+ }
837
+
838
+ /**
839
+ * The session cookie's name as the running Better-Auth instance sets it — `__Secure-` prefixed under
840
+ * `advanced.useSecureCookies`, renamed under `advanced.cookies.session_token.name` — falling back to
841
+ * {@link getSessionCookieName} when the instance cannot say.
842
+ */
843
+ protected async sessionCookieNameOfInstance(): Promise<string> {
844
+ try {
845
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
846
+ const name = context?.authCookies?.sessionToken?.name;
847
+ if (typeof name === 'string' && name) {
848
+ return name;
849
+ }
850
+ } catch {
851
+ // The configured name below is what the framework writes itself
852
+ }
853
+ return this.getSessionCookieName();
854
+ }
855
+
856
+ /**
857
+ * Sends a response of Better-Auth's handler to the client, through {@link presentSessionTokens}. Every place that
858
+ * forwards to the handler (the API middleware, the controller's catch-all) sends through here, so a forwarded route
859
+ * cannot hand a client a token the framework's own sign-in would not.
860
+ */
861
+ async sendBetterAuthResponse(res: ExpressResponse, response: globalThis.Response): Promise<void> {
862
+ await sendWebResponse(res, await this.presentSessionTokens(response));
863
+ }
864
+
807
865
  /**
808
866
  * Gets the cookie prefix (the `iam` in `iam.session_token`).
809
867
  *
@@ -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.**