@lenne.tech/nest-server 12.8.1 → 12.8.3

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 (39) hide show
  1. package/.claude/rules/architecture.md +14 -4
  2. package/.claude/rules/better-auth.md +10 -0
  3. package/.claude/rules/configurable-features.md +2 -1
  4. package/.claude/rules/testing.md +3 -3
  5. package/FRAMEWORK-API.md +2 -1
  6. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  7. package/dist/core/modules/better-auth/better-auth.config.js +31 -5
  8. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  9. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +2 -1
  10. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +12 -1
  11. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  12. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.d.ts +2 -0
  13. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +12 -0
  14. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
  15. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +2 -0
  16. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +23 -1
  17. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
  18. package/dist/core/modules/migrate/helpers/ts-compiler-hooks.mjs +4 -55
  19. package/dist/core/modules/migrate/helpers/ts-compiler-hooks.mjs.map +1 -1
  20. package/dist/core/modules/migrate/helpers/ts-compiler.cjs +100 -5
  21. package/dist/core/modules/migrate/helpers/ts-compiler.cjs.map +1 -1
  22. package/dist/core/modules/migrate/helpers/ts-compiler.d.cts +12 -1
  23. package/dist/core/modules/user/core-user.service.js +5 -1
  24. package/dist/core/modules/user/core-user.service.js.map +1 -1
  25. package/migration-guides/11.41.7-to-11.41.8.md +1 -1
  26. package/migration-guides/12.2.x-to-12.3.x.md +2 -2
  27. package/migration-guides/12.8.1-to-12.8.2.md +125 -0
  28. package/migration-guides/12.8.2-to-12.8.3.md +111 -0
  29. package/package.json +1 -1
  30. package/src/core/common/interfaces/server-options.interface.ts +23 -1
  31. package/src/core/modules/better-auth/README.md +6 -3
  32. package/src/core/modules/better-auth/better-auth.config.ts +63 -5
  33. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +36 -4
  34. package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +23 -0
  35. package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +44 -3
  36. package/src/core/modules/migrate/README.md +5 -3
  37. package/src/core/modules/migrate/helpers/ts-compiler-hooks.mjs +14 -65
  38. package/src/core/modules/migrate/helpers/ts-compiler.cjs +157 -12
  39. package/src/core/modules/user/core-user.service.ts +10 -2
@@ -0,0 +1,111 @@
1
+ # Migration Guide: 12.8.2 → 12.8.3
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | `betterAuth.emailVerification.appName`: the application name in the verification and password-reset mails, independent of `package.json` (§2) |
9
+ | **Bugfixes** | Under Node 26 every start and every migration run from source printed `[DEP0205] DeprecationWarning: module.register() is deprecated`. The TypeScript loader now registers its import hooks with `module.registerHooks()` where Node supports it (§1) |
10
+ | **Migration Effort** | None. Optional: set `appName` when the mails should not carry the `package.json` name (§2) |
11
+
12
+ 12.8.3 is a patch for 12.8.2. Nothing has to change in a project.
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@12.8.3
18
+ pnpm run update # nest-server-starter based projects
19
+ pnpm run build
20
+ pnpm test
21
+ ```
22
+
23
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
24
+
25
+ ## 1. The TypeScript loader without `module.register()` on Node 26
26
+
27
+ **Why:** the framework's TypeScript loader (`migrate/helpers/ts-compiler.js`) runs the dev server from source
28
+ (`node -r …/ts-compiler.js src/main.ts`), the migrate CLI (`--compiler ts:…/ts-compiler.js`) and `config.env.ts`. For
29
+ `import`ed TypeScript (an ESM project, a `.mts` file) it registered Node module hooks through `module.register()`.
30
+ Node 26 deprecates that function at runtime, so every one of those runs printed DEP0205, in npm and vendor projects
31
+ alike.
32
+
33
+ **What changed:** the loader picks the hook API per Node line:
34
+
35
+ | Node | API | Why |
36
+ |---|---|---|
37
+ | 24.12+ and 26+ | `module.registerHooks()`, in-thread | hands a CommonJS module imported from ESM back to the CommonJS loader, as the loader needs |
38
+ | 22.x, 24.0–24.11, 25.x | `module.register()` with `ts-compiler-hooks.mjs`, as before | these lines refuse that hand-back in synchronous hooks; none of them deprecates `module.register()` |
39
+
40
+ Both paths share one implementation in `ts-compiler.cjs`. The behaviour is the same on every line: decorators with
41
+ metadata, `./x.js` specifiers resolving to `x.ts`, JSON imports with attributes, CommonJS-scoped `.ts` / `.cts` files
42
+ compiled by the `require` hook with a real `require` (`require.cache`, `require.extensions`). The CommonJS path
43
+ (`require()` of a `.ts` file, every migration) is unchanged.
44
+
45
+ `engines.node` stays `>= 22.15`. Nothing to do: the loader path, its function export and `--compiler ts:…` are the same.
46
+
47
+ ## 2. `betterAuth.emailVerification.appName`
48
+
49
+ **Why:** the verification and password-reset mails name the application in the subject
50
+ (`<appName> - Verify your email address`), in the EJS templates (`appName`) and in the Brevo parameters (`appName`).
51
+ That name came from the `name` of the `package.json` in the working directory, formatted (`my-app` → `My App`). In a
52
+ monorepo the working directory is the API package: one named `api` sent `Api - Verify your email address`. Changing it
53
+ needed an override of `getAppName()`.
54
+
55
+ **What changed:** an optional setting:
56
+
57
+ ```typescript
58
+ // config.env.ts
59
+ betterAuth: {
60
+ emailVerification: {
61
+ appName: 'Kundenportal',
62
+ },
63
+ },
64
+ ```
65
+
66
+ or `NSC__BETTER_AUTH__EMAIL_VERIFICATION__APP_NAME=Kundenportal`. The value is trimmed. Unset or empty, the mails keep
67
+ the `package.json` name. A value that is not a string is ignored with one warning. An override of `getAppName()` or
68
+ `resolveAppName()` still wins.
69
+
70
+ **A project with email verification switched off** (`emailVerification: false`) still sends password-reset mails, so
71
+ the name matters there too. Write it with `enabled: false`:
72
+
73
+ ```typescript
74
+ betterAuth: {
75
+ emailVerification: { enabled: false, appName: 'Kundenportal' },
76
+ },
77
+ ```
78
+
79
+ With environment variables, set `NSC__BETTER_AUTH__EMAIL_VERIFICATION__ENABLED=false` next to
80
+ `NSC__BETTER_AUTH__EMAIL_VERIFICATION__APP_NAME`. `false` keeps no settings, so `appName` would be ignored; an object
81
+ without `enabled: false` (which is what the variable alone turns `false` into) switches verification ON, and every
82
+ sign-in of a user whose address was never verified is then answered with 401 `EMAIL_VERIFICATION_REQUIRED`.
83
+
84
+ Authenticator apps and passkey prompts are not affected: they read `betterAuth.twoFactor.appName` and
85
+ `betterAuth.passkey.rpName`, as before.
86
+
87
+ ## Compatibility Notes
88
+
89
+ | Pattern | Status |
90
+ |---|---|
91
+ | `node -r …/ts-compiler.js src/main.ts`, `migrate … --compiler ts:…` | unchanged, without DEP0205 on Node 26 |
92
+ | A project calling `require('…/ts-compiler.js')()` itself | unchanged (idempotent function export) |
93
+ | A subclass overriding `getAppName()` / `resolveAppName()` | unchanged, still wins over the setting |
94
+ | Own email templates using `appName` | receive the configured name when it is set |
95
+
96
+ ## Troubleshooting
97
+
98
+ | Symptom | Cause | Fix |
99
+ |---|---|---|
100
+ | `[DEP0205] DeprecationWarning: module.register() is deprecated` after the update | a second loader in the project (`tsx`, `ts-node/esm`, a `--loader` / `--import` flag) still calls `module.register()` | remove or update that loader; the framework's own no longer calls it on Node 26 |
101
+ | The mail subject still shows the package name | `appName` is set at the wrong level, or empty, or `emailVerification` is `false` (keeps no settings) | it belongs under `betterAuth.emailVerification`; with verification off write `{ enabled: false, appName }`; check the boot log for the "must be a string" warning |
102
+ | After setting `appName`, unverified users get 401 `EMAIL_VERIFICATION_REQUIRED` at sign-in | the project had `emailVerification: false`; the object (or `NSC__…__APP_NAME` alone) switched verification on | add `enabled: false` (`NSC__BETTER_AUTH__EMAIL_VERIFICATION__ENABLED=false`) |
103
+
104
+ ## References
105
+
106
+ - `src/core/modules/migrate/helpers/ts-compiler.cjs`: `registerEsmHooks()`, `registerHooksHandsBackCommonJs()`,
107
+ `loadTypeScript()`
108
+ - `src/core/modules/migrate/README.md`: the TypeScript loader
109
+ - `src/core/modules/better-auth/core-better-auth-email-verification.service.ts`: `resolveAppName()`
110
+ - `src/core/modules/better-auth/README.md`: email verification
111
+ - `tests/unit/ts-compiler.spec.ts`, `tests/unit/better-auth-mail-app-name.spec.ts`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.8.1",
3
+ "version": "12.8.3",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -509,6 +509,27 @@ export type IBetterAuth = IBetterAuthWithoutPasskey | IBetterAuthWithPasskey;
509
509
  * ```
510
510
  */
511
511
  export interface IBetterAuthEmailVerificationConfig {
512
+ /**
513
+ * The application name in the verification and password-reset mails: the subject (`<appName> - Verify your email
514
+ * address`), the `appName` variable of the EJS templates and the `appName` parameter of the Brevo templates.
515
+ *
516
+ * Unset (or empty), the name comes from the `name` of the `package.json` in the working directory, formatted
517
+ * (`my-app` → `My App`), as before 12.8.3 — in a monorepo that is the API package (`api`). A value that is not a
518
+ * string is ignored with a warning. `twoFactor.appName` and `passkey.rpName` name the application in authenticator
519
+ * apps and passkey prompts; they are separate settings.
520
+ *
521
+ * With email verification switched off, write `emailVerification: { enabled: false, appName }`
522
+ * (`NSC__BETTER_AUTH__EMAIL_VERIFICATION__ENABLED=false` next to the variable): `false` keeps no settings, and an
523
+ * object without `enabled: false` switches verification on — every sign-in of an unverified user then answers 401.
524
+ *
525
+ * **Environment Variable:** `NSC__BETTER_AUTH__EMAIL_VERIFICATION__APP_NAME`
526
+ *
527
+ * @default undefined (the formatted package.json name, 'Nest Server' without one)
528
+ * @example 'Kundenportal'
529
+ * @since 12.8.3
530
+ */
531
+ appName?: string;
532
+
512
533
  /**
513
534
  * Whether `GET /iam/verify-email` signs in the browser that opens the verification link.
514
535
  *
@@ -4608,7 +4629,8 @@ interface IBetterAuthBase {
4608
4629
  * Since 12.3.0 it closes social sign-up too: every configured social provider receives it as its own
4609
4630
  * `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
4610
4631
  * signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
4611
- * registers itself through `options.plugins` are not covered.
4632
+ * registers itself through `plugins` are not covered; they need their own sign-up option
4633
+ * (`magicLink({ disableSignUp: true })`).
4612
4634
  * The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
4613
4635
  * which would answer `SIGNUP_DISABLED` to every caller.
4614
4636
  * @default false
@@ -539,6 +539,7 @@ const config = {
539
539
  template: 'custom-verify', // Custom template name
540
540
  locale: 'en', // Template locale (default: 'de')
541
541
  brevoTemplateId: 42, // Send via Brevo transactional API (optional)
542
+ appName: 'Kundenportal', // Name in the mails (12.8.3+; default: the formatted package.json name)
542
543
  },
543
544
  // To disable:
544
545
  emailVerification: false,
@@ -548,6 +549,8 @@ const config = {
548
549
 
549
550
  **Custom Templates:** Create `templates/email-verification-{locale}.ejs` in your project. Available variables: `name`, `link`, `expiresIn`, `appName`.
550
551
 
552
+ **Application name:** `appName` in the verification and password-reset mails (subject, EJS variable, Brevo parameter) is `emailVerification.appName` when set (12.8.3+, `NSC__BETTER_AUTH__EMAIL_VERIFICATION__APP_NAME`), otherwise the `name` of the `package.json` in the working directory, formatted (`my-app` → `My App`). In a monorepo that is the API package, so set it there. Authenticator apps and passkey prompts read `twoFactor.appName` and `passkey.rpName`. With email verification switched off, write `emailVerification: { enabled: false, appName: '…' }` (`NSC__BETTER_AUTH__EMAIL_VERIFICATION__ENABLED=false` next to the variable): `false` keeps no settings, and an object without `enabled: false` switches verification on, which answers every sign-in of an unverified user with 401.
553
+
551
554
  **Brevo Integration:** When `brevoTemplateId` is set and Brevo is configured (`config.brevo`), verification emails are sent via Brevo's transactional API instead of SMTP/EJS templates. The same template variables (`name`, `link`, `appName`, `expiresIn`) are passed to the Brevo template.
552
555
 
553
556
  **Auto sign-in after verification (`autoSignInAfterVerification`, default `false` since 12.3.0):** with it on,
@@ -677,8 +680,8 @@ socialProviders: {
677
680
  ```
678
681
 
679
682
  Only a boolean counts on the provider; any other value follows `emailAndPassword.disableSignUp`, so a string from
680
- `NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds itself through `betterAuth.options.plugins`
681
- (Generic OAuth, Magic Link, …) are not covered and need their own sign-up options. Before 12.3.0 every provider created
683
+ `NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds itself through `betterAuth.plugins`
684
+ (Generic OAuth, Magic Link, …) are not covered and need their own sign-up options (`magicLink({ disableSignUp: true })`). Before 12.3.0 every provider created
682
685
  accounts whatever `disableSignUp` said.
683
686
 
684
687
  **Default:** `false` (sign-up enabled) - fully backward compatible.
@@ -1988,7 +1991,7 @@ src/assets/templates/password-reset-de.ejs # or -en, or plain password-reset.e
1988
1991
  | --------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1989
1992
  | `name` | yes | `user.name`, falling back to the local part of the address |
1990
1993
  | `link` | yes | the ready-made reset URL |
1991
- | `appName` | yes | derived from `package.json` `name` |
1994
+ | `appName` | yes | `emailVerification.appName`, else derived from `package.json` `name` |
1992
1995
  | `logoSrc` | **no** | optional. The shipped templates render an `<img>` when it is present and the app name as text otherwise. Nothing in the framework supplies it — pass it from a subclass that overrides `sendPasswordResetEmail()`, or reference it from your own template. |
1993
1996
 
1994
1997
  > **Keep the un-suffixed `password-reset.ejs` renderable from `{ link, name }` alone.**
@@ -7,7 +7,7 @@ import * as fs from 'fs';
7
7
  import * as path from 'path';
8
8
  import { inspect } from 'util';
9
9
 
10
- import { resolveServerUrls, strippedApiHostname } from '../../common/helpers/cookies.helper.js';
10
+ import { isLocalEnv, resolveServerUrls, strippedApiHostname } from '../../common/helpers/cookies.helper.js';
11
11
  import { revalidateWsConnectionsOf } from '../../common/helpers/graphql-ws-connection.helper.js';
12
12
  import { IBetterAuth, ICorsConfig } from '../../common/interfaces/server-options.interface.js';
13
13
  import { ConfigService } from '../../common/services/config.service.js';
@@ -647,6 +647,15 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
647
647
  // `Secure` TRANSPORT flag. Only injected on https so http/local and a consumer's
648
648
  // own `options.advanced.useSecureCookies` override are left untouched.
649
649
  ...(secureCookies && { defaultCookieAttributes: { secure: true } }),
650
+ // Better-Auth decides the origin check itself when this is unset: `isTest()` — `NODE_ENV === 'test'` or a
651
+ // truthy `TEST` variable — switches it off, and with it the CSRF check (backward compatibility in
652
+ // origin-check.mjs) and the validation of `callbackURL` / `redirectTo` against `trustedOrigins`. A deployed
653
+ // stage named `test` is exactly that environment, so a password-reset mail carried any `redirectTo` a caller
654
+ // chose — with a valid token, to the caller's page. Pinned for every environment that is not local / ci / e2e
655
+ // (an unknown or missing name included). Those three keep Better-Auth's own decision: vitest sets `TEST=true`,
656
+ // and pinning there would arm the check in every e2e suite of every project at once. A project's own
657
+ // `options.advanced.disableOriginCheck` still wins (see the merge below).
658
+ ...(!isLocalEnv(serverEnv) && { disableOriginCheck: false }),
650
659
  },
651
660
  basePath,
652
661
  baseURL: betterAuthBaseUrl,
@@ -762,10 +771,39 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
762
771
  const {
763
772
  advanced: optionsAdvanced,
764
773
  emailAndPassword: optionsEmailAndPassword,
774
+ user: optionsUser,
765
775
  ...restOptions
766
776
  } = config.options as Record<string, unknown>;
767
777
  finalConfig = { ...betterAuthConfig, ...restOptions };
768
778
 
779
+ // `user` is merged, not replaced. A project that sets `options.user` for its own reason (`changeEmail`,
780
+ // `deleteUser`) would otherwise drop `modelName: 'users'` — Better-Auth then reads and writes a `user` collection
781
+ // or table the framework never sees — and every field `additionalUserFields` declares, the `input: false` locks
782
+ // included. The framework's fields win over a project field of the same name; `betterAuth.additionalUserFields` is
783
+ // where a project changes them.
784
+ if (optionsUser && typeof optionsUser === 'object') {
785
+ const baseUser = betterAuthConfig.user as Record<string, unknown>;
786
+ const overrideUser = optionsUser as Record<string, unknown>;
787
+ // Copies, because the lock below writes to them and the project's options may be the frozen configuration
788
+ const projectFields = Object.fromEntries(
789
+ Object.entries((overrideUser.additionalFields as Record<string, unknown> | undefined) ?? {}).map(
790
+ ([key, field]) => [key, field && typeof field === 'object' ? { ...field } : field],
791
+ ),
792
+ );
793
+ const mergedFields = {
794
+ ...projectFields,
795
+ ...(baseUser.additionalFields as Record<string, unknown>),
796
+ };
797
+ // A project field under another key may still map to a protected column (`fieldName: 'roles'`)
798
+ lockProtectedColumns(mergedFields as Record<string, { fieldName?: string; input?: boolean }>);
799
+ finalConfig.user = {
800
+ ...baseUser,
801
+ ...overrideUser,
802
+ additionalFields: mergedFields,
803
+ modelName: overrideUser.modelName ?? baseUser.modelName,
804
+ };
805
+ }
806
+
769
807
  // `logger` is merged, not replaced: a project that only sets `level` or `disabled` keeps the Nest routing,
770
808
  // one that passes its own `log` handler gets exactly that.
771
809
  if (restOptions.logger && typeof restOptions.logger === 'object') {
@@ -839,6 +877,11 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
839
877
  | undefined),
840
878
  },
841
879
  }),
880
+ // An explicitly `undefined` value survives the spread as a present key and hands the decision back to
881
+ // Better-Auth's `isTest()`. Only a value the project actually set overrides the pin.
882
+ disableOriginCheck:
883
+ (optionsAdvanced as Record<string, unknown>).disableOriginCheck ??
884
+ (betterAuthConfig.advanced as Record<string, unknown>).disableOriginCheck,
842
885
  };
843
886
  }
844
887
  } else {
@@ -1400,14 +1443,29 @@ function buildUserFields(config: IBetterAuth): Record<string, UserFieldConfig> {
1400
1443
  // it, e.g. `additionalUserFields: { customRoles: { fieldName: 'roles', input: true } }`. Lock any
1401
1444
  // such field too, so no additionalUserFields entry — regardless of its key — can feed client input
1402
1445
  // into a protected column.
1446
+ lockProtectedColumns(coreFields);
1447
+
1448
+ return coreFields;
1449
+ }
1450
+
1451
+ /**
1452
+ * Sets `input: false` on every field that feeds a protected column under another key
1453
+ * (`customRoles: { fieldName: 'roles' }`). Used for `additionalUserFields` and for the fields a project passes through
1454
+ * `options.user.additionalFields`, which the `user` merge in createBetterAuthInstance() adds beside the framework's.
1455
+ */
1456
+ function lockProtectedColumns(fields: Record<string, { fieldName?: string; input?: boolean }>): void {
1403
1457
  const protectedColumns = new Set<string>(PROTECTED_INPUT_FALSE_KEYS);
1404
- for (const [key, field] of Object.entries(coreFields)) {
1405
- if (!protectedColumns.has(key) && field.fieldName && protectedColumns.has(field.fieldName)) {
1458
+ for (const [key, field] of Object.entries(fields)) {
1459
+ if (
1460
+ field &&
1461
+ typeof field === 'object' &&
1462
+ !protectedColumns.has(key) &&
1463
+ field.fieldName &&
1464
+ protectedColumns.has(field.fieldName)
1465
+ ) {
1406
1466
  field.input = false;
1407
1467
  }
1408
1468
  }
1409
-
1410
- return coreFields;
1411
1469
  }
1412
1470
 
1413
1471
  /**
@@ -32,12 +32,17 @@ import { callerDirectory } from '../../common/helpers/module-location.helper.js'
32
32
  */
33
33
  type ResolvedEmailVerificationConfig = Pick<
34
34
  IBetterAuthEmailVerificationConfig,
35
- 'brevoTemplateId' | 'callbackURL' | 'passwordResetBrevoTemplateId' | 'passwordResetLink'
35
+ 'appName' | 'brevoTemplateId' | 'callbackURL' | 'passwordResetBrevoTemplateId' | 'passwordResetLink'
36
36
  > &
37
37
  Required<
38
38
  Omit<
39
39
  IBetterAuthEmailVerificationConfig,
40
- 'brevoTemplateId' | 'callbackURL' | 'passwordResetBrevoTemplateId' | 'passwordResetLink' | 'resendCooldownSeconds'
40
+ | 'appName'
41
+ | 'brevoTemplateId'
42
+ | 'callbackURL'
43
+ | 'passwordResetBrevoTemplateId'
44
+ | 'passwordResetLink'
45
+ | 'resendCooldownSeconds'
41
46
  >
42
47
  > & {
43
48
  resendCooldownSeconds: number;
@@ -634,6 +639,16 @@ export class CoreBetterAuthEmailVerificationService {
634
639
  return Math.max(1, Math.round(resolved / 60));
635
640
  }
636
641
 
642
+ /**
643
+ * Whether the project switched Better-Auth's origin check off (`betterAuth.options.advanced.disableOriginCheck`):
644
+ * `true`, or a list of paths, which may name the reset route. The framework itself pins `false` (12.8.2), so only a
645
+ * project's own value counts here.
646
+ */
647
+ protected isOriginCheckDisabled(): boolean {
648
+ const raw = this.configService.getFastButReadOnly<unknown>('betterAuth.options.advanced.disableOriginCheck');
649
+ return raw === true || Array.isArray(raw);
650
+ }
651
+
637
652
  protected buildPasswordResetUrl(options: SendPasswordResetEmailOptions): string {
638
653
  const configured = this.config.passwordResetLink;
639
654
 
@@ -648,7 +663,9 @@ export class CoreBetterAuthEmailVerificationService {
648
663
  // `nuxt-base-starter` sends it on every request (`forgot-password.vue` →
649
664
  // `requestPasswordReset({ email, redirectTo: appUrl('/auth/reset-password', siteUrl) })`), and
650
665
  // a client that names its page is a better authority on that page than a framework default.
651
- if (!target) {
666
+ // Only while Better-Auth's origin check validated it (see readCallbackUrlFromBetterAuthLink): a project that
667
+ // switched the check off gets the default page, never an unvalidated URL with a valid token in it.
668
+ if (!target && !this.isOriginCheckDisabled()) {
652
669
  target = this.readCallbackUrlFromBetterAuthLink(options.url);
653
670
  // Only an absolute http(s) URL or a root-relative path names a page. Anything else — a path without
654
671
  // its leading slash (`redirectTo: 'reset'`), or a template literal over an unset variable
@@ -711,6 +728,11 @@ export class CoreBetterAuthEmailVerificationService {
711
728
  * knowing before anyone widens it. `cors.allowAll` does not widen it (an origin check has no
712
729
  * "allow everything" mode), but an over-broad `allowedOrigins` would.
713
730
  *
731
+ * And it makes the origin check itself load-bearing. Until 12.8.2 Better-Auth switched it off on its
732
+ * own under `NODE_ENV=test` (`isTest()`), which is a deployed stage in starter-based projects; the
733
+ * framework now pins `advanced.disableOriginCheck: false`. A project that switches it off itself
734
+ * gets no caller URL here at all ({@link isOriginCheckDisabled}).
735
+ *
714
736
  * Returns `undefined` for anything unparseable or absent, so the caller falls through to its own
715
737
  * resolution rather than to a half-formed URL.
716
738
  */
@@ -1158,9 +1180,19 @@ export class CoreBetterAuthEmailVerificationService {
1158
1180
  }
1159
1181
 
1160
1182
  /**
1161
- * Resolve the application name from package.json, falling back to a framework default.
1183
+ * Resolve the application name: `betterAuth.emailVerification.appName` when set (12.8.3), otherwise the formatted
1184
+ * `name` of the working directory's package.json, otherwise a framework default.
1162
1185
  */
1163
1186
  protected resolveAppName(): string {
1187
+ const configured: unknown = this.config.appName;
1188
+ if (typeof configured === 'string' && configured.trim()) {
1189
+ return configured.trim();
1190
+ }
1191
+ if (configured !== undefined && configured !== null && typeof configured !== 'string') {
1192
+ this.logger.warn(
1193
+ `betterAuth.emailVerification.appName must be a string and is ignored (got ${typeof configured}); the mails use the package.json name`,
1194
+ );
1195
+ }
1164
1196
  // Try to get from package.json name
1165
1197
  try {
1166
1198
  const packageJsonPath = path.join(process.cwd(), 'package.json');
@@ -2,6 +2,7 @@ import { HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/c
2
2
  import { NextFunction, Request, Response } from 'express';
3
3
 
4
4
  import { CoreBetterAuthRateLimiter, RateLimitResult } from './core-better-auth-rate-limiter.service.js';
5
+ import { CONTROLLER_HANDLED_PATHS } from './core-better-auth-openapi.helper.js';
5
6
  import { CoreBetterAuthService } from './core-better-auth.service.js';
6
7
 
7
8
  /**
@@ -57,6 +58,9 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
57
58
  const requestPath = (req.originalUrl || req.url || '').split('?')[0];
58
59
  const path = requestPath.startsWith(basePath) ? requestPath.substring(basePath.length) : requestPath;
59
60
 
61
+ // The route names counters are keyed by, from the running instance (once per instance)
62
+ this.provideKnownEndpoints();
63
+
60
64
  // Check rate limit
61
65
  const result = await this.rateLimiter.check(ip, path);
62
66
 
@@ -94,6 +98,25 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
94
98
  return req.ip || req.socket?.remoteAddress || 'unknown';
95
99
  }
96
100
 
101
+ /** The instance whose routes the limiter knows */
102
+ private knownEndpointsFrom: unknown = null;
103
+
104
+ /**
105
+ * Hands the limiter the routes the base path serves: Better-Auth's own (every endpoint of the running instance,
106
+ * plugins included) and the controller's. Counters are keyed by these names only, so unknown paths cannot create
107
+ * counters (see CoreBetterAuthRateLimiter.normalizeEndpoint()).
108
+ */
109
+ private provideKnownEndpoints(): void {
110
+ // Optional call: a project's stand-in service may not offer it, and the limiter stays bounded without the names
111
+ const instance = this.betterAuthService.getInstance?.() as null | undefined | { api?: Record<string, unknown> };
112
+ if (!instance || instance === this.knownEndpointsFrom) {
113
+ return;
114
+ }
115
+ this.knownEndpointsFrom = instance;
116
+ const routes = Object.values(instance.api ?? {}).map((endpoint) => (endpoint as { path?: unknown })?.path);
117
+ this.rateLimiter.setKnownEndpoints([...routes, ...CONTROLLER_HANDLED_PATHS]);
118
+ }
119
+
97
120
  /**
98
121
  * Add standard rate limit headers to response
99
122
  */
@@ -288,7 +288,36 @@ export class CoreBetterAuthRateLimiter {
288
288
  }
289
289
 
290
290
  /**
291
- * Normalize endpoint path for consistent grouping
291
+ * The route names the base path serves: the last static segment of every route Better-Auth and the controller
292
+ * answer (`/sign-in/email` → `email`, `/two-factor/enable` → `enable`). Set by CoreBetterAuthRateLimitMiddleware from
293
+ * the running instance. A counter is keyed by one of these names, so a client cannot create counters of its own.
294
+ */
295
+ protected knownEndpoints: null | ReadonlySet<string> = null;
296
+
297
+ /**
298
+ * Record the routes the base path serves (paths relative to it, `:param` segments allowed). Only their last static
299
+ * segment counts.
300
+ */
301
+ setKnownEndpoints(paths: Iterable<unknown>): void {
302
+ const names = new Set<string>();
303
+ for (const path of paths) {
304
+ if (typeof path !== 'string') {
305
+ continue;
306
+ }
307
+ const last = path.split('?')[0].split('/').filter(Boolean).pop();
308
+ if (last && !last.startsWith(':')) {
309
+ names.add(last.toLowerCase());
310
+ }
311
+ }
312
+ this.knownEndpoints = names;
313
+ }
314
+
315
+ /**
316
+ * Normalize endpoint path for consistent grouping. The result comes from a bounded set — a known route name, a
317
+ * configured strict entry, `callback` or `other` — never from the request alone: keyed by the raw last segment, one
318
+ * client sending `/iam/x1`, `/iam/x2`, … created one counter per path, none of them ever reached the limit, and once
319
+ * the store held `maxEntries` counters every new client fell into the overflow buckets the attacker had filled, and
320
+ * was refused at its first sign-in.
292
321
  */
293
322
  private normalizeEndpoint(path: string): string {
294
323
  // Remove query strings
@@ -299,9 +328,21 @@ export class CoreBetterAuthRateLimiter {
299
328
  return 'callback';
300
329
  }
301
330
 
302
- // Extract the last segment as the endpoint identifier
331
+ // The last segment, when it names a route the base path serves
303
332
  const segments = cleanPath.split('/').filter(Boolean);
304
- return segments[segments.length - 1] || 'root';
333
+ const last = segments[segments.length - 1];
334
+ if (last && this.knownEndpoints?.has(last)) {
335
+ return last;
336
+ }
337
+
338
+ // A strict route under a name nobody serves (`/reset-password/<token>`, `/sign-in/<anything>`) keeps its own counter
339
+ const strict = this.config.strictEndpoints.find((entry) => pathContainsSegments(cleanPath, entry.toLowerCase()));
340
+ if (strict) {
341
+ return `strict:${strict.toLowerCase()}`;
342
+ }
343
+
344
+ // Everything else of one client shares one counter, as every IAM request did before the per-route split
345
+ return 'other';
305
346
  }
306
347
 
307
348
  /**
@@ -545,9 +545,11 @@ semantics for class fields), and type-checks nothing — `tsc` and the IDE do th
545
545
  (`pnpm add -D @swc/core`; starter-based projects have it), resolved from the working directory. The same file runs
546
546
  the dev server from source: `node -r <path>/ts-compiler.js src/main.ts`.
547
547
 
548
- It covers both module systems: a `require` hook for CommonJS, and Node module hooks (`ts-compiler-hooks.mjs`,
549
- registered on load) for ES modules — an ESM project's entry and everything it imports. Both map a `./x.js` specifier to
550
- `./x.ts` when only the source exists. The implementation is `ts-compiler.cjs`; `ts-compiler.js` is the established
548
+ It covers both module systems: a `require` hook for CommonJS, and Node module hooks, registered on load, for ES
549
+ modules — an ESM project's entry and everything it imports. Both map a `./x.js` specifier to `./x.ts` when only the
550
+ source exists. The module hooks run through `module.registerHooks()` on Node 24.12+ and 26+, so Node 26 prints no
551
+ `module.register()` deprecation (DEP0205) on every start and migration (12.8.3); Node 22, 24.0–24.11 and 25 keep
552
+ `module.register()` with `ts-compiler-hooks.mjs`, which none of them deprecates. The implementation is `ts-compiler.cjs`; `ts-compiler.js` is the established
551
553
  entry path and forwards to it. `helpers/package.json` declares `"type": "commonjs"`, so that path works in CommonJS and
552
554
  ESM projects, in npm and vendor mode.
553
555
 
@@ -1,65 +1,31 @@
1
1
  /**
2
- * ESM hooks of the framework's TypeScript loader, registered by `ts-compiler.cjs` through `module.register()`.
2
+ * Asynchronous module hooks of the framework's TypeScript loader, registered by `ts-compiler.cjs` through
3
+ * `module.register()` on the Node lines whose `module.registerHooks()` cannot hand CommonJS back to the CommonJS loader
4
+ * (22.x, 24.0–24.11, 25.x; see `registerHooksHandsBackCommonJs()`). Newer lines run the synchronous twins in
5
+ * `ts-compiler.cjs` in-thread instead, and this file is not loaded there.
6
+ *
7
+ * Both share one implementation in `ts-compiler.cjs`, so the two paths cannot drift:
3
8
  *
4
9
  * - `resolve`: a relative `./x.js` from a TypeScript file finds `x.ts` when no `x.js` exists (ESM requires the
5
10
  * extension of the EMITTED file, so sources written for both module systems name files that exist only after a
6
11
  * build). A real `.js` file always wins.
7
- * - `load`: a TypeScript file in ESM scope (`.mts`, or `.ts` under `"type": "module"`) is compiled with SWC to ESM,
8
- * with the options of the CommonJS hook. One in CommonJS scope is handed back to the CommonJS loader, where the
9
- * `require` hook compiles it — the same file must not be compiled two different ways.
12
+ * - `load`: a TypeScript file in ESM scope (`.mts`, or `.ts` under `"type": "module"`) is compiled with SWC to ESM. One
13
+ * in CommonJS scope is handed back to the CommonJS loader, where the `require` hook compiles it.
14
+ *
15
+ * Runs on the hooks thread `module.register()` creates; loading `ts-compiler.cjs` there registers no hooks again.
10
16
  */
11
- import { readFileSync } from 'node:fs';
12
17
  import { createRequire } from 'node:module';
13
- import { dirname, join } from 'node:path';
14
- import { fileURLToPath } from 'node:url';
15
18
 
16
19
  const require = createRequire(import.meta.url);
17
- const { loadSwc, SOURCE_EXTENSIONS, SWC_OPTIONS } = require('./ts-compiler.cjs');
18
-
19
- const TYPESCRIPT = /\.(c|m)?ts$/;
20
- const packageTypes = new Map();
21
- let swc;
22
-
23
- /** `"module"` or `"commonjs"`, from the nearest package.json — how Node itself decides a `.ts` file's format. */
24
- function packageType(directory) {
25
- if (packageTypes.has(directory)) {
26
- return packageTypes.get(directory);
27
- }
28
- let type = 'commonjs';
29
- try {
30
- type = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')).type === 'module' ? 'module' : 'commonjs';
31
- } catch {
32
- const parent = dirname(directory);
33
- type = parent === directory ? 'commonjs' : packageType(parent);
34
- }
35
- packageTypes.set(directory, type);
36
- return type;
37
- }
38
-
39
- function formatOf(filename) {
40
- if (filename.endsWith('.mts')) {
41
- return 'module';
42
- }
43
- if (filename.endsWith('.cts')) {
44
- return 'commonjs';
45
- }
46
- return packageType(dirname(filename));
47
- }
20
+ const { loadTypeScript, typeScriptSpecifiers } = require('./ts-compiler.cjs');
48
21
 
49
22
  export async function resolve(specifier, context, nextResolve) {
50
23
  try {
51
24
  return await nextResolve(specifier, context);
52
25
  } catch (error) {
53
- const extension = specifier.match(/\.(c|m)?js$/)?.[0];
54
- const fromTypeScript = TYPESCRIPT.test(context.parentURL ?? '');
55
- const pathLike = /^\.{0,2}\//.test(specifier) || specifier.startsWith('file:');
56
- if (error?.code !== 'ERR_MODULE_NOT_FOUND' || !extension || !fromTypeScript || !pathLike) {
57
- throw error;
58
- }
59
- const sources = { ...SOURCE_EXTENSIONS, '.mjs': ['.mts'] }[extension] ?? [];
60
- for (const sourceExtension of sources) {
26
+ for (const candidate of typeScriptSpecifiers(specifier, context, error) ?? []) {
61
27
  try {
62
- return await nextResolve(specifier.slice(0, -extension.length) + sourceExtension, context);
28
+ return await nextResolve(candidate, context);
63
29
  } catch {
64
30
  // try the next one; the original error is the one worth reporting
65
31
  }
@@ -69,22 +35,5 @@ export async function resolve(specifier, context, nextResolve) {
69
35
  }
70
36
 
71
37
  export async function load(url, context, nextLoad) {
72
- if (!url.startsWith('file:') || !TYPESCRIPT.test(new URL(url).pathname)) {
73
- return nextLoad(url, context);
74
- }
75
- const filename = fileURLToPath(url);
76
- if (formatOf(filename) === 'commonjs') {
77
- // No source: Node loads it with the CommonJS loader, i.e. through the `require` hook.
78
- return { format: 'commonjs', shortCircuit: true };
79
- }
80
- swc ??= loadSwc();
81
- const { code } = swc.transformSync(readFileSync(filename, 'utf8'), {
82
- ...SWC_OPTIONS,
83
- filename,
84
- // SWC drops import attributes unless told to keep them, and Node refuses a JSON import without
85
- // `with { type: 'json' }` (ERR_IMPORT_ATTRIBUTE_MISSING) — `import pkg from '../package.json' with { type: 'json' }`.
86
- jsc: { ...SWC_OPTIONS.jsc, experimental: { keepImportAssertions: true } },
87
- module: { type: 'es6' },
88
- });
89
- return { format: 'module', shortCircuit: true, source: code };
38
+ return loadTypeScript(url) ?? nextLoad(url, context);
90
39
  }