@lenne.tech/nest-server 12.8.0 → 12.8.2

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 (49) hide show
  1. package/.claude/rules/better-auth.md +19 -0
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/testing.md +3 -3
  4. package/FRAMEWORK-API.md +1 -1
  5. package/dist/core/modules/auth/services/core-auth.service.js +3 -0
  6. package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
  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-api.middleware.js +2 -1
  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 +1 -0
  12. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +5 -1
  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-rate-limit.middleware.d.ts +2 -0
  15. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +12 -0
  16. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
  17. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +2 -0
  18. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +23 -1
  19. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
  20. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
  21. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
  22. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  23. package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
  24. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  25. package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
  26. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  27. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
  28. package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
  29. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  30. package/dist/core/modules/user/core-user.service.js +5 -1
  31. package/dist/core/modules/user/core-user.service.js.map +1 -1
  32. package/migration-guides/11.41.7-to-11.41.8.md +1 -1
  33. package/migration-guides/12.2.x-to-12.3.x.md +2 -2
  34. package/migration-guides/12.8.0-to-12.8.1.md +85 -0
  35. package/migration-guides/12.8.1-to-12.8.2.md +125 -0
  36. package/package.json +1 -1
  37. package/src/core/common/interfaces/server-options.interface.ts +2 -1
  38. package/src/core/modules/auth/services/core-auth.service.ts +8 -0
  39. package/src/core/modules/better-auth/README.md +11 -5
  40. package/src/core/modules/better-auth/better-auth.config.ts +63 -5
  41. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
  42. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +18 -1
  43. package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +23 -0
  44. package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +44 -3
  45. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
  46. package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
  47. package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
  48. package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
  49. package/src/core/modules/user/core-user.service.ts +10 -2
@@ -0,0 +1,125 @@
1
+ # Migration Guide: 12.8.1 → 12.8.2
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None. On a stage with `NODE_ENV=test` Better-Auth's origin and CSRF checks now run, as they always did elsewhere (§1) |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Security: on a stage with `NODE_ENV=test`, Better-Auth's origin check, CSRF check and `callbackURL` / `redirectTo` validation were off, so a password-reset mail could carry its token to a page the caller chose (§1). Documentation named `betterAuth.options.plugins` for custom plugins, which replaces the built-in ones (§2). A project's `betterAuth.options.user` replaced the framework's `user` block (§3). An address change that differed only in case ended every session (§4). One client could fill the IAM rate limiter's store with paths nobody serves, after which new clients were refused at their first sign-in (§5) |
10
+ | **Migration Effort** | Update. A test stage whose frontend origin is missing from `trustedOrigins` answers 403 `INVALID_ORIGIN` now, as production already does (§1). Plugins registered through `betterAuth.options.plugins` move to `betterAuth.plugins` (§2) |
11
+
12
+ 12.8.2 is a security patch for 12.8.1. The same fix ships in 12.6.7 (`latest-12.6`) and 11.44.2 (`latest-11`).
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@12.8.2
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 origin check runs whatever the environment is called
26
+
27
+ **Why:** Better-Auth decides its origin check itself while `advanced.disableOriginCheck` is unset. Its `isTest()`
28
+ (`NODE_ENV === 'test'`, or a truthy `TEST` variable) switches the check off. With it go:
29
+
30
+ - the CSRF check (Better-Auth keeps them coupled for backward compatibility),
31
+ - the validation of `callbackURL`, `redirectTo`, `errorCallbackURL` and `newUserCallbackURL` against `trustedOrigins`.
32
+
33
+ The nest-server-starter names its deployed test stage `test`, so every such stage ran without these checks. The worst
34
+ consequence: `POST /iam/request-password-reset` is unauthenticated and took any `redirectTo`. The core's reset mail
35
+ (`betterAuth.emailVerification.passwordResetLink`, default since 11.38.0) uses the caller's `redirectTo` because
36
+ Better-Auth normally validates it first. A request for somebody else's address with
37
+ `redirectTo: 'https://attacker.example/reset'` therefore sent that person a genuine mail whose link carried a valid reset
38
+ token to the attacker's page.
39
+
40
+ **What changed:** for every config environment that is not `local`, `ci` or `e2e` (an unknown or missing one
41
+ included), the core passes `advanced.disableOriginCheck: false` to Better-Auth, so `NODE_ENV` no longer decides the check
42
+ there. `local`, `ci` and `e2e` keep Better-Auth's own decision: vitest sets `TEST=true`, so test suites still run without
43
+ the check, as before. A suite that wants it (CSRF, foreign origins, `redirectTo`) sets
44
+ `betterAuth.options.advanced.disableOriginCheck: false` itself, as `tests/better-auth-signin-csrf.e2e-spec.ts` does. A
45
+ project that sets `betterAuth.options.advanced.disableOriginCheck` keeps its own value; an explicitly `undefined` value
46
+ counts as not set. While a project switches the check off (`true`, or a list of paths),
47
+ the core's reset mail no longer takes the caller's `redirectTo` at all and links to the default page
48
+ (`<appUrl>/auth/reset-password`), because nothing validated the URL.
49
+
50
+ **Who was affected:** every project with Better-Auth that ran a deployed stage with `NODE_ENV=test` or a truthy `TEST`
51
+ variable. Stages with `NODE_ENV=develop` or `production` were not affected.
52
+
53
+ **Your project:** update. Then check:
54
+
55
+ - **Frontend origins of the test stage.** A browser request that carries cookies is checked against `trustedOrigins`
56
+ now. If the test stage's frontend runs on an origin the configuration does not name (`appUrl`, `cors.allowedOrigins`,
57
+ `betterAuth.trustedOrigins`), sign-in through Better-Auth's own routes, 2FA and passkeys answer 403 `INVALID_ORIGIN`
58
+ there. Production behaves this way already; add the origin to the same setting.
59
+ - **Password resets on test stages.** A reset link requested while the stage ran an affected version may have carried
60
+ its token to a foreign page. Whoever held the token could set a new password, so ending sessions alone does not
61
+ lock them out again. Where test stages hold accounts that matter, take the time the stage ran an affected version as
62
+ the window, and for every account whose password changed in it:
63
+ - make the password unusable and have the owner set a new one through a reset on the fixed version;
64
+ - remove what was added in the window: passkeys, 2FA enrolments, a changed e-mail address, API tokens;
65
+ - then end its sessions.
66
+
67
+ What shows such a reset: `POST /iam/reset-password` in the access logs, and credential accounts (`account`,
68
+ `providerId: 'credential'`) whose `updatedAt` falls in the window. The `redirectTo` itself is a body field, which
69
+ access logs do not record, and Better-Auth logged nothing for it while the check was off.
70
+
71
+ ## 2. Documentation: custom Better-Auth plugins belong in `betterAuth.plugins`
72
+
73
+ The descriptions of `emailAndPassword.disableSignUp` (interface, README, guide 12.2.x → 12.3.x) named
74
+ `betterAuth.options.plugins` as the place for a project's own plugins. The framework appends `betterAuth.plugins` to its
75
+ own (JWT, 2FA, passkey). `betterAuth.options` is spread over the generated configuration, so `options.plugins`
76
+ **replaces** that list, and JWT, 2FA and passkey stop working without an error.
77
+
78
+ **Your project:** if you register plugins through `betterAuth.options.plugins`, move them to `betterAuth.plugins`. A
79
+ plugin that creates users itself (Magic Link, Generic OAuth) does not follow `emailAndPassword.disableSignUp`. Give it
80
+ its own option, for example `magicLink({ disableSignUp: true, … })`.
81
+
82
+ ## 3. `betterAuth.options.user` is merged
83
+
84
+ The framework gives Better-Auth `user: { modelName: 'users', additionalFields }`. That is the collection or table it
85
+ shares with the user model, plus the fields `betterAuth.additionalUserFields` declares, among them the `input: false` locks
86
+ on `roles`, `verified` and `twoFactorEnabled`. `betterAuth.options` was spread over that configuration, so a project
87
+ that set `options.user` for its own reason (`changeEmail`, `deleteUser`) replaced the whole block. Better-Auth then read
88
+ and wrote a `user` collection the framework never sees, and knew none of the additional fields.
89
+
90
+ **What changed:** `options.user` is merged. `modelName` stays `users` unless the project names another one. A project
91
+ field of the same name as a framework field does not replace it; change those through `betterAuth.additionalUserFields`.
92
+ A project field under another name that maps to a locked column (`fieldName: 'roles'`) is locked as well.
93
+
94
+ **Your project:** nothing, unless you set `betterAuth.options.user`. Then check whether a `user` collection or table holds
95
+ records written while the options were replaced.
96
+
97
+ ## 4. An address that differs only in case is no change
98
+
99
+ `CoreUserService.update()` syncs an address change to IAM, and that sync ends every session of the account. It compared
100
+ the stored address with the submitted one as typed, while the address is stored trimmed and in lower case. A profile
101
+ form sending `Foo@Example.com` back for `foo@example.com` therefore signed the user out everywhere without changing
102
+ anything. The comparison now uses the stored form. Nothing to do.
103
+
104
+ ## 5. The IAM rate limiter keys its counters by a bounded set of names
105
+
106
+ Only with `betterAuth.rateLimit` configured (the nest-server-starter reads `IAM_RATE_LIMIT_MAX`). Since 12.3.0 a
107
+ counter was keyed by the last segment of the path as sent, and the limiter runs for every path under the base path,
108
+ existing or not. One client sending `/iam/x1`, `/iam/x2`, … created one counter per request, and none of them reached the
109
+ limit. Once the store held `maxEntries` counters (10,000 by default, the Redis store likewise), every new client fell
110
+ into the shared overflow buckets the attacker had filled, and was refused at its first sign-in.
111
+
112
+ **What changed:** a counter is keyed by a route name the base path serves (taken from the running Better-Auth instance and
113
+ the controller, so plugin routes are included), by the matching strict entry for a strict route under an unknown name
114
+ (`/reset-password/<token>`), or by one `other` counter per client for everything else. Real routes keep their counters
115
+ as before: `/sign-in/email` and `/sign-up/email` still share one, `/get-session` and `/two-factor/enable` still have one
116
+ each. Nothing to do.
117
+
118
+ ## References
119
+
120
+ - `src/core/modules/better-auth/better-auth.config.ts`: the `advanced` block of `createBetterAuthInstance()`
121
+ - `src/core/modules/better-auth/core-better-auth-email-verification.service.ts`: `buildPasswordResetUrl()`,
122
+ `readCallbackUrlFromBetterAuthLink()`
123
+ - `tests/unit/better-auth-origin-check-test-env.spec.ts`, `tests/unit/better-auth-user-options-merge.spec.ts`,
124
+ `tests/unit/user-email-change-case.spec.ts`, `tests/unit/better-auth-rate-limit-key-bound.spec.ts`
125
+ - `.claude/rules/better-auth.md`: security checklist
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.8.0",
3
+ "version": "12.8.2",
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": [
@@ -4608,7 +4608,8 @@ interface IBetterAuthBase {
4608
4608
  * Since 12.3.0 it closes social sign-up too: every configured social provider receives it as its own
4609
4609
  * `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
4610
4610
  * signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
4611
- * registers itself through `options.plugins` are not covered.
4611
+ * registers itself through `plugins` are not covered; they need their own sign-up option
4612
+ * (`magicLink({ disableSignUp: true })`).
4612
4613
  * The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
4613
4614
  * which would answer `SIGNUP_DISABLED` to every caller.
4614
4615
  * @default false
@@ -591,6 +591,14 @@ export class CoreAuthService {
591
591
 
592
592
  // Link or create Legacy user with iamId
593
593
  const iamUser = response.user as { email: string; id: string; name?: string };
594
+
595
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
596
+ // with a placeholder user it never stored. Linking it re-pointed the real account, overwrote its password with
597
+ // the caller's, and this method then returned that account — the caller got its tokens (12.8.1). The legacy
598
+ // sign-up has always answered a known address with this error, so the IAM path does the same.
599
+ if (!(await this.betterAuthService.isPersistedUser(iamUser.id))) {
600
+ throw new BadRequestException('Email address already in use');
601
+ }
594
602
  const syncedUser = await this.betterAuthUserMapper.linkOrCreateUser(iamUser as any, {
595
603
  firstName: inputAny.firstName,
596
604
  lastName: inputAny.lastName,
@@ -677,8 +677,8 @@ socialProviders: {
677
677
  ```
678
678
 
679
679
  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
680
+ `NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds itself through `betterAuth.plugins`
681
+ (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
682
  accounts whatever `disableSignUp` said.
683
683
 
684
684
  **Default:** `false` (sign-up enabled) - fully backward compatible.
@@ -2099,11 +2099,17 @@ When a user is deleted:
2099
2099
  db.account.findOne({ userId: ObjectId('...'), providerId: 'credential' });
2100
2100
  ```
2101
2101
 
2102
- From better-auth 1.7 the row must ALSO carry `issuer: 'local:credential'`. A row matching only
2103
- `providerId` is not usable — better-auth keys accounts by `(issuer, accountId)` and will not find
2104
- it, so sign-in answers 401 while this query happily reports that the account exists:
2102
+ On better-auth 1.7.3 and later (nest-server requires 1.7.16 or later) that query is the whole
2103
+ check: rows carry no `issuer`, and an `issuer` filter finds nothing for every user — that is
2104
+ expected, not the cause of a 401. Do not write `issuer` fields by hand.
2105
+
2106
+ Only on better-auth 1.7.0–1.7.2 (see [Boot-Time Behaviour](#boot-time-behaviour)) must the row ALSO
2107
+ carry `issuer: 'local:credential'`. There a row matching only `providerId` is not usable — those
2108
+ versions key accounts by `(issuer, accountId)` and will not find it, so sign-in answers 401 while
2109
+ the query above reports that the account exists:
2105
2110
 
2106
2111
  ```javascript
2112
+ // better-auth 1.7.0–1.7.2 only
2107
2113
  db.account.findOne({ issuer: 'local:credential', providerId: 'credential', userId: ObjectId('...') });
2108
2114
  ```
2109
2115
 
@@ -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
  /**
@@ -8,6 +8,7 @@ import { BetterAuthCookieHelper, createCookieHelper } from './core-better-auth-c
8
8
  import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.helper.js';
9
9
  import { isControllerHandledPath } from './core-better-auth-openapi.helper.js';
10
10
  import { runWithResetPassword } from './core-better-auth-password-reset.registry.js';
11
+ import { canonicalRequestPath } from './core-better-auth-path-guard.middleware.js';
11
12
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
12
13
  import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper.js';
13
14
  import { CoreBetterAuthService } from './core-better-auth.service.js';
@@ -314,9 +315,13 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
314
315
  }
315
316
 
316
317
  const basePath = this.betterAuthService.getBasePath();
317
- // Use originalUrl to get full path for IAM endpoints, but fallback to req.path
318
- // The originalUrl contains the original request path as sent by client
319
- const requestPath = req.originalUrl?.split('?')[0] || req.path;
318
+ // The path Better-Auth will ROUTE, not the one the client wrote (12.8.1): the forwarded Web Request is built with
319
+ // `new URL(originalUrl, baseUrl)` (toWebRequest()), which resolves `.`, `..` and `%2e` segments. Compared raw,
320
+ // `/iam/sign-up/%2e/email` counted as "not a controller path" while Better-Auth's own sign-up served it — past the
321
+ // controller's checks and every project override. CoreBetterAuthPathGuardMiddleware refuses such a path before this
322
+ // runs; deciding on the canonical path keeps this middleware right where the guard is not registered, as the rate
323
+ // limiter does.
324
+ const requestPath = canonicalRequestPath(req.originalUrl || req.url || req.path);
320
325
 
321
326
  // Only handle requests that start with the Better Auth base path
322
327
  if (!requestPath.startsWith(basePath)) {
@@ -634,6 +634,16 @@ export class CoreBetterAuthEmailVerificationService {
634
634
  return Math.max(1, Math.round(resolved / 60));
635
635
  }
636
636
 
637
+ /**
638
+ * Whether the project switched Better-Auth's origin check off (`betterAuth.options.advanced.disableOriginCheck`):
639
+ * `true`, or a list of paths, which may name the reset route. The framework itself pins `false` (12.8.2), so only a
640
+ * project's own value counts here.
641
+ */
642
+ protected isOriginCheckDisabled(): boolean {
643
+ const raw = this.configService.getFastButReadOnly<unknown>('betterAuth.options.advanced.disableOriginCheck');
644
+ return raw === true || Array.isArray(raw);
645
+ }
646
+
637
647
  protected buildPasswordResetUrl(options: SendPasswordResetEmailOptions): string {
638
648
  const configured = this.config.passwordResetLink;
639
649
 
@@ -648,7 +658,9 @@ export class CoreBetterAuthEmailVerificationService {
648
658
  // `nuxt-base-starter` sends it on every request (`forgot-password.vue` →
649
659
  // `requestPasswordReset({ email, redirectTo: appUrl('/auth/reset-password', siteUrl) })`), and
650
660
  // a client that names its page is a better authority on that page than a framework default.
651
- if (!target) {
661
+ // Only while Better-Auth's origin check validated it (see readCallbackUrlFromBetterAuthLink): a project that
662
+ // switched the check off gets the default page, never an unvalidated URL with a valid token in it.
663
+ if (!target && !this.isOriginCheckDisabled()) {
652
664
  target = this.readCallbackUrlFromBetterAuthLink(options.url);
653
665
  // Only an absolute http(s) URL or a root-relative path names a page. Anything else — a path without
654
666
  // its leading slash (`redirectTo: 'reset'`), or a template literal over an unset variable
@@ -711,6 +723,11 @@ export class CoreBetterAuthEmailVerificationService {
711
723
  * knowing before anyone widens it. `cors.allowAll` does not widen it (an origin check has no
712
724
  * "allow everything" mode), but an over-broad `allowedOrigins` would.
713
725
  *
726
+ * And it makes the origin check itself load-bearing. Until 12.8.2 Better-Auth switched it off on its
727
+ * own under `NODE_ENV=test` (`isTest()`), which is a deployed stage in starter-based projects; the
728
+ * framework now pins `advanced.disableOriginCheck: false`. A project that switches it off itself
729
+ * gets no caller URL here at all ({@link isOriginCheckDisabled}).
730
+ *
714
731
  * Returns `undefined` for anything unparseable or absent, so the caller falls through to its own
715
732
  * resolution rather than to a half-formed URL.
716
733
  */
@@ -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
  /**
@@ -241,6 +241,29 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
241
241
  * @param sessionUser - The Better-Auth session user
242
242
  * @returns A mapped user with role capabilities
243
243
  */
244
+ /**
245
+ * The mapped user of a Better-Auth user that is stored nowhere, from its own fields only (12.8.1).
246
+ *
247
+ * The placeholder Better-Auth answers a sign-up for an already registered address with (see
248
+ * `CoreBetterAuthService.isPersistedUser()`) must look like a new user: its own id, no roles, not verified. Looking it
249
+ * up by address, as {@link mapSessionUser} does, found the real account and answered its id and roles.
250
+ */
251
+ mapUnstoredSessionUser(sessionUser: BetterAuthSessionUser): MappedUser | null {
252
+ if (!sessionUser?.id || !sessionUser?.email) {
253
+ return null;
254
+ }
255
+ return this.createMappedUser({
256
+ email: sessionUser.email,
257
+ emailVerified: sessionUser.emailVerified,
258
+ iamId: sessionUser.id,
259
+ id: sessionUser.id,
260
+ image: sessionUser.image,
261
+ name: sessionUser.name,
262
+ roles: [],
263
+ verified: sessionUser.emailVerified,
264
+ });
265
+ }
266
+
244
267
  async mapSessionUser(sessionUser: BetterAuthSessionUser): Promise<MappedUser | null> {
245
268
  if (!sessionUser?.id || !sessionUser?.email) {
246
269
  return null;
@@ -465,6 +488,24 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
465
488
  * @param plainPassword - The plain password to hash with bcrypt
466
489
  * @returns true if sync was successful, false otherwise
467
490
  */
491
+ /**
492
+ * Spends the time {@link syncPasswordToLegacy} spends on a password, and writes nothing (12.8.1).
493
+ *
494
+ * A sign-up for an already registered address writes nothing (see `CoreBetterAuthService.isPersistedUser()`).
495
+ * Without this it would answer a bcrypt round faster than a real sign-up, and the response time would tell which
496
+ * addresses have an account — the enumeration Better-Auth's placeholder answer exists to prevent.
497
+ */
498
+ async equalizeLegacyPasswordSync(plainPassword?: string): Promise<void> {
499
+ if (!plainPassword) {
500
+ return;
501
+ }
502
+ try {
503
+ await bcrypt.hash(this.normalizePasswordForIam(plainPassword), 10);
504
+ } catch {
505
+ // Timing only — nothing depends on the result
506
+ }
507
+ }
508
+
468
509
  async syncPasswordToLegacy(iamUserId: string, userEmail: string, plainPassword?: string): Promise<boolean> {
469
510
  const sql = getBetterAuthSqlStore();
470
511
  if (sql) {
@@ -611,17 +611,31 @@ export class CoreBetterAuthController {
611
611
  }
612
612
 
613
613
  if (hasUser(response)) {
614
- // Link or create user in our database
615
- // Pass termsAndPrivacyAccepted to store the acceptance timestamp
616
- await this.userMapper.linkOrCreateUser(response.user, {
617
- termsAndPrivacyAccepted: input.termsAndPrivacyAccepted,
618
- });
619
-
620
- // Sync password to legacy (enables IAM Sign-Up → Legacy Sign-In)
621
- // Pass the plain password so it can be hashed with bcrypt for Legacy Auth
622
- await this.userMapper.syncPasswordToLegacy(response.user.id, response.user.email, input.password);
614
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
615
+ // like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
616
+ // re-pointed the real account found by address and overwrote its legacy password with the caller's (12.8.1).
617
+ // The answer below stays that of a new sign-up; only the writes are left out.
618
+ const isPlaceholder = !(await this.betterAuthService.isPersistedUser(response.user.id));
619
+
620
+ if (isPlaceholder) {
621
+ // The same bcrypt round as the legacy sync, so the response time does not tell the address exists
622
+ await this.userMapper.equalizeLegacyPasswordSync(input.password);
623
+ } else {
624
+ // Link or create user in our database
625
+ // Pass termsAndPrivacyAccepted to store the acceptance timestamp
626
+ await this.userMapper.linkOrCreateUser(response.user, {
627
+ termsAndPrivacyAccepted: input.termsAndPrivacyAccepted,
628
+ });
629
+
630
+ // Sync password to legacy (enables IAM Sign-Up → Legacy Sign-In)
631
+ // Pass the plain password so it can be hashed with bcrypt for Legacy Auth
632
+ await this.userMapper.syncPasswordToLegacy(response.user.id, response.user.email, input.password);
633
+ }
623
634
 
624
- const mappedUser = await this.userMapper.mapSessionUser(response.user);
635
+ // A new user has no roles yet; the placeholder must not carry those of the account it stands for
636
+ const mappedUser = isPlaceholder
637
+ ? this.userMapper.mapUnstoredSessionUser(response.user)
638
+ : await this.userMapper.mapSessionUser(response.user);
625
639
 
626
640
  // Get token: JWT accessToken > top-level token > session.token
627
641
  // Without this, no session cookies are set after sign-up, causing 401 on
@@ -484,10 +484,20 @@ export class CoreBetterAuthResolver {
484
484
  if (hasUser(response)) {
485
485
  const sessionUser: BetterAuthSessionUser = response.user;
486
486
 
487
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
488
+ // like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
489
+ // re-pointed the real account found by address, and the answer carried that account's id and roles (12.8.1).
490
+ // The answer stays that of a new sign-up; only the write is left out.
491
+ const isPlaceholder = !(await this.betterAuthService.isPersistedUser(sessionUser.id));
492
+
487
493
  // Link or create user in our database
488
494
  // Pass termsAndPrivacyAccepted to store the acceptance timestamp
489
- await this.userMapper.linkOrCreateUser(sessionUser, { termsAndPrivacyAccepted });
490
- const mappedUser = await this.userMapper.mapSessionUser(sessionUser);
495
+ if (!isPlaceholder) {
496
+ await this.userMapper.linkOrCreateUser(sessionUser, { termsAndPrivacyAccepted });
497
+ }
498
+ const mappedUser = isPlaceholder
499
+ ? this.userMapper.mapUnstoredSessionUser(sessionUser)
500
+ : await this.userMapper.mapSessionUser(sessionUser);
491
501
 
492
502
  // If email verification is enabled, revoke the session and don't return session data
493
503
  // The user must verify their email before they can use any session
@@ -1101,6 +1101,34 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1101
1101
  }
1102
1102
  }
1103
1103
 
1104
+ /**
1105
+ * Whether Better-Auth has stored the user `userId` — false for the placeholder it answers a sign-up with when the
1106
+ * address is already registered (12.8.1).
1107
+ *
1108
+ * With `emailAndPassword.requireEmailVerification: true` or `autoSignIn: false`, Better-Auth answers a sign-up for a
1109
+ * known address like a new one (enumeration protection): `{ token: null, user: <a generated id, the given address> }`.
1110
+ * That user exists nowhere. The sign-up paths linked it to the app user found by address — the real account then
1111
+ * carried the placeholder's id and `verified: false`, its legacy password became the one the caller chose, and the
1112
+ * answer carried its roles. A sign-up therefore writes only for a user this confirms. Asked through Better-Auth's own
1113
+ * adapter (`internalAdapter.findUserById()`), so it reads wherever Better-Auth keeps its users.
1114
+ *
1115
+ * @returns `false` for an unknown id, an empty id, and a failed lookup — a sign-up that cannot confirm the user writes
1116
+ * nothing rather than guessing
1117
+ */
1118
+ async isPersistedUser(userId: string): Promise<boolean> {
1119
+ if (typeof userId !== 'string' || !userId) {
1120
+ return false;
1121
+ }
1122
+ try {
1123
+ const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1124
+ const user: unknown = await context?.internalAdapter?.findUserById?.(userId);
1125
+ return !!user && String((user as { id?: unknown }).id) === userId;
1126
+ } catch (error) {
1127
+ this.logger.error(`isPersistedUser error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1128
+ return false;
1129
+ }
1130
+ }
1131
+
1104
1132
  /**
1105
1133
  * Revokes a specific session (logout for that session)
1106
1134
  *