@lenne.tech/nest-server 11.28.1 → 11.29.0

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.
@@ -528,6 +528,18 @@ Authenticates the request using three strategies in priority order:
528
528
 
529
529
  If authentication succeeds, `req.user` is set with the authenticated user (including `hasRole()` method).
530
530
 
531
+ > **Native `/iam/*` routes bypass the `@Roles()`/`checkRoles` layer.** Better-Auth's own endpoints
532
+ > (e.g. `POST /iam/update-user`, `POST /iam/sign-up/email`) that are **not** in
533
+ > `CONTROLLER_HANDLED_PATHS` are forwarded raw by `CoreBetterAuthApiMiddleware` to Better-Auth's
534
+ > native handler under its `sessionMiddleware` — i.e. reachable by **any authenticated user**,
535
+ > independent of the controller's class-level `@Roles(ADMIN)` and nest-server's `checkRoles`. This is
536
+ > why server-managed user fields (`roles`, `verified`, `verifiedAt`, `twoFactorEnabled`, `iamId`) are
537
+ > locked at the Better-Auth schema layer with `input: false` (see `betterAuth.additionalUserFields[].input`
538
+ > in `.claude/rules/configurable-features.md` and `.claude/rules/better-auth.md` §2): field-level
539
+ > input rejection is the correct control here because the guard layer does not run on these
540
+ > raw-forwarded routes. A forged `POST /iam/update-user {"roles":["admin"]}` is rejected with
541
+ > `FIELD_NOT_ALLOWED` (HTTP 400) at the input-parse stage, before any persistence.
542
+
531
543
  #### 3. graphqlUploadExpress
532
544
 
533
545
  Only for GraphQL routes. Handles multipart file upload requests according to the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec).
@@ -0,0 +1,231 @@
1
+ # Migration Guide: 11.28.1 → 11.29.0
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |----------|---------|
7
+ | **Breaking Changes** | Server-managed Better-Auth user fields (`roles`, `verified`, `verifiedAt`, `twoFactorEnabled`, `iamId`, and by default `termsAndPrivacyAcceptedAt`) are now registered with `input: false`, so Better-Auth's **native** input parsing rejects client-supplied values. Behavioral change on `POST /iam/update-user` and `POST /iam/sign-up/email`. |
8
+ | **Security Fix** | Closes a confirmed **vertical privilege-escalation** vulnerability (OWASP A01): any authenticated user could self-grant `admin` via `POST /iam/update-user {"roles":["admin"]}`. |
9
+ | **New Features** | New per-field `input?: boolean` option on `IBetterAuthUserField` (`betterAuth.additionalUserFields`) so projects can mark their own fields as server-managed. New parallel-safe e2e test infrastructure (machine-wide run governor, startup sweep, `retry: 2`) — optional adoption, see below. |
10
+ | **Bugfix** | `CoreUserService.create()` now checks email uniqueness at application level (the unique index alone misses duplicates on a fresh database while autoIndex is still building — same window on freshly deployed production DBs). **Behavioral note:** a duplicate email via `userService.create()` now always yields **400 "Email address already in use"** — previously, callers other than `signUp` could see a raw **422 Unprocessable Entity** when the error surfaced as a Mongo duplicate-key error. Adjust tests that asserted the 422. |
11
+ | **Migration Effort** | **~0 minutes for most projects** (`pnpm update`). **Audit required** only if your project relied on client-setting one of the locked fields via the Better-Auth input path — see below. |
12
+
13
+ MINOR was incremented because this repo's scheme treats behavioral/breaking changes as MINOR (MAJOR mirrors the NestJS version, still 11).
14
+
15
+ ---
16
+
17
+ ## Why this change
18
+
19
+ Better-Auth registers `betterAuth.additionalUserFields` as native `additionalFields`, and Better-Auth
20
+ defaults each field to `input: true` — i.e. **client-settable** via `POST /iam/sign-up/email` and
21
+ `POST /iam/update-user`. Critically, `/iam/update-user` is **not** in `CONTROLLER_HANDLED_PATHS`, so
22
+ `CoreBetterAuthApiMiddleware` forwards it raw to Better-Auth's native handler under its
23
+ `sessionMiddleware` — reachable by **any authenticated user**, bypassing the controller's class-level
24
+ `@Roles(ADMIN)` and nest-server's `checkRoles`.
25
+
26
+ Before 11.29.0 the server-managed `roles` field was registered **without** `input: false`. The result:
27
+
28
+ ```http
29
+ POST /iam/update-user
30
+ Authorization: Bearer <any authenticated user's token>
31
+
32
+ { "roles": ["admin"] }
33
+ ```
34
+
35
+ …wrote `roles: ["admin"]` onto the caller's own user row, which then became authoritative for
36
+ `@Restricted(RoleEnum.ADMIN)`. A freshly self-registered user could make themselves admin.
37
+
38
+ ## What changed
39
+
40
+ Server-managed core fields are now registered with `input: false` and **re-asserted after** any
41
+ project `additionalUserFields` are merged, so a project override cannot silently re-open them. The
42
+ security-critical, hard-locked set (`PROTECTED_INPUT_FALSE_KEYS`) is:
43
+
44
+ | Field | Prevented attack |
45
+ |-------|------------------|
46
+ | `roles` | vertical privilege escalation (self-granting `admin`) |
47
+ | `verified` / `verifiedAt` | email-verification bypass |
48
+ | `twoFactorEnabled` | self-toggling the 2FA state |
49
+ | `iamId` | identity / account-linking hijack |
50
+
51
+ The lock is **column-scoped**: a shadow field whose `fieldName` maps to one of these columns
52
+ (e.g. `{ customRoles: { fieldName: 'roles', input: true } }`) is also forced to `input: false`.
53
+
54
+ Runtime behavior after the change:
55
+
56
+ - `POST /iam/update-user {"roles":[...]}` (or `verified`, etc.) → **`FIELD_NOT_ALLOWED` (HTTP 400)**.
57
+ - `POST /iam/sign-up/email {"roles":[...]}` → account created with the **server default** (`roles: []`);
58
+ the forged value is silently dropped, not persisted.
59
+ - `termsAndPrivacyAcceptedAt` is `input: false` by **default** but is intentionally **not** in the
60
+ hard-lock set (it is a consent timestamp, not a privilege boundary) — a project may re-open it with
61
+ `additionalUserFields: { termsAndPrivacyAcceptedAt: { type: 'date', input: true } }`.
62
+
63
+ **Unaffected:** nest-server's own role-assignment path — `UserService.setRoles`,
64
+ `CrudService.update` (via `checkRoles`), and the Better-Auth user mapper's native `$set` writes — does
65
+ **not** use Better-Auth input parsing and keeps working exactly as before. `input: false` only gates
66
+ the Better-Auth native sign-up/update-user routes.
67
+
68
+ ---
69
+
70
+ ## Quick Migration (npm mode)
71
+
72
+ For the overwhelming majority of projects, **no code change is required**:
73
+
74
+ ```bash
75
+ pnpm add @lenne.tech/nest-server@11.29.0
76
+ pnpm run build
77
+ pnpm test
78
+ ```
79
+
80
+ Your existing role assignment (admin panels calling `updateUser`/`setRoles`, sign-up flows,
81
+ verification flows) continues to work — those go through nest-server's service layer, not the
82
+ Better-Auth native input path.
83
+
84
+ ---
85
+
86
+ ## New: Parallel-Safe e2e Test Infrastructure (Optional Adoption)
87
+
88
+ This release also overhauls the e2e test infrastructure so that MANY parallel sessions
89
+ (`lt ticket` worktrees, several projects, agent sessions) can run test suites on one machine
90
+ without starving each other or leaving database garbage behind. **These are repository files, not
91
+ npm-package code** — `pnpm update` does NOT bring them into your project. Adopt them by syncing the
92
+ test files from [nest-server-starter](https://github.com/lenneTech/nest-server-starter) (or via the
93
+ lt-dev fullstack update agent):
94
+
95
+ | File | What it adds |
96
+ |------|--------------|
97
+ | `tests/e2e-run-slots.ts` (new) | **Machine-wide run governor**: at most N concurrent e2e runs across ALL lt projects (slot files in the OS temp dir, PID-liveness crash recovery, fail-open). Knobs: `LT_E2E_MAX_RUNS` (0 disables), `LT_E2E_SLOT_DIR`, `LT_E2E_SLOT_TIMEOUT`. |
98
+ | `tests/global-setup.ts` | **Startup sweep** — stale test DBs of this project AND leftover upload-test artifacts (`tests/*.txt` / `*.bin` from aborted file-upload specs) are removed when the next run STARTS, so cleanup survives SIGKILL (watchdog) and `--reporter` CLI overrides; then acquires a governor slot. |
99
+ | `tests/db-lifecycle.reporter.ts` | Exports the shared `isStaleTestDb()` predicate used by the sweep; failure message now points to the startup-sweep semantics. |
100
+ | `vitest-e2e.config.ts` | Auto low-resource mode when **another e2e run is active** (deterministic slot signal — the 1-minute load average structurally lags short runs) or load is high; **`retry: 2`** (a higher retry turns one broken spec file into an hour-long 0%-CPU grind that looks like a deadlock). |
101
+ | `tests/unit/e2e-run-slots.spec.ts` (new) | Unit tests for the governor. |
102
+
103
+ Measured effect (12-core machine): two overlapping full-speed runs previously drove load to 30 with
104
+ spurious 401 failures; with the governor, 6 parallel project checks all pass in 109–125s. A run
105
+ printing `[e2e-governor] waiting for a free e2e slot` every 15s is **queued, not hung**.
106
+
107
+ Rule carried over from the reporter docs: specs that need an extra database must derive it via
108
+ `deriveTestDbUri('<suffix>')` — never a hardcoded or `Date.now()`-based name — and drop their DB
109
+ **after** `app.close()` (async module init can re-create a database dropped while the app is alive).
110
+
111
+ **Related: `scripts/check.mjs` (canonical version distributed by the lt CLI).** The report-driven
112
+ check wrapper gained the same robustness set across all lt base repos: an **idle-watchdog** that
113
+ kills a test step after 300s of silence and diagnoses it as a hang (`CHECK_IDLE_TIMEOUT` /
114
+ `--idle-timeout=<s>`, 0 disables), whole-process-tree kills (no orphaned fork workers), a
115
+ SIGTERM/SIGKILL exit hint (a killed step is not an assertion failure), summed vitest metrics
116
+ (unit + e2e runs are no longer under-reported), and the audit rendered like every other step.
117
+ Consumer projects receive it via `lt fullstack update` (self-heal; skips a `scripts/check.mjs`
118
+ with uncommitted local edits) — `lt dev doctor` warns when the local copy drifts from the
119
+ canonical version.
120
+
121
+ ---
122
+
123
+ ## Audit Before Upgrading
124
+
125
+ > **Mirrors the v11.28.x precedent in [`.claude/rules/role-system.md`](../.claude/rules/role-system.md)
126
+ > ("Audit every `S_SELF`/`S_CREATOR` on an input type before upgrading").**
127
+
128
+ You only need to act if **both** are true for your project:
129
+
130
+ 1. You send `roles`, `verified`, `verifiedAt`, `twoFactorEnabled`, `iamId` (or
131
+ `termsAndPrivacyAcceptedAt`) in the **body of `POST /iam/update-user` or `POST /iam/sign-up/email`**
132
+ (i.e. through Better-Auth's native input path), **and**
133
+ 2. You expected that value to be persisted.
134
+
135
+ If so, those requests will now receive `400 FIELD_NOT_ALLOWED` (update-user) or silently get the
136
+ server default (sign-up). **Move the assignment to the correct server-side path:**
137
+
138
+ ```typescript
139
+ // BEFORE (relied on Better-Auth native input — now rejected):
140
+ // POST /iam/update-user { "roles": ["admin"] }
141
+
142
+ // AFTER — assign roles through nest-server's service layer (authorized + audited):
143
+ await this.userService.setRoles(userId, [RoleEnum.ADMIN]);
144
+ // or, from an admin-driven update that runs checkRoles:
145
+ await this.userService.update(userId, { roles: [RoleEnum.ADMIN] }, { currentUser: adminUser });
146
+ ```
147
+
148
+ If you deliberately need one of your **own** `additionalUserFields` to be server-managed, set
149
+ `input: false` on it:
150
+
151
+ ```typescript
152
+ betterAuth: {
153
+ additionalUserFields: {
154
+ internalScore: { type: 'number', defaultValue: 0, input: false }, // rejects client input
155
+ },
156
+ }
157
+ ```
158
+
159
+ **Note:** You cannot re-open a hard-locked key (`roles`, `verified`, `verifiedAt`, `twoFactorEnabled`,
160
+ `iamId`) via `additionalUserFields` — the re-assertion re-locks it by design. This is intentional and
161
+ is the security guarantee of this release.
162
+
163
+ ---
164
+
165
+ ## Compatibility Notes
166
+
167
+ | Pattern | Status |
168
+ |---------|--------|
169
+ | Admin panel updating roles via `UserService`/`CrudService`/GraphQL `updateUser` | ✅ Unaffected — service layer, not Better-Auth input |
170
+ | Sign-up / email verification / 2FA enable-disable flows | ✅ Unaffected — server-managed |
171
+ | Reading `roles`/`verified` in responses | ✅ Unaffected — `input: false` only gates writes |
172
+ | Client sending `roles`/`verified` in `/iam/update-user` or `/iam/sign-up/email` body | ⚠️ Now rejected/dropped — this was the vulnerability |
173
+ | Custom `additionalUserFields` (non-protected keys) | ✅ Unaffected — still client-settable unless you set `input: false` |
174
+
175
+ ### Toolchain: `engines.pnpm` now advertised
176
+
177
+ `package.json` now declares `engines.pnpm: "^11.0.0"` (and drops the repo-internal `packageManager`
178
+ pin). Impact on consumers is **low and pnpm-only**:
179
+
180
+ - **npm / yarn consumers:** unaffected — they ignore `engines.pnpm`.
181
+ - **pnpm consumers on pnpm ≥ 11:** unaffected.
182
+ - **pnpm consumers on pnpm < 11:** you may see an `EBADENGINE` / `ERR_PNPM_UNSUPPORTED_ENGINE`
183
+ **warning** on install (a hard error only if you run with `engine-strict=true`). Upgrade to pnpm 11
184
+ (`corepack use pnpm@11` or `npm i -g pnpm@11`) to silence it. The framework's runtime does not
185
+ depend on pnpm — this only concerns the install step for pnpm-based projects.
186
+
187
+ No `engines.node` change (still `>= 22`).
188
+
189
+ ### Vendor-mode consumers (`src/core/` copied into your project)
190
+
191
+ This release touches only `src/core/modules/better-auth/better-auth.config.ts`,
192
+ `src/core/common/interfaces/server-options.interface.ts` and
193
+ `src/core/modules/user/core-user.service.ts` (bugfix: application-level email-uniqueness check in
194
+ `create()` — the unique index alone misses duplicates on a fresh database while autoIndex is still
195
+ building; raw Mongo duplicate-key errors now also map to the correct "Email address already in use"
196
+ message) — no new files, no new imports, no new runtime dependencies. After syncing `src/core/` (via `/lt-dev:backend:update-nest-server-core` /
197
+ `lt-dev:nest-server-core-updater`), no additional package or config work is required. Run your
198
+ Better-Auth tests to confirm.
199
+
200
+ ---
201
+
202
+ ## Troubleshooting
203
+
204
+ ### A client integration started getting `400 FIELD_NOT_ALLOWED` on `/iam/update-user`
205
+
206
+ Working as intended. The client was setting a server-managed field (`roles`/`verified`/…) through the
207
+ Better-Auth native input path. Move that assignment to the server (`UserService.setRoles` /
208
+ `CrudService.update` with an authorized `currentUser`), or — for your own field — decide whether it
209
+ should really be `input: false`.
210
+
211
+ ### A user's `roles` no longer update after sign-up
212
+
213
+ If you relied on passing `roles` in the sign-up body, that value is now dropped (server default
214
+ applied). Assign roles explicitly after account creation via `UserService.setRoles`, or through your
215
+ admin-provisioning flow.
216
+
217
+ ### I need one of my own additional fields to reject client input
218
+
219
+ Add `input: false` to it in `betterAuth.additionalUserFields`. See the "Audit" section above.
220
+
221
+ ---
222
+
223
+ ## References
224
+
225
+ - [Role System — S_ roles, 401/403 policy, S_SELF/S_CREATOR ownership](../.claude/rules/role-system.md)
226
+ - [Better-Auth Module Rules — §2 server-managed fields must be `input: false`](../.claude/rules/better-auth.md)
227
+ - [Configurable Features — BetterAuth Server-Managed User Fields](../.claude/rules/configurable-features.md)
228
+ - [Request Lifecycle — native `/iam/*` routes bypass the guard layer](../docs/REQUEST-LIFECYCLE.md)
229
+ - Regression test: `tests/stories/better-auth-privilege-escalation.e2e-spec.ts`
230
+ - [Migration Guide 11.28.0 → 11.28.1](./11.28.0-to-11.28.1.md) — previous release
231
+ - [nest-server-starter](https://github.com/lenneTech/nest-server-starter) (reference implementation)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.28.1",
3
+ "version": "11.29.0",
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",
@@ -23,9 +23,10 @@
23
23
  "build:dev": "pnpm run build",
24
24
  "c": "pnpm run check",
25
25
  "check": "node scripts/check.mjs",
26
- "check:raw": "pnpm audit && pnpm run format:check && pnpm run lint && pnpm run check:swc-tdz && pnpm test && pnpm run build && bash scripts/check-server-start.sh",
27
- "check:fix": "pnpm install && pnpm audit --fix && pnpm run format && pnpm run lint:fix && pnpm run check:swc-tdz && pnpm test && pnpm run build && bash scripts/check-server-start.sh",
28
- "check:naf": "pnpm install && pnpm run format && pnpm run lint:fix && pnpm run check:swc-tdz && pnpm test && pnpm run build && bash scripts/check-server-start.sh",
26
+ "check:raw": "pnpm install --frozen-lockfile && pnpm audit && pnpm run format:check && pnpm run lint && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && bash scripts/check-server-start.sh",
27
+ "check:fix": "pnpm install && pnpm audit --fix && pnpm run format && pnpm run lint:fix && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && bash scripts/check-server-start.sh",
28
+ "check:naf": "pnpm install && pnpm run format && pnpm run lint:fix && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && bash scripts/check-server-start.sh",
29
+ "check:manifest": "node scripts/check-package-manifest.mjs",
29
30
  "check:swc-tdz": "nest build -b swc -p tsconfig.swc-tdz.json && node scripts/check-swc-tdz.mjs",
30
31
  "cf": "pnpm run check:fix",
31
32
  "cnaf": "pnpm run check:naf",
@@ -75,7 +76,8 @@
75
76
  "url": "https://github.com/lenneTech/nest-server/issues"
76
77
  },
77
78
  "engines": {
78
- "node": ">= 22"
79
+ "node": ">= 22",
80
+ "pnpm": "^11.0.0"
79
81
  },
80
82
  "dependencies": {
81
83
  "@apollo/server": "5.5.1",
@@ -187,6 +189,5 @@
187
189
  ],
188
190
  "watch": {
189
191
  "build:dev": "src"
190
- },
191
- "packageManager": "pnpm@11.13.0"
192
+ }
192
193
  }
@@ -727,6 +727,18 @@ export interface IBetterAuthUserField {
727
727
  */
728
728
  fieldName?: string;
729
729
 
730
+ /**
731
+ * Whether a client may supply this field's value via Better-Auth's native input parsing
732
+ * (sign-up create / update-user).
733
+ *
734
+ * When `false`, Better-Auth rejects client-supplied values: it throws `FIELD_NOT_ALLOWED`
735
+ * on the update-user route and silently substitutes the server-side default on sign-up.
736
+ * Use this to mark server-managed fields that must never be set from client input.
737
+ *
738
+ * @default true (Better-Auth default when omitted)
739
+ */
740
+ input?: boolean;
741
+
730
742
  /**
731
743
  * Whether this field is required
732
744
  */
@@ -641,6 +641,8 @@ const config = {
641
641
  department: { type: 'string', required: true },
642
642
  preferences: { type: 'string', defaultValue: '{}' },
643
643
  isActive: { type: 'boolean', defaultValue: true },
644
+ // Server-managed field: reject any client-supplied value (sign-up / update-user)
645
+ internalScore: { type: 'number', defaultValue: 0, input: false },
644
646
  },
645
647
  },
646
648
  };
@@ -648,6 +650,26 @@ const config = {
648
650
 
649
651
  **Available field types:** `'string'`, `'number'`, `'boolean'`, `'date'`, `'json'`, `'string[]'`, `'number[]'`
650
652
 
653
+ **Field options:**
654
+
655
+ | Option | Type | Default | Description |
656
+ | -------------- | ---------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
657
+ | `type` | field type | — | Required. One of the field types above. |
658
+ | `defaultValue` | any | — | Value used when the client does not (or may not) supply one. |
659
+ | `required` | boolean | `false` | Whether the field is required. |
660
+ | `input` | boolean | `true` (Better-Auth default) | When `false`, Better-Auth rejects client-supplied values: it throws `FIELD_NOT_ALLOWED` (HTTP 400) on `POST /iam/update-user` and substitutes the server default on sign-up. Use it to mark **server-managed** fields that must never be set from client input. |
661
+
662
+ > **⚠️ Security — server-managed core fields are hard-locked.** The core fields `roles`, `verified`,
663
+ > `verifiedAt`, `twoFactorEnabled` and `iamId` are registered with `input: false` and **re-asserted
664
+ > after** your `additionalUserFields` are merged, so a project override **cannot** re-open them for
665
+ > client input. This closes a vertical privilege-escalation path (a client can no longer self-grant
666
+ > `roles: ['admin']`, self-verify, or toggle 2FA via `POST /iam/update-user`). The lock also applies
667
+ > to any shadow field whose `fieldName` maps to one of those columns. `roles`/`verified` etc. are
668
+ > still assigned server-side through nest-server's own service layer (`UserService.setRoles`,
669
+ > `CrudService.update` with `checkRoles`) — that path does not use Better-Auth input parsing and is
670
+ > unaffected. (`termsAndPrivacyAcceptedAt` is `input: false` by default but is intentionally NOT
671
+ > hard-locked — it is a consent timestamp, not a privilege boundary, so a project may re-open it.)
672
+
651
673
  ### Module Integration (Recommended Pattern)
652
674
 
653
675
  By default (`autoRegister: false`), projects integrate BetterAuth via an **extended module** in their project. This follows the same pattern as Legacy Auth and allows for custom resolvers, controllers, and project-specific authentication logic.
@@ -275,6 +275,14 @@ interface SocialProviderConfig {
275
275
  interface UserFieldConfig {
276
276
  defaultValue?: unknown;
277
277
  fieldName?: string;
278
+ /**
279
+ * Whether a client may supply this field's value via Better-Auth's native input parsing
280
+ * (sign-up create / update-user). When `false`, Better-Auth rejects client-supplied values
281
+ * (throws FIELD_NOT_ALLOWED on update, silently substitutes the server default on create).
282
+ * Defaults to `true` in Better-Auth when omitted. Used to lock server-managed fields
283
+ * (e.g. `roles`) so authenticated users cannot self-set them.
284
+ */
285
+ input?: boolean;
278
286
  required?: boolean;
279
287
  type: BetterAuthFieldType;
280
288
  }
@@ -808,6 +816,28 @@ export function buildTrustedOrigins(
808
816
  return undefined;
809
817
  }
810
818
 
819
+ /**
820
+ * Server-managed, security-critical user fields whose `input: false` MUST be re-asserted after
821
+ * merging project-supplied `additionalUserFields`, so a project override cannot silently re-open
822
+ * a protected key. Each of these, if client-settable, is a concrete vulnerability:
823
+ *
824
+ * - `roles` → vertical privilege escalation (self-granting `admin`)
825
+ * - `verified` → email-verification bypass
826
+ * - `verifiedAt` → email-verification bypass
827
+ * - `twoFactorEnabled` → self-toggling the 2FA state
828
+ * - `iamId` → identity / account-linking hijack
829
+ *
830
+ * Note: `termsAndPrivacyAcceptedAt` is server-managed by default (input:false above) but is
831
+ * intentionally NOT hard-locked here — a project may legitimately choose to accept a client-set
832
+ * consent timestamp; it is not a privilege boundary.
833
+ *
834
+ * These protections only concern Better-Auth's native input parsing (sign-up / update-user).
835
+ * nest-server's own role assignment (UserService/CrudService `checkRoles` + Mongoose writes,
836
+ * `setRoles`, and the user mapper's native `$set` writes) does NOT use Better-Auth input parsing
837
+ * and is therefore unaffected by `input: false`.
838
+ */
839
+ const PROTECTED_INPUT_FALSE_KEYS = ['iamId', 'roles', 'twoFactorEnabled', 'verified', 'verifiedAt'] as const;
840
+
811
841
  /**
812
842
  * Builds the user additional fields configuration.
813
843
  * Merges core fields (firstName, lastName, etc.) with custom fields from config.
@@ -824,6 +854,9 @@ function buildUserFields(config: IBetterAuth): Record<string, UserFieldConfig> {
824
854
  iamId: {
825
855
  defaultValue: null,
826
856
  fieldName: 'iamId',
857
+ // Server-managed: linked to the Better-Auth identity by the user mapper (native DB write),
858
+ // never from client input. input:false blocks identity/account-linking hijack.
859
+ input: false,
827
860
  type: 'string',
828
861
  },
829
862
  lastName: {
@@ -834,45 +867,83 @@ function buildUserFields(config: IBetterAuth): Record<string, UserFieldConfig> {
834
867
  roles: {
835
868
  defaultValue: [],
836
869
  fieldName: 'roles',
870
+ // Server-managed: assigned via UserService/CrudService (checkRoles guard) + setRoles,
871
+ // never from client input. input:false blocks vertical privilege escalation
872
+ // (e.g. a self-registered user POSTing {"roles":["admin"]} to /iam/update-user).
873
+ input: false,
837
874
  type: 'string[]',
838
875
  },
839
876
  // Track when terms and privacy policy were accepted (for sign-up checks)
840
877
  termsAndPrivacyAcceptedAt: {
841
878
  defaultValue: null,
842
879
  fieldName: 'termsAndPrivacyAcceptedAt',
880
+ // Server-managed consent timestamp: set by the sign-up flow, not client input.
881
+ input: false,
843
882
  type: 'date',
844
883
  },
845
884
  twoFactorEnabled: {
846
885
  defaultValue: false,
847
886
  fieldName: 'twoFactorEnabled',
887
+ // Server-managed: toggled by the 2FA enable/disable flow, never from client input.
888
+ // input:false blocks self-toggling the 2FA state.
889
+ input: false,
848
890
  type: 'boolean',
849
891
  },
850
892
  verified: {
851
893
  defaultValue: false,
852
894
  fieldName: 'verified',
895
+ // Server-managed: synced from Better-Auth email verification, never from client input.
896
+ // input:false blocks email-verification bypass.
897
+ input: false,
853
898
  type: 'boolean',
854
899
  },
855
900
  // Track when email was verified (synced from Better-Auth)
856
901
  verifiedAt: {
857
902
  defaultValue: null,
858
903
  fieldName: 'verifiedAt',
904
+ // Server-managed: synced from Better-Auth email verification, never from client input.
905
+ // input:false blocks email-verification bypass.
906
+ input: false,
859
907
  type: 'date',
860
908
  },
861
909
  };
862
910
 
863
911
  // Merge with custom additional fields from configuration
864
- // Custom fields can override core fields or add new ones
912
+ // Custom fields can override core fields or add new ones.
913
+ // The `input` flag is carried through so projects can mark their own fields as server-managed.
865
914
  if (config.additionalUserFields) {
866
915
  for (const [key, field] of Object.entries(config.additionalUserFields)) {
867
916
  coreFields[key] = {
868
917
  defaultValue: field.defaultValue,
869
918
  fieldName: field.fieldName || key,
919
+ input: field.input,
870
920
  required: field.required,
871
921
  type: field.type,
872
922
  };
873
923
  }
874
924
  }
875
925
 
926
+ // Security: re-assert input:false on server-managed, security-critical fields AFTER the merge,
927
+ // so a project-supplied additionalUserFields override cannot silently re-open a protected key
928
+ // (privilege escalation, email-verification bypass, 2FA bypass, identity hijack).
929
+ for (const key of PROTECTED_INPUT_FALSE_KEYS) {
930
+ if (coreFields[key]) {
931
+ coreFields[key].input = false;
932
+ }
933
+ }
934
+
935
+ // Security (defense-in-depth): the loop above keys on the well-known object key. A project could
936
+ // still reopen a protected COLUMN by registering a shadow field under a different key that maps to
937
+ // it, e.g. `additionalUserFields: { customRoles: { fieldName: 'roles', input: true } }`. Lock any
938
+ // such field too, so no additionalUserFields entry — regardless of its key — can feed client input
939
+ // into a protected column.
940
+ const protectedColumns = new Set<string>(PROTECTED_INPUT_FALSE_KEYS);
941
+ for (const [key, field] of Object.entries(coreFields)) {
942
+ if (!protectedColumns.has(key) && field.fieldName && protectedColumns.has(field.fieldName)) {
943
+ field.input = false;
944
+ }
945
+ }
946
+
876
947
  return coreFields;
877
948
  }
878
949
 
@@ -53,6 +53,19 @@ export abstract class CoreUserService<
53
53
  serviceOptions = prepareServiceOptionsForCreate(serviceOptions);
54
54
  return this.process(
55
55
  async (data) => {
56
+ // Application-level email-uniqueness check. The unique index alone is NOT
57
+ // sufficient: on a FRESH database Mongoose builds indexes asynchronously
58
+ // (autoIndex), so an early duplicate sign-up can slip through before the
59
+ // index exists — observed as a load-dependent e2e flake, and the same
60
+ // window exists on a freshly deployed production database. The index
61
+ // remains the backstop for truly concurrent duplicate requests.
62
+ if (data.input?.email) {
63
+ const existing = await this.mainDbModel.findOne({ email: data.input.email }).lean().exec();
64
+ if (existing) {
65
+ throw new BadRequestException('Email address already in use');
66
+ }
67
+ }
68
+
56
69
  // Create user with verification token
57
70
  const currentUserId = serviceOptions?.currentUser?._id;
58
71
  const createdUser = new this.mainDbModel({
@@ -66,7 +79,7 @@ export abstract class CoreUserService<
66
79
  try {
67
80
  await createdUser.save();
68
81
  } catch (error) {
69
- if (error?.errors?.email?.kind === 'unique') {
82
+ if (error?.errors?.email?.kind === 'unique' || error?.code === 11000) {
70
83
  throw new BadRequestException('Email address already in use');
71
84
  } else {
72
85
  throw new UnprocessableEntityException();