@lenne.tech/nest-server 11.44.2 → 11.46.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.
- package/.claude/rules/configurable-features.md +3 -1
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +3 -2
- package/dist/core/common/helpers/swagger-enabled.helper.d.ts +2 -0
- package/dist/core/common/helpers/swagger-enabled.helper.js +13 -0
- package/dist/core/common/helpers/swagger-enabled.helper.js.map +1 -0
- package/dist/core/common/helpers/swagger.helper.d.ts +1 -1
- package/dist/core/common/helpers/swagger.helper.js +16 -3
- package/dist/core/common/helpers/swagger.helper.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +6 -0
- package/dist/core/modules/better-auth/better-auth.config.js +1 -1
- 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.js +2 -2
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +18 -0
- package/dist/core/modules/error-code/error-codes.js +16 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core/modules/system-setup/core-system-setup.controller.d.ts +2 -2
- package/dist/core/modules/system-setup/core-system-setup.controller.js +14 -4
- package/dist/core/modules/system-setup/core-system-setup.controller.js.map +1 -1
- package/dist/core/modules/system-setup/core-system-setup.service.d.ts +18 -0
- package/dist/core/modules/system-setup/core-system-setup.service.js +118 -15
- package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
- package/dist/core/modules/system-setup/system-setup-http-init.helper.d.ts +12 -0
- package/dist/core/modules/system-setup/system-setup-http-init.helper.js +60 -0
- package/dist/core/modules/system-setup/system-setup-http-init.helper.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/server/modules/error-code/error-codes.d.ts +2 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/migration-guides/11.44.x-to-11.45.x.md +111 -0
- package/migration-guides/11.45.x-to-11.46.x.md +219 -0
- package/package.json +1 -1
- package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
- package/src/core/common/helpers/swagger.helper.ts +40 -6
- package/src/core/common/interfaces/server-options.interface.ts +79 -3
- package/src/core/modules/better-auth/CUSTOMIZATION.md +1 -1
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +4 -0
- package/src/core/modules/better-auth/README.md +7 -0
- package/src/core/modules/better-auth/better-auth.config.ts +3 -1
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +5 -2
- package/src/core/modules/error-code/error-codes.ts +27 -0
- package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +23 -1
- package/src/core/modules/system-setup/README.md +54 -12
- package/src/core/modules/system-setup/core-system-setup.controller.ts +30 -8
- package/src/core/modules/system-setup/core-system-setup.service.ts +251 -23
- package/src/core/modules/system-setup/system-setup-http-init.helper.ts +165 -0
- package/src/index.ts +2 -0
|
@@ -640,6 +640,33 @@ export const LtnsErrors = {
|
|
|
640
640
|
},
|
|
641
641
|
},
|
|
642
642
|
|
|
643
|
+
/**
|
|
644
|
+
* `POST /system-setup/init` is closed in this environment (11.46.0+): by default it is open only in `local`, `ci`
|
|
645
|
+
* and `e2e`. A deployment provisions its first admin through `systemSetup.initialAdmin`, or opens the HTTP init
|
|
646
|
+
* explicitly with `systemSetup.httpInit`.
|
|
647
|
+
*/
|
|
648
|
+
SYSTEM_SETUP_HTTP_INIT_DISABLED: {
|
|
649
|
+
code: 'LTNS_0053',
|
|
650
|
+
message: 'Initial admin setup over HTTP is not enabled in this environment',
|
|
651
|
+
translations: {
|
|
652
|
+
de: 'Die Ersteinrichtung über die Oberfläche ist in dieser Umgebung nicht freigegeben.',
|
|
653
|
+
en: 'Initial admin setup over HTTP is not enabled in this environment.',
|
|
654
|
+
},
|
|
655
|
+
},
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* `POST /system-setup/init` requires the setup token (`systemSetup.httpInit.token`) in the `X-System-Setup-Token`
|
|
659
|
+
* header, and the request sent none or a different one (11.46.0+).
|
|
660
|
+
*/
|
|
661
|
+
SYSTEM_SETUP_TOKEN_INVALID: {
|
|
662
|
+
code: 'LTNS_0054',
|
|
663
|
+
message: 'Missing or invalid system setup token',
|
|
664
|
+
translations: {
|
|
665
|
+
de: 'Der Einrichtungs-Token fehlt oder ist falsch.',
|
|
666
|
+
en: 'The system setup token is missing or invalid.',
|
|
667
|
+
},
|
|
668
|
+
},
|
|
669
|
+
|
|
643
670
|
// =====================================================
|
|
644
671
|
// AI Errors (LTNS_0600-LTNS_0699)
|
|
645
672
|
// =====================================================
|
|
@@ -10,7 +10,9 @@
|
|
|
10
10
|
|
|
11
11
|
| Scenario | Action Needed |
|
|
12
12
|
| ---------------------------------------------------- | ----------------------------------------------- |
|
|
13
|
-
|
|
|
13
|
+
| Local development / e2e suites (`local`, `ci`, `e2e`) | None - the init endpoint is open there by default |
|
|
14
|
+
| A deployed stage needs its first admin (11.46.0+) | Set ENV variables (Step 1) - the HTTP init is closed there by default |
|
|
15
|
+
| A deployed stage must be set up through a UI form | Step 1b (setup token) |
|
|
14
16
|
| Automated deployment (Docker/CI) needs auto-creation | Set ENV variables (Step 1) |
|
|
15
17
|
| Want to disable system setup | Set `systemSetup: { enabled: false }` in config |
|
|
16
18
|
| Custom setup logic (extra fields, notifications) | Step 2 (Custom Controller) |
|
|
@@ -63,6 +65,22 @@ The admin is created automatically on server start when zero users exist.
|
|
|
63
65
|
|
|
64
66
|
---
|
|
65
67
|
|
|
68
|
+
## Step 1b: Open the HTTP init with a token (Optional, 11.46.0+)
|
|
69
|
+
|
|
70
|
+
Outside `local`, `ci` and `e2e`, `POST /system-setup/init` answers 403 `LTNS_0053` unless `systemSetup.httpInit`
|
|
71
|
+
opens it. When a deployed stage must be set up through a form:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN=<secret of at least 16 characters, with letters>
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The frontend sends it in the `X-System-Setup-Token` header (403 `LTNS_0054` without it). `GET /system-setup/status`
|
|
78
|
+
reports `httpInitEnabled` / `httpInitTokenRequired`. Remove the variable once the admin exists.
|
|
79
|
+
|
|
80
|
+
**WHY a token and not `httpInit: true`:** without a token, whoever reaches the API first becomes the administrator.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
66
84
|
## Step 2: Custom Controller (Optional)
|
|
67
85
|
|
|
68
86
|
Only needed if you want to add extra validation, logging, or custom fields.
|
|
@@ -80,6 +98,9 @@ export class SystemSetupController extends CoreSystemSetupController {
|
|
|
80
98
|
}
|
|
81
99
|
```
|
|
82
100
|
|
|
101
|
+
**An override of `createInitialAdmin()` must call `this.systemSetupService.assertHttpInitAllowed(token)` first** (the
|
|
102
|
+
token read with `@Headers(SYSTEM_SETUP_TOKEN_HEADER)`). Otherwise it keeps the init open in every environment.
|
|
103
|
+
|
|
83
104
|
> **Note:** The SystemSetup module auto-registers its controller via CoreModule. To use a custom controller, you would need to disable auto-registration and register your own module.
|
|
84
105
|
|
|
85
106
|
---
|
|
@@ -92,6 +113,7 @@ export class SystemSetupController extends CoreSystemSetupController {
|
|
|
92
113
|
- [ ] `POST /system-setup/init` creates admin user with correct role
|
|
93
114
|
- [ ] `GET /system-setup/status` returns `{ needsSetup: false }` after init
|
|
94
115
|
- [ ] `POST /system-setup/init` returns 403 when users already exist
|
|
116
|
+
- [ ] On a deployed stage without `httpInit`: `POST /system-setup/init` returns 403 `LTNS_0053`
|
|
95
117
|
|
|
96
118
|
---
|
|
97
119
|
|
|
@@ -4,7 +4,9 @@ Initial admin user creation for fresh deployments of @lenne.tech/nest-server.
|
|
|
4
4
|
|
|
5
5
|
## TL;DR
|
|
6
6
|
|
|
7
|
-
System setup is **enabled by default** when BetterAuth is active.
|
|
7
|
+
System setup is **enabled by default** when BetterAuth is active. Locally (`local`, `ci`, `e2e`) no configuration is
|
|
8
|
+
needed. On every other environment the anonymous `POST /system-setup/init` is **closed** since 11.46.0 (see
|
|
9
|
+
[HTTP init](#http-init-systemsetuphttpinit)); a deployment creates its first admin from `initialAdmin`.
|
|
8
10
|
|
|
9
11
|
For automated deployments (Docker, CI/CD), set initial admin credentials via ENV:
|
|
10
12
|
|
|
@@ -23,6 +25,7 @@ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=YourSecurePassword123!
|
|
|
23
25
|
- [Endpoints](#endpoints)
|
|
24
26
|
- [Configuration](#configuration)
|
|
25
27
|
- [Auto-Creation via Config/ENV](#auto-creation-via-configenv)
|
|
28
|
+
- [HTTP init (`systemSetup.httpInit`)](#http-init-systemsetuphttpinit)
|
|
26
29
|
- [Security](#security)
|
|
27
30
|
- [Frontend Integration](#frontend-integration)
|
|
28
31
|
- [Troubleshooting](#troubleshooting)
|
|
@@ -56,13 +59,20 @@ Returns the current setup status.
|
|
|
56
59
|
```json
|
|
57
60
|
{
|
|
58
61
|
"needsSetup": true,
|
|
59
|
-
"betterAuthEnabled": true
|
|
62
|
+
"betterAuthEnabled": true,
|
|
63
|
+
"httpInitEnabled": true,
|
|
64
|
+
"httpInitTokenRequired": false
|
|
60
65
|
}
|
|
61
66
|
```
|
|
62
67
|
|
|
68
|
+
`httpInitEnabled` / `httpInitTokenRequired` (11.46.0+) say whether `POST /system-setup/init` is open here and whether
|
|
69
|
+
it needs the setup token. Offer a setup form only when `needsSetup && httpInitEnabled`.
|
|
70
|
+
|
|
63
71
|
### POST /system-setup/init
|
|
64
72
|
|
|
65
|
-
Creates the initial admin user. Only works when zero users exist.
|
|
73
|
+
Creates the initial admin user. Only works when zero users exist, and only where `systemSetup.httpInit` opens it — by
|
|
74
|
+
default in `local`, `ci` and `e2e` (403 `LTNS_0053` elsewhere). With a configured token the request carries it in the
|
|
75
|
+
`X-System-Setup-Token` header (403 `LTNS_0054` without it or with a wrong one).
|
|
66
76
|
|
|
67
77
|
**Request Body:**
|
|
68
78
|
|
|
@@ -182,16 +192,44 @@ NEST_SERVER_CONFIG='{ "systemSetup": { "initialAdmin": { "email": "admin@example
|
|
|
182
192
|
|
|
183
193
|
---
|
|
184
194
|
|
|
195
|
+
## HTTP init (`systemSetup.httpInit`)
|
|
196
|
+
|
|
197
|
+
Since 11.46.0 (backport of 12.4.0) the anonymous init is fail-closed outside the local environments: whoever reaches
|
|
198
|
+
an API without users through it would become its administrator.
|
|
199
|
+
|
|
200
|
+
| `systemSetup.httpInit` | `local` / `ci` / `e2e` | every other environment |
|
|
201
|
+
|---|---|---|
|
|
202
|
+
| not set | open | **closed** — 403 `LTNS_0053` |
|
|
203
|
+
| `true` (`NSC__SYSTEM_SETUP__HTTP_INIT=true`) | open | open, without a token |
|
|
204
|
+
| `{ token }` (`NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN`, at least 16 characters) | open, token required | open, token required |
|
|
205
|
+
| `false` / `{ enabled: false }` | closed | closed |
|
|
206
|
+
|
|
207
|
+
The environment is the configured `env`, but where that is local only because 11.x fell back to the `local` block (a
|
|
208
|
+
`NODE_ENV` without a block of its own, or an empty one), `NODE_ENV` decides — such a stage counts as deployed
|
|
209
|
+
(`resolveSystemSetupEnv()`). A token that is missing, empty, shorter than 16 characters or not a string keeps the init
|
|
210
|
+
closed and logs an error at boot; a non-boolean, non-object value counts as not set. `initialAdmin` is not affected. A deployed instance that starts
|
|
211
|
+
with zero users, no usable `initialAdmin` and a closed init logs an error naming both ways in. While the init is closed,
|
|
212
|
+
`setupSwagger()` leaves it out of the document.
|
|
213
|
+
|
|
214
|
+
A project controller that overrides `createInitialAdmin()` must call `systemSetupService.assertHttpInitAllowed(token)`
|
|
215
|
+
first; `createInitialAdmin()` itself is not gated, because the boot path calls it too. Migration:
|
|
216
|
+
[11.45.x → 11.46.x](../../../../migration-guides/11.45.x-to-11.46.x.md).
|
|
217
|
+
|
|
185
218
|
## Security
|
|
186
219
|
|
|
187
|
-
1. **
|
|
220
|
+
1. **Fail-closed HTTP init** - the anonymous init is open only where `systemSetup.httpInit` allows it (by default
|
|
221
|
+
`local`, `ci`, `e2e`)
|
|
222
|
+
2. **Zero-user guard** - Init requires `countDocuments({}) === 0`. Necessary but not sufficient:
|
|
188
223
|
the atomic claim below must also be winnable, so an empty `users` collection alone does not
|
|
189
224
|
re-open setup
|
|
190
|
-
|
|
191
|
-
|
|
225
|
+
3. **Enabled by default** - Safe because the init is closed on deployed environments unless opened, and locked once
|
|
226
|
+
any user exists
|
|
227
|
+
4. **Race condition protection** - MongoDB unique email index prevents duplicates; auto-creation on
|
|
192
228
|
bootstrap is additionally claimed atomically via the `system-setup-locks` marker
|
|
193
|
-
|
|
194
|
-
|
|
229
|
+
5. **Permanent lock** - Once any user exists, init returns 403
|
|
230
|
+
6. **BetterAuth required** - Returns 403 if BetterAuth is not enabled
|
|
231
|
+
7. **Rollback** - a creation that fails after the user was written removes that user again (11.46.0+), so the setup can
|
|
232
|
+
be retried
|
|
195
233
|
|
|
196
234
|
### How It Bypasses disableSignUp
|
|
197
235
|
|
|
@@ -206,13 +244,17 @@ Typical frontend flow:
|
|
|
206
244
|
```typescript
|
|
207
245
|
// 1. Check if setup is needed
|
|
208
246
|
const status = await fetch('/system-setup/status');
|
|
209
|
-
|
|
247
|
+
// A backend older than 11.46.0 sends neither httpInit field: treat that as "available"
|
|
248
|
+
const { needsSetup, httpInitEnabled = true, httpInitTokenRequired = false } = await status.json();
|
|
210
249
|
|
|
211
|
-
if (needsSetup) {
|
|
212
|
-
// 2. Show setup form and submit
|
|
250
|
+
if (needsSetup && httpInitEnabled) {
|
|
251
|
+
// 2. Show setup form (with a token field when httpInitTokenRequired) and submit
|
|
213
252
|
const result = await fetch('/system-setup/init', {
|
|
214
253
|
method: 'POST',
|
|
215
|
-
headers: {
|
|
254
|
+
headers: {
|
|
255
|
+
'Content-Type': 'application/json',
|
|
256
|
+
...(httpInitTokenRequired ? { 'X-System-Setup-Token': setupToken } : {}),
|
|
257
|
+
},
|
|
216
258
|
body: JSON.stringify({
|
|
217
259
|
email: 'admin@example.com',
|
|
218
260
|
password: 'SecurePassword123!',
|
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import { Body, Controller, Get, Post } from '@nestjs/common';
|
|
2
|
-
import { ApiBody, ApiOperation, ApiProperty, ApiResponse, ApiTags } from '@nestjs/swagger';
|
|
1
|
+
import { Body, Controller, Get, Headers, Post } from '@nestjs/common';
|
|
2
|
+
import { ApiBody, ApiHeader, ApiOperation, ApiProperty, ApiResponse, ApiTags } from '@nestjs/swagger';
|
|
3
3
|
import { IsEmail, IsNotEmpty, IsOptional, IsString, MinLength } from 'class-validator';
|
|
4
4
|
|
|
5
5
|
import { Roles } from '../../common/decorators/roles.decorator';
|
|
6
6
|
import { RoleEnum } from '../../common/enums/role.enum';
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
CoreSystemSetupService,
|
|
9
|
+
type SystemSetupInitResult,
|
|
10
|
+
type SystemSetupStatus,
|
|
11
|
+
} from './core-system-setup.service';
|
|
12
|
+
import { SYSTEM_SETUP_TOKEN_HEADER } from './system-setup-http-init.helper';
|
|
8
13
|
|
|
9
14
|
/**
|
|
10
15
|
* DTO for system setup init request
|
|
@@ -31,8 +36,12 @@ export class SystemSetupInitDto {
|
|
|
31
36
|
* CoreSystemSetupController provides REST endpoints for initial system setup.
|
|
32
37
|
*
|
|
33
38
|
* These endpoints are public (S_EVERYONE) to allow first-time admin creation
|
|
34
|
-
* on a fresh system with zero users. The service enforces security
|
|
35
|
-
*
|
|
39
|
+
* on a fresh system with zero users. The service enforces security: the init is
|
|
40
|
+
* refused where `systemSetup.httpInit` does not open it (by default every
|
|
41
|
+
* environment except `local`, `ci` and `e2e`, 11.46.0+), and once any user exists.
|
|
42
|
+
*
|
|
43
|
+
* A subclass that overrides `createInitialAdmin()` must call
|
|
44
|
+
* `systemSetupService.assertHttpInitAllowed(token)` itself.
|
|
36
45
|
*/
|
|
37
46
|
@ApiTags('System Setup')
|
|
38
47
|
@Controller('system-setup')
|
|
@@ -55,18 +64,31 @@ export class CoreSystemSetupController {
|
|
|
55
64
|
* Create the initial admin user (only works when zero users exist)
|
|
56
65
|
*/
|
|
57
66
|
@ApiBody({ type: SystemSetupInitDto })
|
|
67
|
+
@ApiHeader({
|
|
68
|
+
description: 'The setup token, required when systemSetup.httpInit configures one (see GET /system-setup/status)',
|
|
69
|
+
name: SYSTEM_SETUP_TOKEN_HEADER,
|
|
70
|
+
required: false,
|
|
71
|
+
})
|
|
58
72
|
@ApiOperation({
|
|
59
|
-
description:
|
|
73
|
+
description:
|
|
74
|
+
'Creates the initial admin user. Only works when zero users exist in the database, and only where ' +
|
|
75
|
+
'systemSetup.httpInit opens it (by default in the local, ci and e2e environments).',
|
|
60
76
|
summary: 'Create initial admin',
|
|
61
77
|
})
|
|
62
78
|
@ApiResponse({ description: 'Initial admin created', status: 201 })
|
|
63
79
|
@ApiResponse({
|
|
64
|
-
description:
|
|
80
|
+
description:
|
|
81
|
+
'LTNS_0053: HTTP init not enabled in this environment; LTNS_0054: setup token missing or invalid; ' +
|
|
82
|
+
'LTNS_0050: users already exist, or the initial-admin setup is claimed',
|
|
65
83
|
status: 403,
|
|
66
84
|
})
|
|
67
85
|
@Post('init')
|
|
68
86
|
@Roles(RoleEnum.S_EVERYONE)
|
|
69
|
-
async createInitialAdmin(
|
|
87
|
+
async createInitialAdmin(
|
|
88
|
+
@Body() input: SystemSetupInitDto,
|
|
89
|
+
@Headers(SYSTEM_SETUP_TOKEN_HEADER) token?: string,
|
|
90
|
+
): Promise<SystemSetupInitResult> {
|
|
91
|
+
this.systemSetupService.assertHttpInitAllowed(token);
|
|
70
92
|
return this.systemSetupService.createInitialAdmin(input);
|
|
71
93
|
}
|
|
72
94
|
}
|
|
@@ -3,11 +3,20 @@ import { InjectConnection } from '@nestjs/mongoose';
|
|
|
3
3
|
import { isEmail } from 'class-validator';
|
|
4
4
|
import { Connection } from 'mongoose';
|
|
5
5
|
|
|
6
|
+
import { isLocalEnv } from '../../common/helpers/cookies.helper';
|
|
7
|
+
import type { ISystemSetupInitialAdmin } from '../../common/interfaces/server-options.interface';
|
|
6
8
|
import { ConfigService } from '../../common/services/config.service';
|
|
7
9
|
import { legacyCredentialAccountIssuer } from '../better-auth/core-better-auth-account-issuer.helper';
|
|
8
10
|
import { CoreBetterAuthUserMapper } from '../better-auth/core-better-auth-user.mapper';
|
|
9
11
|
import { CoreBetterAuthService } from '../better-auth/core-better-auth.service';
|
|
10
12
|
import { ErrorCode } from '../error-code/error-codes';
|
|
13
|
+
import {
|
|
14
|
+
type ISystemSetupHttpInitPolicy,
|
|
15
|
+
isSystemSetupTokenValid,
|
|
16
|
+
resolveSystemSetupEnv,
|
|
17
|
+
resolveSystemSetupHttpInit,
|
|
18
|
+
SYSTEM_SETUP_TOKEN_HEADER,
|
|
19
|
+
} from './system-setup-http-init.helper';
|
|
11
20
|
|
|
12
21
|
/**
|
|
13
22
|
* Collection holding the bootstrap claim markers.
|
|
@@ -51,6 +60,23 @@ export interface SystemSetupInitResult {
|
|
|
51
60
|
*/
|
|
52
61
|
export interface SystemSetupStatus {
|
|
53
62
|
betterAuthEnabled: boolean;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether `POST /system-setup/init` is open in this environment (`systemSetup.httpInit`; by default only in
|
|
66
|
+
* `local`, `ci` and `e2e`). Independent of `needsSetup`: a frontend offers the setup form only when both are true.
|
|
67
|
+
*
|
|
68
|
+
* @since 11.46.0
|
|
69
|
+
*/
|
|
70
|
+
httpInitEnabled: boolean;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Whether the init must carry the setup token in the `X-System-Setup-Token` header. Only ever true together with
|
|
74
|
+
* `httpInitEnabled`.
|
|
75
|
+
*
|
|
76
|
+
* @since 11.46.0
|
|
77
|
+
*/
|
|
78
|
+
httpInitTokenRequired: boolean;
|
|
79
|
+
|
|
54
80
|
needsSetup: boolean;
|
|
55
81
|
}
|
|
56
82
|
|
|
@@ -62,9 +88,12 @@ export interface SystemSetupStatus {
|
|
|
62
88
|
* which is the same approach used by Better-Auth's own admin plugin.
|
|
63
89
|
*
|
|
64
90
|
* Security:
|
|
91
|
+
* - The anonymous HTTP init is open only where `systemSetup.httpInit` allows it — by default only in `local`, `ci`
|
|
92
|
+
* and `e2e` ({@link assertHttpInitAllowed}, 11.46.0+); a deployment provisions its first admin via `initialAdmin`
|
|
65
93
|
* - Only works when zero users exist in the database
|
|
66
94
|
* - Once any user exists, the init endpoint is permanently locked
|
|
67
|
-
* - Race conditions handled by
|
|
95
|
+
* - Race conditions handled by an atomic claim shared by both entry points
|
|
96
|
+
* - A creation that fails after the user was created removes that user again, so `needsSetup` stays true
|
|
68
97
|
*/
|
|
69
98
|
@Injectable()
|
|
70
99
|
export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
@@ -85,32 +114,21 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
85
114
|
* is fully initialized before attempting user creation.
|
|
86
115
|
*/
|
|
87
116
|
async onApplicationBootstrap(): Promise<void> {
|
|
88
|
-
|
|
117
|
+
await this.createInitialAdminFromConfig();
|
|
118
|
+
await this.reportSetupReachability();
|
|
119
|
+
}
|
|
89
120
|
|
|
90
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Create the initial admin from `systemSetup.initialAdmin` when zero users exist (the boot half of
|
|
123
|
+
* {@link onApplicationBootstrap}). Not gated by `systemSetup.httpInit`: it is the deployment's own configuration,
|
|
124
|
+
* not an anonymous request.
|
|
125
|
+
*/
|
|
126
|
+
protected async createInitialAdminFromConfig(): Promise<void> {
|
|
127
|
+
const initialAdmin = this.usableInitialAdmin({ warn: true });
|
|
91
128
|
if (!initialAdmin) {
|
|
92
129
|
return;
|
|
93
130
|
}
|
|
94
131
|
|
|
95
|
-
// Partial credentials → warn and skip
|
|
96
|
-
if (!initialAdmin.email || !initialAdmin.password) {
|
|
97
|
-
const missing = [!initialAdmin.email && 'email', !initialAdmin.password && 'password'].filter(Boolean).join(', ');
|
|
98
|
-
this.logger.warn(`Incomplete initialAdmin config - missing: ${missing}. Auto-creation skipped.`);
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// Validate email format (same validator as @IsEmail() decorator)
|
|
103
|
-
if (!isEmail(initialAdmin.email)) {
|
|
104
|
-
this.logger.warn(`Invalid initialAdmin email format: "${initialAdmin.email}". Auto-creation skipped.`);
|
|
105
|
-
return;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Validate password is not empty/whitespace
|
|
109
|
-
if (!initialAdmin.password.trim()) {
|
|
110
|
-
this.logger.warn('Empty initialAdmin password. Auto-creation skipped.');
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
132
|
const status = await this.getSetupStatus();
|
|
115
133
|
if (!status.needsSetup) {
|
|
116
134
|
return;
|
|
@@ -146,6 +164,173 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
146
164
|
}
|
|
147
165
|
}
|
|
148
166
|
|
|
167
|
+
/**
|
|
168
|
+
* The configured `systemSetup.initialAdmin`, or `undefined` when it is absent or cannot be used.
|
|
169
|
+
*
|
|
170
|
+
* With `warn`, each reason it cannot be used is logged (the boot path); without, it only answers.
|
|
171
|
+
*/
|
|
172
|
+
protected usableInitialAdmin(options?: { warn?: boolean }): ISystemSetupInitialAdmin | undefined {
|
|
173
|
+
const initialAdmin = this.configService.configFastButReadOnly?.systemSetup?.initialAdmin;
|
|
174
|
+
const skip = (message: string): undefined => {
|
|
175
|
+
if (options?.warn) {
|
|
176
|
+
this.logger.warn(message);
|
|
177
|
+
}
|
|
178
|
+
return undefined;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// No initialAdmin config at all → nothing to report here
|
|
182
|
+
if (!initialAdmin) {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Partial credentials → skip
|
|
187
|
+
if (!initialAdmin.email || !initialAdmin.password) {
|
|
188
|
+
const missing = [!initialAdmin.email && 'email', !initialAdmin.password && 'password'].filter(Boolean).join(', ');
|
|
189
|
+
return skip(`Incomplete initialAdmin config - missing: ${missing}. Auto-creation skipped.`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Validate email format (same validator as @IsEmail() decorator)
|
|
193
|
+
if (!isEmail(initialAdmin.email)) {
|
|
194
|
+
return skip(`Invalid initialAdmin email format: "${initialAdmin.email}". Auto-creation skipped.`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// An all-digit NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD arrives as a NUMBER (getEnvironmentObject() converts
|
|
198
|
+
// numeric strings), and `.trim()` on it used to throw at boot. Name the cause instead.
|
|
199
|
+
if (typeof initialAdmin.password !== 'string') {
|
|
200
|
+
return skip(
|
|
201
|
+
`initialAdmin password is a ${typeof initialAdmin.password}, not a string (an all-digit ENV value is ` +
|
|
202
|
+
'converted to a number). Auto-creation skipped.',
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Validate password is not empty/whitespace
|
|
207
|
+
if (!initialAdmin.password.trim()) {
|
|
208
|
+
return skip('Empty initialAdmin password. Auto-creation skipped.');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return initialAdmin;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The environment the HTTP-init policy is decided for: the configured `env`, else `NODE_ENV` — and `NODE_ENV` when
|
|
216
|
+
* the configured `env` is local only because 11.x fell back to the `local` block ({@link resolveSystemSetupEnv})
|
|
217
|
+
*/
|
|
218
|
+
protected currentEnv(): string | undefined {
|
|
219
|
+
return resolveSystemSetupEnv(this.configService.configFastButReadOnly?.env);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Whether the anonymous `POST /system-setup/init` is open here, and whether it needs the setup token
|
|
224
|
+
* (`systemSetup.httpInit`, see {@link resolveSystemSetupHttpInit}).
|
|
225
|
+
*
|
|
226
|
+
* @since 11.46.0
|
|
227
|
+
*/
|
|
228
|
+
getHttpInitPolicy(): ISystemSetupHttpInitPolicy {
|
|
229
|
+
return resolveSystemSetupHttpInit(
|
|
230
|
+
this.configService.configFastButReadOnly?.systemSetup?.httpInit,
|
|
231
|
+
this.currentEnv(),
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Refuse an HTTP init the configuration does not allow — call it from every HTTP entry point before
|
|
237
|
+
* {@link createInitialAdmin}, which does not check it (the boot path must not be gated).
|
|
238
|
+
*
|
|
239
|
+
* @param token the value of the `X-System-Setup-Token` header
|
|
240
|
+
* @throws ForbiddenException `SYSTEM_SETUP_HTTP_INIT_DISABLED` when the HTTP init is closed in this environment,
|
|
241
|
+
* `SYSTEM_SETUP_TOKEN_INVALID` when it needs a token and `token` is missing or wrong
|
|
242
|
+
* @since 11.46.0
|
|
243
|
+
*/
|
|
244
|
+
assertHttpInitAllowed(token?: unknown): void {
|
|
245
|
+
const policy = this.getHttpInitPolicy();
|
|
246
|
+
if (!policy.enabled) {
|
|
247
|
+
throw new ForbiddenException(ErrorCode.SYSTEM_SETUP_HTTP_INIT_DISABLED);
|
|
248
|
+
}
|
|
249
|
+
if (policy.tokenRequired && !isSystemSetupTokenValid(policy.token, token)) {
|
|
250
|
+
throw new ForbiddenException(ErrorCode.SYSTEM_SETUP_TOKEN_INVALID);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Say at boot when a deployment has no way to its first admin, or an open one (the second half of
|
|
256
|
+
* {@link onApplicationBootstrap}).
|
|
257
|
+
*
|
|
258
|
+
* A deployed environment with zero users, no usable `initialAdmin` and a closed HTTP init cannot be set up at all:
|
|
259
|
+
* nobody notices until somebody tries to sign in. With the HTTP init open WITHOUT a token, whoever reaches the API
|
|
260
|
+
* first becomes the administrator. Both are logged; neither stops the boot. Local environments are left alone,
|
|
261
|
+
* and an instance with a usable `initialAdmin` reports through the auto-creation instead — reporting here as well
|
|
262
|
+
* would raise a false alarm on every replica that lost the creation race while the winner is still creating.
|
|
263
|
+
*/
|
|
264
|
+
protected async reportSetupReachability(): Promise<void> {
|
|
265
|
+
const policy = this.getHttpInitPolicy();
|
|
266
|
+
if (policy.problem) {
|
|
267
|
+
this.logger.error(
|
|
268
|
+
`POST /system-setup/init stays closed: ${policy.problem}. Set a token of at least 16 characters ` +
|
|
269
|
+
'(NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN), or systemSetup.httpInit: true to open it without one.',
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
this.warnAboutIgnoredEnvironmentNames();
|
|
273
|
+
|
|
274
|
+
if (isLocalEnv(this.currentEnv()) || this.usableInitialAdmin() || (policy.enabled && policy.tokenRequired)) {
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
let needsSetup: boolean;
|
|
279
|
+
try {
|
|
280
|
+
needsSetup = (await this.getSetupStatus()).needsSetup;
|
|
281
|
+
} catch (error) {
|
|
282
|
+
// A diagnostic must never be the reason a boot fails
|
|
283
|
+
this.logger.warn(
|
|
284
|
+
`Could not check whether initial setup is needed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
285
|
+
);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (!needsSetup) {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const env = this.currentEnv() ?? '(not set)';
|
|
293
|
+
if (!policy.enabled) {
|
|
294
|
+
this.logger.error(
|
|
295
|
+
`No users exist and this instance cannot be set up: environment "${env}" closes POST /system-setup/init, ` +
|
|
296
|
+
'and no initialAdmin is configured. Set NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL and ' +
|
|
297
|
+
'NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD (created on the next start), or open the HTTP init explicitly ' +
|
|
298
|
+
'with NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN=<secret of at least 16 characters> ' +
|
|
299
|
+
`(sent as the "${SYSTEM_SETUP_TOKEN_HEADER}" header).`,
|
|
300
|
+
);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
this.logger.warn(
|
|
304
|
+
`No users exist and POST /system-setup/init is open without a token in environment "${env}": whoever reaches ` +
|
|
305
|
+
'the API first becomes the administrator. Prefer NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL / __PASSWORD, or ' +
|
|
306
|
+
'protect the init with NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN.',
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Warn about `NSC__` variables for `systemSetup` that carry a camelCase segment (`NSC__systemSetup__initialAdmin__email`).
|
|
312
|
+
*
|
|
313
|
+
* `getEnvironmentObject()` lowercases every segment it does not split at `_`, so such a variable lands under
|
|
314
|
+
* `systemsetup.initialadmin` — a key nothing reads — and the auto-creation silently never happens. Only the variable
|
|
315
|
+
* NAMES are logged, never values.
|
|
316
|
+
*/
|
|
317
|
+
protected warnAboutIgnoredEnvironmentNames(): void {
|
|
318
|
+
for (const key of Object.keys(process.env)) {
|
|
319
|
+
if (!key.startsWith('NSC__')) {
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
const segments = key.slice('NSC__'.length).split('__');
|
|
323
|
+
if (
|
|
324
|
+
segments[0]?.replace(/_/g, '').toLowerCase() !== 'systemsetup' ||
|
|
325
|
+
!segments.some((s) => /[a-z][A-Z]/.test(s))
|
|
326
|
+
) {
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
const corrected = `NSC__${segments.map((s) => s.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()).join('__')}`;
|
|
330
|
+
this.logger.warn(`Environment variable ${key} is not read (camelCase segment). Use ${corrected} instead.`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
149
334
|
/**
|
|
150
335
|
* Try to claim the initial-admin creation for this instance
|
|
151
336
|
*
|
|
@@ -198,13 +383,41 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
198
383
|
}
|
|
199
384
|
}
|
|
200
385
|
|
|
386
|
+
/**
|
|
387
|
+
* Remove the user a failed {@link createInitialAdmin} had already created: Better-Auth's sessions and accounts and
|
|
388
|
+
* the `users` document, which Better-Auth and the user model share. Without it the deployment keeps a user without
|
|
389
|
+
* the admin role, `needsSetup` turns false and init stays refused for good.
|
|
390
|
+
*
|
|
391
|
+
* Never throws: the failure that triggered the rollback is the one the caller must see. A rollback that fails is
|
|
392
|
+
* logged with what to remove by hand.
|
|
393
|
+
*/
|
|
394
|
+
protected async rollbackInitialAdmin(
|
|
395
|
+
context: { internalAdapter: { deleteUser(userId: string): Promise<unknown> } },
|
|
396
|
+
iamUserId: string,
|
|
397
|
+
email: string,
|
|
398
|
+
): Promise<void> {
|
|
399
|
+
try {
|
|
400
|
+
await context.internalAdapter.deleteUser(iamUserId);
|
|
401
|
+
this.logger.warn(`Initial admin creation failed; the partially created user ${email} was removed again`);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
this.logger.error(
|
|
404
|
+
`Initial admin creation failed and the partially created user ${email} could not be removed ` +
|
|
405
|
+
`(${error instanceof Error ? error.message : 'Unknown error'}). Remove that user and its accounts from ` +
|
|
406
|
+
'"users" and "account", otherwise initial setup stays refused because a user exists.',
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
201
411
|
/**
|
|
202
412
|
* Check if the system needs initial setup (zero users)
|
|
203
413
|
*/
|
|
204
414
|
async getSetupStatus(): Promise<SystemSetupStatus> {
|
|
205
415
|
const userCount = await this.connection.collection('users').countDocuments({});
|
|
416
|
+
const httpInit = this.getHttpInitPolicy();
|
|
206
417
|
return {
|
|
207
418
|
betterAuthEnabled: this.betterAuthService.isEnabled(),
|
|
419
|
+
httpInitEnabled: httpInit.enabled,
|
|
420
|
+
httpInitTokenRequired: httpInit.enabled && httpInit.tokenRequired,
|
|
208
421
|
needsSetup: userCount === 0,
|
|
209
422
|
};
|
|
210
423
|
}
|
|
@@ -214,6 +427,9 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
214
427
|
*
|
|
215
428
|
* Uses BetterAuth's internalAdapter to bypass disableSignUp,
|
|
216
429
|
* then syncs to nest-server users collection with admin role.
|
|
430
|
+
*
|
|
431
|
+
* Does NOT check `systemSetup.httpInit`: the boot path calls it too. An HTTP entry point calls
|
|
432
|
+
* {@link assertHttpInitAllowed} first, as `CoreSystemSetupController` does.
|
|
217
433
|
*/
|
|
218
434
|
async createInitialAdmin(input: SystemSetupInitInput): Promise<SystemSetupInitResult> {
|
|
219
435
|
// Pre-check: only allow when zero users exist
|
|
@@ -264,9 +480,12 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
264
480
|
throw new ForbiddenException(ErrorCode.SYSTEM_SETUP_NOT_AVAILABLE);
|
|
265
481
|
}
|
|
266
482
|
|
|
483
|
+
// Set once the IAM user exists: every failure after that point removes the user again (see the catch below)
|
|
484
|
+
let createdIamUserId: string | undefined;
|
|
485
|
+
let context: Awaited<typeof authInstance.$context> | undefined;
|
|
267
486
|
try {
|
|
268
487
|
// Access BetterAuth internal context (same pattern as core-better-auth-api.middleware.ts)
|
|
269
|
-
|
|
488
|
+
context = await authInstance.$context;
|
|
270
489
|
|
|
271
490
|
// Normalize password for IAM (SHA256 if plain text)
|
|
272
491
|
const normalizedPassword = this.userMapper.normalizePasswordForIam(input.password);
|
|
@@ -302,6 +521,7 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
302
521
|
if (!iamUser) {
|
|
303
522
|
throw new Error('Failed to create IAM user');
|
|
304
523
|
}
|
|
524
|
+
createdIamUserId = iamUser.id;
|
|
305
525
|
|
|
306
526
|
// Hash password and create credential account
|
|
307
527
|
const hashedPassword = await context.password.hash(normalizedPassword);
|
|
@@ -350,6 +570,14 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
350
570
|
success: true,
|
|
351
571
|
};
|
|
352
572
|
} catch (error) {
|
|
573
|
+
// Remove the user this call created BEFORE releasing the claim. A failure after createUser (linkAccount,
|
|
574
|
+
// the sync, the role update, the legacy password) otherwise left a user without the admin role — and from then
|
|
575
|
+
// on `needsSetup` is false and init refused, so the deployment had users but no administrator and no way back
|
|
576
|
+
// short of editing the database.
|
|
577
|
+
if (createdIamUserId && context) {
|
|
578
|
+
await this.rollbackInitialAdmin(context, createdIamUserId, input.email);
|
|
579
|
+
}
|
|
580
|
+
|
|
353
581
|
// Release the claim we took above: a caller that failed mid-creation must not
|
|
354
582
|
// leave a deployment with zero users and no way in. The marker is additionally
|
|
355
583
|
// stale-expiring, so this is belt AND braces for the crash-before-release case.
|