@lenne.tech/nest-server 11.44.1 → 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 +10 -0
- package/.claude/rules/configurable-features.md +1 -1
- package/.claude/rules/testing.md +3 -3
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +30 -4
- package/dist/core/modules/better-auth/better-auth.config.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-rate-limit.middleware.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +12 -0
- 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 +2 -0
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +23 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.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/tsconfig.build.tsbuildinfo +1 -1
- package/migration-guides/11.41.7-to-11.41.8.md +1 -1
- package/migration-guides/11.44.0-to-11.44.1.md +2 -2
- package/migration-guides/11.44.1-to-11.44.2.md +125 -0
- package/package.json +1 -1
- package/src/core/common/interfaces/server-options.interface.ts +2 -1
- package/src/core/modules/better-auth/README.md +2 -2
- package/src/core/modules/better-auth/better-auth.config.ts +63 -5
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +18 -1
- package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +23 -0
- package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +44 -3
- package/src/core/modules/user/core-user.service.ts +10 -2
|
@@ -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.
|
|
@@ -129,8 +129,8 @@ betterAuth: {
|
|
|
129
129
|
|
|
130
130
|
`disableSignUp: true` on a provider closes sign-up for that provider alone, while sign-up stays open elsewhere. Only a
|
|
131
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.
|
|
133
|
-
covered; set their own sign-up options.
|
|
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
134
|
|
|
135
135
|
## Troubleshooting
|
|
136
136
|
|
|
@@ -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",
|
|
@@ -4212,7 +4212,8 @@ interface IBetterAuthBase {
|
|
|
4212
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
4213
|
* `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
|
|
4214
4214
|
* signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
|
|
4215
|
-
* registers itself through `
|
|
4215
|
+
* registers itself through `plugins` are not covered; they need their own sign-up option
|
|
4216
|
+
* (`magicLink({ disableSignUp: true })`).
|
|
4216
4217
|
* The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
|
|
4217
4218
|
* which would answer `SIGNUP_DISABLED` to every caller.
|
|
4218
4219
|
* @default false
|
|
@@ -643,8 +643,8 @@ socialProviders: {
|
|
|
643
643
|
```
|
|
644
644
|
|
|
645
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.
|
|
647
|
-
(Generic OAuth, Magic Link, …) are not covered and need their own sign-up options. Before 11.44.1 every provider created
|
|
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
648
|
accounts whatever `disableSignUp` said.
|
|
649
649
|
|
|
650
650
|
**Default:** `false` (sign-up enabled) - fully backward compatible.
|
|
@@ -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';
|
|
@@ -559,6 +559,15 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
|
|
|
559
559
|
// `Secure` TRANSPORT flag. Only injected on https so http/local and a consumer's
|
|
560
560
|
// own `options.advanced.useSecureCookies` override are left untouched.
|
|
561
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 }),
|
|
562
571
|
},
|
|
563
572
|
basePath,
|
|
564
573
|
baseURL: betterAuthBaseUrl,
|
|
@@ -674,10 +683,39 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
|
|
|
674
683
|
const {
|
|
675
684
|
advanced: optionsAdvanced,
|
|
676
685
|
emailAndPassword: optionsEmailAndPassword,
|
|
686
|
+
user: optionsUser,
|
|
677
687
|
...restOptions
|
|
678
688
|
} = config.options as Record<string, unknown>;
|
|
679
689
|
finalConfig = { ...betterAuthConfig, ...restOptions };
|
|
680
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
|
+
|
|
681
719
|
// `emailAndPassword` needs a DEEP merge, and this one is load-bearing.
|
|
682
720
|
// The block above carries `password: { hash: nativeScryptHash, verify:
|
|
683
721
|
// nativeScryptVerify }` — the hashing every stored credential was created
|
|
@@ -745,6 +783,11 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
|
|
|
745
783
|
| undefined),
|
|
746
784
|
},
|
|
747
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,
|
|
748
791
|
};
|
|
749
792
|
}
|
|
750
793
|
} else {
|
|
@@ -1296,14 +1339,29 @@ function buildUserFields(config: IBetterAuth): Record<string, UserFieldConfig> {
|
|
|
1296
1339
|
// it, e.g. `additionalUserFields: { customRoles: { fieldName: 'roles', input: true } }`. Lock any
|
|
1297
1340
|
// such field too, so no additionalUserFields entry — regardless of its key — can feed client input
|
|
1298
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 {
|
|
1299
1353
|
const protectedColumns = new Set<string>(PROTECTED_INPUT_FALSE_KEYS);
|
|
1300
|
-
for (const [key, field] of Object.entries(
|
|
1301
|
-
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
|
+
) {
|
|
1302
1362
|
field.input = false;
|
|
1303
1363
|
}
|
|
1304
1364
|
}
|
|
1305
|
-
|
|
1306
|
-
return coreFields;
|
|
1307
1365
|
}
|
|
1308
1366
|
|
|
1309
1367
|
/**
|
|
@@ -619,6 +619,16 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
619
619
|
return Math.max(1, Math.round(resolved / 60));
|
|
620
620
|
}
|
|
621
621
|
|
|
622
|
+
/**
|
|
623
|
+
* Whether the project switched Better-Auth's origin check off (`betterAuth.options.advanced.disableOriginCheck`):
|
|
624
|
+
* `true`, or a list of paths, which may name the reset route. The framework itself pins `false` (11.44.2), so only a
|
|
625
|
+
* project's own value counts here.
|
|
626
|
+
*/
|
|
627
|
+
protected isOriginCheckDisabled(): boolean {
|
|
628
|
+
const raw = this.configService.getFastButReadOnly<unknown>('betterAuth.options.advanced.disableOriginCheck');
|
|
629
|
+
return raw === true || Array.isArray(raw);
|
|
630
|
+
}
|
|
631
|
+
|
|
622
632
|
protected buildPasswordResetUrl(options: SendPasswordResetEmailOptions): string {
|
|
623
633
|
const configured = this.config.passwordResetLink;
|
|
624
634
|
|
|
@@ -633,7 +643,9 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
633
643
|
// `nuxt-base-starter` sends it on every request (`forgot-password.vue` →
|
|
634
644
|
// `requestPasswordReset({ email, redirectTo: appUrl('/auth/reset-password', siteUrl) })`), and
|
|
635
645
|
// a client that names its page is a better authority on that page than a framework default.
|
|
636
|
-
|
|
646
|
+
// Only while Better-Auth's origin check validated it (see readCallbackUrlFromBetterAuthLink): a project that
|
|
647
|
+
// switched the check off gets the default page, never an unvalidated URL with a valid token in it.
|
|
648
|
+
if (!target && !this.isOriginCheckDisabled()) {
|
|
637
649
|
target = this.readCallbackUrlFromBetterAuthLink(options.url);
|
|
638
650
|
}
|
|
639
651
|
|
|
@@ -687,6 +699,11 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
687
699
|
* knowing before anyone widens it. `cors.allowAll` does not widen it (an origin check has no
|
|
688
700
|
* "allow everything" mode), but an over-broad `allowedOrigins` would.
|
|
689
701
|
*
|
|
702
|
+
* And it makes the origin check itself load-bearing. Until 11.44.2 Better-Auth switched it off on its
|
|
703
|
+
* own under `NODE_ENV=test` (`isTest()`), which is a deployed stage in starter-based projects; the
|
|
704
|
+
* framework now pins `advanced.disableOriginCheck: false`. A project that switches it off itself
|
|
705
|
+
* gets no caller URL here at all ({@link isOriginCheckDisabled}).
|
|
706
|
+
*
|
|
690
707
|
* Returns `undefined` for anything unparseable or absent, so the caller falls through to its own
|
|
691
708
|
* resolution rather than to a half-formed URL.
|
|
692
709
|
*/
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
|
|
2
2
|
import { NextFunction, Request, Response } from 'express';
|
|
3
3
|
|
|
4
|
+
import { CONTROLLER_HANDLED_PATHS } from './core-better-auth-openapi.helper';
|
|
4
5
|
import { CoreBetterAuthRateLimiter, RateLimitResult } from './core-better-auth-rate-limiter.service';
|
|
5
6
|
import { CoreBetterAuthService } from './core-better-auth.service';
|
|
6
7
|
|
|
@@ -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
|
-
*
|
|
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
|
-
//
|
|
331
|
+
// The last segment, when it names a route the base path serves
|
|
303
332
|
const segments = cleanPath.split('/').filter(Boolean);
|
|
304
|
-
|
|
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
|
/**
|
|
@@ -697,8 +697,16 @@ export abstract class CoreUserService<
|
|
|
697
697
|
// Perform the update
|
|
698
698
|
const updatedUser = await super.update(id, input, serviceOptions);
|
|
699
699
|
|
|
700
|
-
// Sync email change to IAM if email was changed and mapper is available
|
|
701
|
-
|
|
700
|
+
// Sync email change to IAM if email was changed and mapper is available. Compared the way the address is stored
|
|
701
|
+
// (trimmed, lower case): `Foo@Example.com` for `foo@example.com` changes nothing, and the sync would end every
|
|
702
|
+
// session of the account for it.
|
|
703
|
+
const normalizeEmail = (value: unknown) => (typeof value === 'string' ? value.trim().toLowerCase() : value);
|
|
704
|
+
if (
|
|
705
|
+
this.options?.betterAuthUserMapper &&
|
|
706
|
+
oldEmail &&
|
|
707
|
+
input.email &&
|
|
708
|
+
normalizeEmail(oldEmail) !== normalizeEmail(input.email)
|
|
709
|
+
) {
|
|
702
710
|
try {
|
|
703
711
|
await this.options.betterAuthUserMapper.syncEmailChangeFromLegacy(oldEmail, input.email);
|
|
704
712
|
this.userServiceLogger.debug(`Synced email change from Legacy to IAM: ${oldEmail} → ${input.email}`);
|