@lenne.tech/nest-server 11.44.0 → 11.44.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.
- package/.claude/rules/better-auth.md +50 -4
- package/.claude/rules/configurable-features.md +1 -1
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/config.env.js +2 -2
- package/dist/config.env.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/modules/auth/services/core-auth.service.js +3 -0
- package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +32 -4
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +2 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +5 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js +70 -0
- package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +14 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +3 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +28 -4
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.module.js +2 -0
- package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/index.d.ts +1 -0
- package/dist/core/modules/better-auth/index.js +1 -0
- package/dist/core/modules/better-auth/index.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +9 -0
- package/dist/core/modules/error-code/error-codes.js +8 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core/modules/user/core-user.service.js +5 -1
- package/dist/core/modules/user/core-user.service.js.map +1 -1
- package/dist/server/modules/error-code/error-codes.d.ts +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/docs/REQUEST-LIFECYCLE.md +1 -0
- package/docs/error-codes.md +14 -0
- package/migration-guides/11.41.7-to-11.41.8.md +1 -1
- package/migration-guides/11.44.0-to-11.44.1.md +152 -0
- package/migration-guides/11.44.1-to-11.44.2.md +125 -0
- package/package.json +1 -1
- package/src/config.env.ts +6 -2
- package/src/core/common/interfaces/server-options.interface.ts +16 -0
- package/src/core/modules/auth/services/core-auth.service.ts +8 -0
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +3 -0
- package/src/core/modules/better-auth/README.md +34 -4
- package/src/core/modules/better-auth/better-auth.config.ts +72 -5
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +18 -1
- package/src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts +85 -0
- package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +28 -2
- package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +58 -10
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
- package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
- package/src/core/modules/better-auth/core-better-auth.module.ts +12 -2
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
- package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
- package/src/core/modules/better-auth/index.ts +1 -0
- package/src/core/modules/error-code/error-codes.ts +9 -0
- package/src/core/modules/user/core-user.service.ts +10 -2
|
@@ -64,6 +64,7 @@ Modern OAuth-compatible authentication with plugin architecture:
|
|
|
64
64
|
| **Social Login** | OAuth providers: Google, GitHub, Apple, Discord, etc. (plugin) |
|
|
65
65
|
| **Email Verification** | Configurable email verification flow |
|
|
66
66
|
| **Sign-Up Validation** | Custom validation hooks for registration |
|
|
67
|
+
| **Path Guard** | `CoreBetterAuthPathGuardMiddleware`, the first middleware under the Better-Auth base path (always registered): a path with a `.` / `..` segment (also `%2e`-encoded), a backslash, an encoded `/` / `\` or a `#` is refused with 400 (`#LTNS_0305`) before the rate limiter, the controller routes or the forwarding read it. Every check there reads the path as sent while Better-Auth routes the resolved one, so without the guard `/iam/callback/../sign-in/email` was skipped by the limiter as a callback and ran as a sign-in (12.2.x) |
|
|
67
68
|
| **Rate Limiting** | Per-endpoint rate limits (`betterAuth.rateLimit`, configurable). Counters live behind a `RateLimitStore`: `RedisRateLimitStore` when `redis` is configured, so `max` is enforced **exactly across replicas** instead of `max × replicas`; otherwise the process-local `InMemoryRateLimitStore` as before. `check()` / `reset()` / `clear()` are **async** since 11.33.0. On a Redis outage it degrades to the in-memory counter and logs once per transition — never a 500, never "allowed". Counters are keyed on `request.ip`, which Express derives from `X-Forwarded-For` only as far as `trust proxy` allows — set `trustProxy` (§ServerOptions) behind a reverse proxy or every client resolves to the proxy and shares ONE bucket; unset with a limiter enabled logs a boot warning |
|
|
68
69
|
| **Cross-Subdomain Cookies** | Automatic cookie domain configuration |
|
|
69
70
|
| **Organization / Multi-Tenant** | Teams and organization management (plugin) |
|
package/docs/error-codes.md
CHANGED
|
@@ -346,6 +346,20 @@ All error codes follow the format: `#PREFIX_XXXX: Description`
|
|
|
346
346
|
- DE: Die gesendeten Daten sind zu groß und wurden nicht verarbeitet.
|
|
347
347
|
- EN: The submitted data is too large and was not processed.
|
|
348
348
|
|
|
349
|
+
### LTNS_0305: invalidRequestPath
|
|
350
|
+
|
|
351
|
+
**Message:** Invalid request path
|
|
352
|
+
|
|
353
|
+
**Description:** Answered with HTTP 400 when a request under the Better-Auth base path (`/iam` by default) carries a path segment `.` or `..` (also percent-encoded as `%2e`), a backslash, an encoded `/` or `\` (`%2f`, `%5c`), or a `#`. No route there uses such a path, and the checks in front of Better-Auth would read it as a different route than Better-Auth itself.
|
|
354
|
+
|
|
355
|
+
**Solution:** Send the path in its canonical form. Browsers and HTTP clients do that on their own; the error points at a client that builds paths by hand or sends them unnormalized on purpose.
|
|
356
|
+
|
|
357
|
+
**Parameters:** none
|
|
358
|
+
|
|
359
|
+
**Translations:**
|
|
360
|
+
- DE: Der Anfragepfad ist ungültig.
|
|
361
|
+
- EN: The request path is invalid.
|
|
362
|
+
|
|
349
363
|
---
|
|
350
364
|
|
|
351
365
|
## Resource Errors (LTNS_0400-LTNS_0499)
|
|
@@ -30,7 +30,7 @@ Vendor-mode projects pick up the core update, and raise the same pins.
|
|
|
30
30
|
[GHSA-965c-763c-88jm](https://github.com/better-auth/better-auth/security/advisories/GHSA-965c-763c-88jm)
|
|
31
31
|
(critical): an OAuth state value can be used as a Magic Link to sign in as another user. It covers
|
|
32
32
|
`better-auth >= 1.4.0-beta.18, < 1.7.7`; 1.7.7 is fixed. A project is exposed when it registers the
|
|
33
|
-
`magicLink` plugin — through `betterAuth.options.plugins` — next to a social or Generic OAuth
|
|
33
|
+
`magicLink` plugin — through `betterAuth.plugins` or `betterAuth.options.plugins` — next to a social or Generic OAuth
|
|
34
34
|
provider, with OAuth state stored in the database (the default when a database is configured). An
|
|
35
35
|
attacker who knows a user's email address then gets a normal session for that user, without access
|
|
36
36
|
to the mailbox.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Migration Guide: 11.44.0 → 11.44.1
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None in the API. Non-canonical paths under the Better-Auth base path answer 400, the IAM rate limit counts per route (§2). `emailAndPassword.disableSignUp: true` closes social sign-up too (§3) |
|
|
8
|
+
| **New Features** | `CoreBetterAuthService.isPersistedUser()`, `CoreBetterAuthUserMapper.mapUnstoredSessionUser()` and `equalizeLegacyPasswordSync()` (§1). `socialProviders.<name>.disableSignUp` (§3). `CoreBetterAuthPathGuardMiddleware`, `canonicalRequestPath()`, error code `LTNS_0305` (§2) |
|
|
9
|
+
| **Bugfixes** | Security: a sign-up for an already registered address changed the existing account (§1). Dot segments under the IAM base path bypassed the controller and the rate limiter (§2). Social login created accounts while sign-up was switched off (§3) |
|
|
10
|
+
| **Migration Effort** | Update. Projects that had `requireEmailVerification: true` or `autoSignIn: false` with open sign-up check their accounts (§1). A deployment with a tight `betterAuth.rateLimit.max` checks the value (§2). A project that closed sign-up but wants new users through one social provider sets one flag (§3) |
|
|
11
|
+
|
|
12
|
+
11.44.1 is a security patch for 11.44.0 (`latest-11`). §1 ships in 12.8.1 and 12.6.6 as well. §2 and §3 are backports
|
|
13
|
+
of 12.3.0, where 12.x has had them since.
|
|
14
|
+
|
|
15
|
+
## Quick Migration
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add @lenne.tech/nest-server@11.44.1
|
|
19
|
+
pnpm run update # nest-server-starter based projects (release/11.x)
|
|
20
|
+
pnpm run build
|
|
21
|
+
pnpm test
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
|
|
25
|
+
|
|
26
|
+
## 1. A sign-up for an already registered address changes nothing
|
|
27
|
+
|
|
28
|
+
**Why:** with `emailAndPassword.requireEmailVerification: true` or `emailAndPassword.autoSignIn: false` (set through
|
|
29
|
+
`betterAuth.options`), Better-Auth 1.5.0 and later answers a sign-up for a known address like a new one, so the
|
|
30
|
+
response does not reveal which addresses have an account. That answer carries a placeholder user: a generated id and
|
|
31
|
+
the given address, stored nowhere. The core's sign-up paths took it for the new user:
|
|
32
|
+
|
|
33
|
+
- **REST `POST /iam/sign-up/email`** (`CoreBetterAuthController.signUp()`, also without a project override) linked the
|
|
34
|
+
placeholder to the real account it found by address. That account's `iamId` then pointed at the placeholder, it got
|
|
35
|
+
`verified: false`, its **legacy password was set to the one the caller chose**, and the answer carried its roles.
|
|
36
|
+
- **GraphQL `betterAuthSignUp`** linked it the same way and answered with the real account's id and roles.
|
|
37
|
+
- **The legacy sign-up with IAM enabled** (`/auth/signup`, GraphQL `signUp`) linked it, overwrote the password and
|
|
38
|
+
returned the real account, and the caller received its tokens.
|
|
39
|
+
|
|
40
|
+
With the legacy endpoints open, the overwritten legacy password let the caller sign in as the account owner. For a
|
|
41
|
+
legacy user without an IAM credential account, the next IAM sign-in with that password migrated the account to it.
|
|
42
|
+
|
|
43
|
+
**What changed:** a user Better-Auth returns from a sign-up is written only once `CoreBetterAuthService.isPersistedUser()`
|
|
44
|
+
confirmed it through Better-Auth's own adapter. For a placeholder, nothing is linked and no password is synced. The
|
|
45
|
+
answer stays that of a new sign-up: its own id, no roles, not verified, and the same bcrypt round as a real sign-up,
|
|
46
|
+
so neither the body nor the response time tells the address exists. The legacy sign-up answers a known address with
|
|
47
|
+
`Email address already in use`, as it always did without IAM.
|
|
48
|
+
|
|
49
|
+
**Who was affected:** a project running better-auth 1.5.0 or later (nest-server 11.18.0 and later pin it) whose
|
|
50
|
+
Better-Auth options set `requireEmailVerification: true` or `autoSignIn: false`, with sign-up open
|
|
51
|
+
(`emailAndPassword.disableSignUp: true` refused the request before it reached Better-Auth). Without those options
|
|
52
|
+
Better-Auth answers a known address with an error, and the core answered `EMAIL_ALREADY_EXISTS` without writing.
|
|
53
|
+
|
|
54
|
+
**Your project:** update. If the conditions above applied, the traces an attack leaves on an account do not list every
|
|
55
|
+
affected one: `iamId` no longer matching the account's own id, and `verified: false` next to `emailVerified: true`, are
|
|
56
|
+
written back by the owner's next IAM sign-in, while the overwritten legacy password stays. Take the time the options
|
|
57
|
+
were active as the window and:
|
|
58
|
+
|
|
59
|
+
- **Accounts that still carry a trace:** remove the legacy `password`, end their sessions (IAM sessions and legacy
|
|
60
|
+
refresh tokens) and send a password reset.
|
|
61
|
+
- **Every account with a Better-Auth credential account:** remove the legacy `password`. IAM sign-in does not read it,
|
|
62
|
+
only the legacy endpoints do. Where `auth.legacyEndpoints` keeps those open (closed by default since 11.38.0), send
|
|
63
|
+
these accounts a password reset instead.
|
|
64
|
+
- **Credential accounts created in the window for a user who existed before it:** a legacy user's first IAM sign-in
|
|
65
|
+
creates one with the password used for that sign-in, after an attack the caller's. End those sessions and send a
|
|
66
|
+
password reset.
|
|
67
|
+
|
|
68
|
+
Better-Auth logs a sign-up for a known address ("Sign-up attempt for existing email") only at `logger.level: 'info'` or
|
|
69
|
+
lower. Its default is `warn`, so there is usually no log trail. A project test that stubs `CoreBetterAuthService` for
|
|
70
|
+
the sign-up needs `isPersistedUser`.
|
|
71
|
+
|
|
72
|
+
## 2. Requests under the Better-Auth base path
|
|
73
|
+
|
|
74
|
+
### Non-canonical paths answer 400
|
|
75
|
+
|
|
76
|
+
Every check under the base path (`/iam` by default) — rate limiter, controller routes, the forwarding to Better-Auth —
|
|
77
|
+
read the path as sent, while Better-Auth routes the path after `new URL()` resolved it. `/iam/sign-up/%2e/email`
|
|
78
|
+
therefore reached Better-Auth's own sign-up past the controller and every project override, and
|
|
79
|
+
`/iam/callback/../sign-in/email` passed the rate limiter as a skipped OAuth callback and ran as a sign-in.
|
|
80
|
+
|
|
81
|
+
`CoreBetterAuthPathGuardMiddleware` now runs first under the base path and answers **400** (`#LTNS_0305: Invalid
|
|
82
|
+
request path`) for a path with a `.` or `..` segment (also `%2e`-encoded), a backslash, an encoded `/` or `\`, or a
|
|
83
|
+
`#`. No Better-Auth route needs any of them; a client that sends one has a bug. It is registered by
|
|
84
|
+
`CoreBetterAuthModule` itself, so there is nothing to add. `CoreBetterAuthApiMiddleware` and the rate limiter decide on
|
|
85
|
+
the same canonical path (`canonicalRequestPath()`) as well, so they stay right where the guard is not registered.
|
|
86
|
+
|
|
87
|
+
### The IAM rate limit tells routes apart
|
|
88
|
+
|
|
89
|
+
The rate-limit middleware read `req.path`, which is `/` for a middleware Nest mounts under the base path. So every IAM
|
|
90
|
+
request of a client shared one counter with the full limit, and the skip list (`/session`, `/callback`) and the halved
|
|
91
|
+
limit for sign-in, sign-up and the password routes never applied over HTTP.
|
|
92
|
+
|
|
93
|
+
Now a client IP has one counter per route NAME — the last path segment — so `/sign-in/email` and `/sign-up/email` (both
|
|
94
|
+
`email`) share one counter. `/session` and `/callback` are not counted, and the strict routes (sign-in, sign-up, the
|
|
95
|
+
password reset and change routes) get half of `betterAuth.rateLimit.max`, rounded up. The skip and strict lists match
|
|
96
|
+
whole path segments, case-insensitively, as Express routes.
|
|
97
|
+
|
|
98
|
+
**What to check:** a deployment that set `betterAuth.rateLimit.max` (the nest-server-starter reads it from
|
|
99
|
+
`IAM_RATE_LIMIT_MAX`) gets half of it for the e-mail sign-in and sign-up now, and the two count together: with
|
|
100
|
+
`max: 10`, five attempts per window for both combined. Behind a shared NAT or proxy, sign-ups use up the same budget as
|
|
101
|
+
sign-ins. Raise the value if that is too tight.
|
|
102
|
+
|
|
103
|
+
## 3. Social login creates no account while sign-up is switched off
|
|
104
|
+
|
|
105
|
+
Only with `betterAuth.emailAndPassword.disableSignUp: true` and at least one social provider. The flag closed
|
|
106
|
+
`/sign-up/email` only. Better-Auth decides a social sign-up per provider, and each provider got only its `clientId` and
|
|
107
|
+
`clientSecret`, so whoever signed in with Google, GitHub etc. for the first time got an account in a project that had
|
|
108
|
+
closed self-registration.
|
|
109
|
+
|
|
110
|
+
**What changes:** every configured provider now receives the flag, so `disableSignUp: true` closes sign-up through
|
|
111
|
+
every social provider as well, unless that provider sets its own `disableSignUp`. A first sign-in through a provider by
|
|
112
|
+
somebody who has no account is refused (the OAuth callback redirects with `error=signup_disabled`, `/sign-in/social`
|
|
113
|
+
with an `idToken` answers 401 `signup disabled`). Users who already have an account keep signing in, also through a
|
|
114
|
+
provider they have not used before: Better-Auth checks the flag only when no user exists for the address.
|
|
115
|
+
|
|
116
|
+
**What to check:** a project that closed sign-up on purpose needs nothing. A project that closed e-mail sign-up but
|
|
117
|
+
wants new users through a provider opens that one deliberately:
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
// config.env.ts
|
|
121
|
+
betterAuth: {
|
|
122
|
+
emailAndPassword: { disableSignUp: true },
|
|
123
|
+
socialProviders: {
|
|
124
|
+
google: { clientId: '...', clientSecret: '...', disableSignUp: false }, // new users through Google
|
|
125
|
+
github: { clientId: '...', clientSecret: '...' }, // follows disableSignUp: closed
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`disableSignUp: true` on a provider closes sign-up for that provider alone, while sign-up stays open elsewhere. Only a
|
|
131
|
+
boolean counts there: any other value, such as the string `"false"` in `NEST_SERVER_CONFIG`, follows
|
|
132
|
+
`emailAndPassword.disableSignUp`. Plugins a project registers itself through `betterAuth.plugins` are not
|
|
133
|
+
covered; set their own sign-up options (`magicLink({ disableSignUp: true })`).
|
|
134
|
+
|
|
135
|
+
## Troubleshooting
|
|
136
|
+
|
|
137
|
+
| Symptom | Cause | Fix |
|
|
138
|
+
|---|---|---|
|
|
139
|
+
| 400 `#LTNS_0305` on an IAM request | The path carries a dot segment, a backslash, an encoded separator or a `#` | Fix the client's URL |
|
|
140
|
+
| 429 on sign-in or sign-up earlier than before | The strict routes get half of `betterAuth.rateLimit.max`, and sign-in and sign-up share one counter (§2) | Raise `betterAuth.rateLimit.max` |
|
|
141
|
+
| New users land on the error page with `error=signup_disabled` after a social login | `disableSignUp: true` covers social providers (§3) | Expected; or set `disableSignUp: false` on the provider |
|
|
142
|
+
| A project test fails with `SIGNUP_FAILED` | Its stub of `CoreBetterAuthService` has no `isPersistedUser` (§1) | Add `isPersistedUser: async () => true` to the stub |
|
|
143
|
+
|
|
144
|
+
## References
|
|
145
|
+
|
|
146
|
+
- `src/core/modules/better-auth/core-better-auth.service.ts`: `isPersistedUser()`
|
|
147
|
+
- `src/core/modules/better-auth/core-better-auth.controller.ts`, `core-better-auth.resolver.ts`,
|
|
148
|
+
`src/core/modules/auth/services/core-auth.service.ts`: the sign-up paths
|
|
149
|
+
- `src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts`, `core-better-auth-rate-limiter.service.ts`
|
|
150
|
+
- `src/core/modules/better-auth/better-auth.config.ts`: `buildSocialProviders()`
|
|
151
|
+
- `src/core/modules/better-auth/README.md`, `INTEGRATION-CHECKLIST.md`
|
|
152
|
+
- `.claude/rules/better-auth.md`: security checklist
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Migration Guide: 11.44.1 → 11.44.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
|
+
11.44.2 is a security patch for 11.44.1 (`latest-11`). The same fixes ship in 12.8.2 (`latest`) and 12.6.7 (`latest-12.6`).
|
|
13
|
+
|
|
14
|
+
## Quick Migration
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pnpm add @lenne.tech/nest-server@11.44.2
|
|
18
|
+
pnpm run update # nest-server-starter based projects (release/11.x)
|
|
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 11.44.0 → 11.44.1) 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 11.44.1 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": "11.44.
|
|
3
|
+
"version": "11.44.2",
|
|
4
4
|
"description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"node",
|
package/src/config.env.ts
CHANGED
|
@@ -59,7 +59,9 @@ const config: { [env: string]: IServerOptions } = {
|
|
|
59
59
|
rpId: 'localhost',
|
|
60
60
|
rpName: 'Nest Server Local',
|
|
61
61
|
},
|
|
62
|
-
|
|
62
|
+
// 200: sign-in and sign-up get the strict half (100), the headroom the suites had while the limiter
|
|
63
|
+
// counted every IAM request of a client on one shared counter of 100
|
|
64
|
+
rateLimit: { enabled: true, max: 200, windowSeconds: 60 },
|
|
63
65
|
secret: process.env.BETTER_AUTH_SECRET || 'BETTER_AUTH_SECRET_LOCAL_32_CHARS_M',
|
|
64
66
|
// Social providers disabled in local environment (no credentials)
|
|
65
67
|
socialProviders: {
|
|
@@ -368,7 +370,9 @@ const config: { [env: string]: IServerOptions } = {
|
|
|
368
370
|
rpId: 'localhost',
|
|
369
371
|
rpName: 'Nest Server Local',
|
|
370
372
|
},
|
|
371
|
-
|
|
373
|
+
// 200: sign-in and sign-up get the strict half (100), the headroom the suites had while the limiter
|
|
374
|
+
// counted every IAM request of a client on one shared counter of 100
|
|
375
|
+
rateLimit: { enabled: true, max: 200, windowSeconds: 60 },
|
|
372
376
|
secret: process.env.BETTER_AUTH_SECRET || 'BETTER_AUTH_SECRET_LOCAL_32_CHARS_M',
|
|
373
377
|
// Social providers disabled in local environment (no credentials)
|
|
374
378
|
socialProviders: {
|
|
@@ -978,6 +978,17 @@ export interface IBetterAuthSocialProvider {
|
|
|
978
978
|
*/
|
|
979
979
|
clientSecret: string;
|
|
980
980
|
|
|
981
|
+
/**
|
|
982
|
+
* Whether a first sign-in through this provider may create an account.
|
|
983
|
+
*
|
|
984
|
+
* Unset, the provider follows `betterAuth.emailAndPassword.disableSignUp`: with that set to `true` (since 12.3.0)
|
|
985
|
+
* nobody gets a new account through any provider, while existing users keep signing in. `false` opens sign-up
|
|
986
|
+
* through this provider although `disableSignUp` closes it otherwise; `true` closes it for this provider alone.
|
|
987
|
+
* Only a boolean counts: any other value follows `emailAndPassword.disableSignUp`.
|
|
988
|
+
* @default emailAndPassword.disableSignUp
|
|
989
|
+
*/
|
|
990
|
+
disableSignUp?: boolean;
|
|
991
|
+
|
|
981
992
|
/**
|
|
982
993
|
* Whether this provider is enabled.
|
|
983
994
|
* Defaults to true when clientId and clientSecret are provided.
|
|
@@ -4198,6 +4209,11 @@ interface IBetterAuthBase {
|
|
|
4198
4209
|
* Disable user registration (sign-up) via BetterAuth.
|
|
4199
4210
|
* Passed through to better-auth's native emailAndPassword.disableSignUp.
|
|
4200
4211
|
* Custom endpoints (GraphQL + REST) also check this flag early.
|
|
4212
|
+
* Since 11.44.1 (12.3.0 on 12.x) it closes social sign-up too: every configured social provider receives it as its own
|
|
4213
|
+
* `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
|
|
4214
|
+
* signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
|
|
4215
|
+
* registers itself through `plugins` are not covered; they need their own sign-up option
|
|
4216
|
+
* (`magicLink({ disableSignUp: true })`).
|
|
4201
4217
|
* The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
|
|
4202
4218
|
* which would answer `SIGNUP_DISABLED` to every caller.
|
|
4203
4219
|
* @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 (11.44.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,
|
|
@@ -448,6 +448,9 @@ After integration, verify:
|
|
|
448
448
|
- [ ] GraphQL `betterAuthSignUp` returns error `LTNS_0026`
|
|
449
449
|
- [ ] `GET /iam/features` reports `signUpEnabled: false`
|
|
450
450
|
- [ ] Sign-in still works for existing users
|
|
451
|
+
- [ ] With a social provider: a first social sign-in of an unknown user creates no account (`error=signup_disabled`),
|
|
452
|
+
an existing user still signs in through it. A provider meant for self-registration carries
|
|
453
|
+
`disableSignUp: false` (11.44.1+)
|
|
451
454
|
|
|
452
455
|
### Additional checks for Migration scenario:
|
|
453
456
|
|
|
@@ -622,13 +622,31 @@ When disabled:
|
|
|
622
622
|
- REST `POST /iam/sign-up/email` returns `400 Bad Request` with error `LTNS_0026`
|
|
623
623
|
- GraphQL `betterAuthSignUp` mutation returns error `LTNS_0026`
|
|
624
624
|
- `betterAuthFeatures` reports `signUpEnabled: false`
|
|
625
|
-
-
|
|
625
|
+
- A first sign-in through a social provider creates no account (since 11.44.1, 12.3.0 on 12.x): the OAuth callback redirects with
|
|
626
|
+
`error=signup_disabled`, `/sign-in/social` with an `idToken` answers 401 `signup disabled`
|
|
627
|
+
- Sign-in continues to work for existing users, through e-mail and every social provider
|
|
626
628
|
|
|
627
629
|
**Defense in Depth:** The flag is enforced at two layers:
|
|
628
630
|
|
|
629
631
|
1. **Custom check** (`CoreBetterAuthService.ensureSignUpEnabled()`) runs in Controller/Resolver _before_ any BetterAuth API call and returns a structured `LTNS_0026` error.
|
|
630
632
|
2. **Native BetterAuth** `emailAndPassword.disableSignUp` acts as a safety net for any direct API access that bypasses the custom check.
|
|
631
633
|
|
|
634
|
+
**Social providers:** Better-Auth reads `emailAndPassword.disableSignUp` for `/sign-up/email` only and decides a social
|
|
635
|
+
sign-up per provider, so `buildSocialProviders()` hands every provider the flag as its own `disableSignUp`. One provider
|
|
636
|
+
can deviate on purpose:
|
|
637
|
+
|
|
638
|
+
```typescript
|
|
639
|
+
socialProviders: {
|
|
640
|
+
google: { clientId: '...', clientSecret: '...', disableSignUp: false }, // new users through Google despite the global flag
|
|
641
|
+
github: { clientId: '...', clientSecret: '...', disableSignUp: true }, // closed for GitHub even while sign-up is open
|
|
642
|
+
},
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
Only a boolean counts on the provider; any other value follows `emailAndPassword.disableSignUp`, so a string from
|
|
646
|
+
`NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds itself through `betterAuth.plugins`
|
|
647
|
+
(Generic OAuth, Magic Link, …) are not covered and need their own sign-up options (`magicLink({ disableSignUp: true })`). Before 11.44.1 every provider created
|
|
648
|
+
accounts whatever `disableSignUp` said.
|
|
649
|
+
|
|
632
650
|
**Default:** `false` (sign-up enabled) - fully backward compatible.
|
|
633
651
|
|
|
634
652
|
### Additional User Fields
|
|
@@ -2014,11 +2032,17 @@ When a user is deleted:
|
|
|
2014
2032
|
db.account.findOne({ userId: ObjectId('...'), providerId: 'credential' });
|
|
2015
2033
|
```
|
|
2016
2034
|
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2035
|
+
On better-auth 1.7.3 and later (nest-server requires 1.7.16 or later) that query is the whole
|
|
2036
|
+
check: rows carry no `issuer`, and an `issuer` filter finds nothing for every user — that is
|
|
2037
|
+
expected, not the cause of a 401. Do not write `issuer` fields by hand.
|
|
2038
|
+
|
|
2039
|
+
Only on better-auth 1.7.0–1.7.2 (see [Boot-Time Behaviour](#boot-time-behaviour)) must the row ALSO
|
|
2040
|
+
carry `issuer: 'local:credential'`. There a row matching only `providerId` is not usable — those
|
|
2041
|
+
versions key accounts by `(issuer, accountId)` and will not find it, so sign-in answers 401 while
|
|
2042
|
+
the query above reports that the account exists:
|
|
2020
2043
|
|
|
2021
2044
|
```javascript
|
|
2045
|
+
// better-auth 1.7.0–1.7.2 only
|
|
2022
2046
|
db.account.findOne({ issuer: 'local:credential', providerId: 'credential', userId: ObjectId('...') });
|
|
2023
2047
|
```
|
|
2024
2048
|
|
|
@@ -2172,6 +2196,12 @@ These endpoints bypass rate limiting entirely:
|
|
|
2172
2196
|
- `/session` - Session checks (frequent client-side calls)
|
|
2173
2197
|
- `/callback` - OAuth callbacks
|
|
2174
2198
|
|
|
2199
|
+
Entries match whole path segments of the path the request is served under (dot segments resolved, case-insensitive, as Express routes): `/sign-in` covers
|
|
2200
|
+
`/sign-in/email`, `/session` does not cover `/sessions-export`. A request whose path under the base path carries a
|
|
2201
|
+
`.` or `..` segment (also `%2e`-encoded), a backslash, an encoded `/` or `\`, or a `#` is refused with 400
|
|
2202
|
+
(`#LTNS_0305: Invalid request path`) before the limiter runs — no route needs such a path, and the limiter and
|
|
2203
|
+
Better-Auth would otherwise read it as two different routes.
|
|
2204
|
+
|
|
2175
2205
|
### Response Headers
|
|
2176
2206
|
|
|
2177
2207
|
When rate limiting is enabled, the following headers are added to responses:
|
|
@@ -7,7 +7,7 @@ import * as crypto from 'crypto';
|
|
|
7
7
|
import * as fs from 'fs';
|
|
8
8
|
import * as path from 'path';
|
|
9
9
|
|
|
10
|
-
import { resolveServerUrls, strippedApiHostname } from '../../common/helpers/cookies.helper';
|
|
10
|
+
import { isLocalEnv, resolveServerUrls, strippedApiHostname } from '../../common/helpers/cookies.helper';
|
|
11
11
|
import { revalidateWsConnectionsOf } from '../../common/helpers/graphql-ws-connection.helper';
|
|
12
12
|
import { IBetterAuth, ICorsConfig } from '../../common/interfaces/server-options.interface';
|
|
13
13
|
import { ConfigService } from '../../common/services/config.service';
|
|
@@ -386,6 +386,7 @@ interface PasskeyNormalizationResult {
|
|
|
386
386
|
interface SocialProviderConfig {
|
|
387
387
|
clientId: string;
|
|
388
388
|
clientSecret: string;
|
|
389
|
+
disableSignUp: boolean;
|
|
389
390
|
}
|
|
390
391
|
|
|
391
392
|
/**
|
|
@@ -558,6 +559,15 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
|
|
|
558
559
|
// `Secure` TRANSPORT flag. Only injected on https so http/local and a consumer's
|
|
559
560
|
// own `options.advanced.useSecureCookies` override are left untouched.
|
|
560
561
|
...(secureCookies && { defaultCookieAttributes: { secure: true } }),
|
|
562
|
+
// Better-Auth decides the origin check itself when this is unset: `isTest()` — `NODE_ENV === 'test'` or a
|
|
563
|
+
// truthy `TEST` variable — switches it off, and with it the CSRF check (backward compatibility in
|
|
564
|
+
// origin-check.mjs) and the validation of `callbackURL` / `redirectTo` against `trustedOrigins`. A deployed
|
|
565
|
+
// stage named `test` is exactly that environment, so a password-reset mail carried any `redirectTo` a caller
|
|
566
|
+
// chose — with a valid token, to the caller's page. Pinned for every environment that is not local / ci / e2e
|
|
567
|
+
// (an unknown or missing name included). Those three keep Better-Auth's own decision: vitest sets `TEST=true`,
|
|
568
|
+
// and pinning there would arm the check in every e2e suite of every project at once. A project's own
|
|
569
|
+
// `options.advanced.disableOriginCheck` still wins (see the merge below).
|
|
570
|
+
...(!isLocalEnv(serverEnv) && { disableOriginCheck: false }),
|
|
561
571
|
},
|
|
562
572
|
basePath,
|
|
563
573
|
baseURL: betterAuthBaseUrl,
|
|
@@ -673,10 +683,39 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
|
|
|
673
683
|
const {
|
|
674
684
|
advanced: optionsAdvanced,
|
|
675
685
|
emailAndPassword: optionsEmailAndPassword,
|
|
686
|
+
user: optionsUser,
|
|
676
687
|
...restOptions
|
|
677
688
|
} = config.options as Record<string, unknown>;
|
|
678
689
|
finalConfig = { ...betterAuthConfig, ...restOptions };
|
|
679
690
|
|
|
691
|
+
// `user` is merged, not replaced. A project that sets `options.user` for its own reason (`changeEmail`,
|
|
692
|
+
// `deleteUser`) would otherwise drop `modelName: 'users'` — Better-Auth then reads and writes a `user` collection
|
|
693
|
+
// or table the framework never sees — and every field `additionalUserFields` declares, the `input: false` locks
|
|
694
|
+
// included. The framework's fields win over a project field of the same name; `betterAuth.additionalUserFields` is
|
|
695
|
+
// where a project changes them.
|
|
696
|
+
if (optionsUser && typeof optionsUser === 'object') {
|
|
697
|
+
const baseUser = betterAuthConfig.user as Record<string, unknown>;
|
|
698
|
+
const overrideUser = optionsUser as Record<string, unknown>;
|
|
699
|
+
// Copies, because the lock below writes to them and the project's options may be the frozen configuration
|
|
700
|
+
const projectFields = Object.fromEntries(
|
|
701
|
+
Object.entries((overrideUser.additionalFields as Record<string, unknown> | undefined) ?? {}).map(
|
|
702
|
+
([key, field]) => [key, field && typeof field === 'object' ? { ...field } : field],
|
|
703
|
+
),
|
|
704
|
+
);
|
|
705
|
+
const mergedFields = {
|
|
706
|
+
...projectFields,
|
|
707
|
+
...(baseUser.additionalFields as Record<string, unknown>),
|
|
708
|
+
};
|
|
709
|
+
// A project field under another key may still map to a protected column (`fieldName: 'roles'`)
|
|
710
|
+
lockProtectedColumns(mergedFields as Record<string, { fieldName?: string; input?: boolean }>);
|
|
711
|
+
finalConfig.user = {
|
|
712
|
+
...baseUser,
|
|
713
|
+
...overrideUser,
|
|
714
|
+
additionalFields: mergedFields,
|
|
715
|
+
modelName: overrideUser.modelName ?? baseUser.modelName,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
680
719
|
// `emailAndPassword` needs a DEEP merge, and this one is load-bearing.
|
|
681
720
|
// The block above carries `password: { hash: nativeScryptHash, verify:
|
|
682
721
|
// nativeScryptVerify }` — the hashing every stored credential was created
|
|
@@ -744,6 +783,11 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
|
|
|
744
783
|
| undefined),
|
|
745
784
|
},
|
|
746
785
|
}),
|
|
786
|
+
// An explicitly `undefined` value survives the spread as a present key and hands the decision back to
|
|
787
|
+
// Better-Auth's `isTest()`. Only a value the project actually set overrides the pin.
|
|
788
|
+
disableOriginCheck:
|
|
789
|
+
(optionsAdvanced as Record<string, unknown>).disableOriginCheck ??
|
|
790
|
+
(betterAuthConfig.advanced as Record<string, unknown>).disableOriginCheck,
|
|
747
791
|
};
|
|
748
792
|
}
|
|
749
793
|
} else {
|
|
@@ -1021,9 +1065,16 @@ function serverOnlyPlugin<T extends BetterAuthPlugin>(plugin: T): T {
|
|
|
1021
1065
|
* Builds the social providers configuration object dynamically.
|
|
1022
1066
|
* Iterates over all configured providers and includes those that are enabled
|
|
1023
1067
|
* with valid clientId and clientSecret.
|
|
1068
|
+
*
|
|
1069
|
+
* `emailAndPassword.disableSignUp: true` closes every way to a new account (11.44.1, 12.3.0 on 12.x). Better-Auth reads that flag for
|
|
1070
|
+
* `/sign-up/email` only and decides a social sign-up per provider (`provider.options.disableSignUp`, in the OAuth
|
|
1071
|
+
* callback and in `/sign-in/social` with an `idToken`), so each provider receives it explicitly. A boolean
|
|
1072
|
+
* `disableSignUp` on the provider is the deliberate exception for that provider; any other value follows the global
|
|
1073
|
+
* flag, so a string arriving through `NEST_SERVER_CONFIG` cannot open a closed registration.
|
|
1024
1074
|
*/
|
|
1025
1075
|
function buildSocialProviders(config: IBetterAuth): Record<string, SocialProviderConfig> {
|
|
1026
1076
|
const socialProvidersConfig: Record<string, SocialProviderConfig> = {};
|
|
1077
|
+
const signUpClosed = config.emailAndPassword?.disableSignUp === true;
|
|
1027
1078
|
|
|
1028
1079
|
// Iterate over all configured social providers dynamically
|
|
1029
1080
|
// A provider is enabled by default if it has credentials configured
|
|
@@ -1034,6 +1085,7 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
|
|
|
1034
1085
|
socialProvidersConfig[name] = {
|
|
1035
1086
|
clientId: provider.clientId,
|
|
1036
1087
|
clientSecret: provider.clientSecret,
|
|
1088
|
+
disableSignUp: typeof provider.disableSignUp === 'boolean' ? provider.disableSignUp : signUpClosed,
|
|
1037
1089
|
};
|
|
1038
1090
|
}
|
|
1039
1091
|
}
|
|
@@ -1287,14 +1339,29 @@ function buildUserFields(config: IBetterAuth): Record<string, UserFieldConfig> {
|
|
|
1287
1339
|
// it, e.g. `additionalUserFields: { customRoles: { fieldName: 'roles', input: true } }`. Lock any
|
|
1288
1340
|
// such field too, so no additionalUserFields entry — regardless of its key — can feed client input
|
|
1289
1341
|
// into a protected column.
|
|
1342
|
+
lockProtectedColumns(coreFields);
|
|
1343
|
+
|
|
1344
|
+
return coreFields;
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
/**
|
|
1348
|
+
* Sets `input: false` on every field that feeds a protected column under another key
|
|
1349
|
+
* (`customRoles: { fieldName: 'roles' }`). Used for `additionalUserFields` and for the fields a project passes through
|
|
1350
|
+
* `options.user.additionalFields`, which the `user` merge in createBetterAuthInstance() adds beside the framework's.
|
|
1351
|
+
*/
|
|
1352
|
+
function lockProtectedColumns(fields: Record<string, { fieldName?: string; input?: boolean }>): void {
|
|
1290
1353
|
const protectedColumns = new Set<string>(PROTECTED_INPUT_FALSE_KEYS);
|
|
1291
|
-
for (const [key, field] of Object.entries(
|
|
1292
|
-
if (
|
|
1354
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
1355
|
+
if (
|
|
1356
|
+
field &&
|
|
1357
|
+
typeof field === 'object' &&
|
|
1358
|
+
!protectedColumns.has(key) &&
|
|
1359
|
+
field.fieldName &&
|
|
1360
|
+
protectedColumns.has(field.fieldName)
|
|
1361
|
+
) {
|
|
1293
1362
|
field.input = false;
|
|
1294
1363
|
}
|
|
1295
1364
|
}
|
|
1296
|
-
|
|
1297
|
-
return coreFields;
|
|
1298
1365
|
}
|
|
1299
1366
|
|
|
1300
1367
|
/**
|