@lenne.tech/nest-server 11.45.0 → 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.
Files changed (43) hide show
  1. package/.claude/rules/configurable-features.md +2 -1
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +2 -2
  4. package/dist/core/common/helpers/swagger.helper.js +6 -0
  5. package/dist/core/common/helpers/swagger.helper.js.map +1 -1
  6. package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
  7. package/dist/core/modules/better-auth/better-auth.config.js +1 -1
  8. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  9. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +2 -2
  10. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  11. package/dist/core/modules/error-code/error-codes.d.ts +18 -0
  12. package/dist/core/modules/error-code/error-codes.js +16 -0
  13. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  14. package/dist/core/modules/system-setup/core-system-setup.controller.d.ts +2 -2
  15. package/dist/core/modules/system-setup/core-system-setup.controller.js +14 -4
  16. package/dist/core/modules/system-setup/core-system-setup.controller.js.map +1 -1
  17. package/dist/core/modules/system-setup/core-system-setup.service.d.ts +18 -0
  18. package/dist/core/modules/system-setup/core-system-setup.service.js +118 -15
  19. package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
  20. package/dist/core/modules/system-setup/system-setup-http-init.helper.d.ts +12 -0
  21. package/dist/core/modules/system-setup/system-setup-http-init.helper.js +60 -0
  22. package/dist/core/modules/system-setup/system-setup-http-init.helper.js.map +1 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/server/modules/error-code/error-codes.d.ts +2 -0
  27. package/dist/tsconfig.build.tsbuildinfo +1 -1
  28. package/migration-guides/11.45.x-to-11.46.x.md +219 -0
  29. package/package.json +1 -1
  30. package/src/core/common/helpers/swagger.helper.ts +10 -0
  31. package/src/core/common/interfaces/server-options.interface.ts +60 -3
  32. package/src/core/modules/better-auth/CUSTOMIZATION.md +1 -1
  33. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +4 -0
  34. package/src/core/modules/better-auth/README.md +7 -0
  35. package/src/core/modules/better-auth/better-auth.config.ts +3 -1
  36. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +5 -2
  37. package/src/core/modules/error-code/error-codes.ts +27 -0
  38. package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +23 -1
  39. package/src/core/modules/system-setup/README.md +54 -12
  40. package/src/core/modules/system-setup/core-system-setup.controller.ts +30 -8
  41. package/src/core/modules/system-setup/core-system-setup.service.ts +251 -23
  42. package/src/core/modules/system-setup/system-setup-http-init.helper.ts +165 -0
  43. package/src/index.ts +1 -0
@@ -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 { CoreSystemSetupService, SystemSetupInitResult, SystemSetupStatus } from './core-system-setup.service';
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 by checking
35
- * that no users exist before allowing creation.
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: 'Creates the initial admin user. Only works when zero users exist in the database.',
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: 'System setup not available - users already exist, or the initial-admin setup is claimed',
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(@Body() input: SystemSetupInitDto): Promise<SystemSetupInitResult> {
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 MongoDB unique email index
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
- const initialAdmin = this.configService.configFastButReadOnly?.systemSetup?.initialAdmin;
117
+ await this.createInitialAdminFromConfig();
118
+ await this.reportSetupReachability();
119
+ }
89
120
 
90
- // No initialAdmin config at all → skip silently
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
- const context = await authInstance.$context;
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.
@@ -0,0 +1,165 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+
3
+ import { isLocalEnv } from '../../common/helpers/cookies.helper';
4
+
5
+ /**
6
+ * The request header `POST /system-setup/init` reads the setup token from (`systemSetup.httpInit.token`).
7
+ *
8
+ * A header, never a body field: the body is the admin's credentials and is shaped by the DTO, while the token is a
9
+ * deployment secret the operator hands out separately. Header names are case-insensitive; Express lowercases them.
10
+ *
11
+ * @since 11.46.0
12
+ */
13
+ export const SYSTEM_SETUP_TOKEN_HEADER = 'x-system-setup-token';
14
+
15
+ /**
16
+ * Minimum length of a configured setup token.
17
+ *
18
+ * The init route is anonymous and not rate-limited, so the token is all that stands between a caller and an
19
+ * administrator account. A shorter value is refused as a misconfiguration (the HTTP init stays closed), never
20
+ * accepted as a weak gate.
21
+ *
22
+ * @since 11.46.0
23
+ */
24
+ export const SYSTEM_SETUP_TOKEN_MIN_LENGTH = 16;
25
+
26
+ /**
27
+ * Whether `POST /system-setup/init` may run, as decided from `systemSetup.httpInit` and the environment.
28
+ *
29
+ * @since 11.46.0
30
+ */
31
+ export interface ISystemSetupHttpInitPolicy {
32
+ /** The HTTP init is open (with or without a token) */
33
+ enabled: boolean;
34
+
35
+ /**
36
+ * What is wrong with the configuration when it is unusable — a token that is missing, empty, too short or not a
37
+ * string. Set only when the configuration asked for a token-protected init and could not get one; the init then
38
+ * stays CLOSED. Meant for the boot log.
39
+ */
40
+ problem?: string;
41
+
42
+ /** Why the decision came out this way: the environment default, or an explicit setting */
43
+ source: 'config' | 'default';
44
+
45
+ /** The configured token, when the init is open and token-protected */
46
+ token?: string;
47
+
48
+ /** A token must be sent in {@link SYSTEM_SETUP_TOKEN_HEADER} */
49
+ tokenRequired: boolean;
50
+ }
51
+
52
+ /**
53
+ * Decide whether the anonymous `POST /system-setup/init` is open, from `systemSetup.httpInit` and the environment.
54
+ *
55
+ * Fail-closed in every branch that is not an explicit, well-formed opt-in:
56
+ *
57
+ * | `httpInit` | `local` / `ci` / `e2e` | every other environment |
58
+ * |---------------------------------------|------------------------|-------------------------|
59
+ * | not set (or not a boolean / object) | open, no token | **closed** |
60
+ * | `true` | open, no token | open, no token |
61
+ * | `false` / `{ enabled: false, … }` | closed | closed |
62
+ * | `{ token: '<≥ 16 characters>' }` | open, token required | open, token required |
63
+ * | an object without a usable token | closed + `problem` | closed + `problem` |
64
+ *
65
+ * The environment test is {@link isLocalEnv}: the deployed `develop` and `test` stages of a starter-based project,
66
+ * `production`, `staging` and an unknown or missing name all count as deployed.
67
+ *
68
+ * Why an object without a usable token CLOSES rather than opening without one: the natural way to write the option is
69
+ * `httpInit: { token: process.env.SETUP_TOKEN }`, and with the variable missing that is `{ token: undefined }`. Reading
70
+ * it as "open, no token" would turn a forgotten secret into an anonymous administrator endpoint — the incident this
71
+ * exists for. A value from `NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN` that is empty or all digits arrives as a NUMBER
72
+ * (`getEnvironmentObject()` converts numeric strings, `''` included, and a long digit string loses digits on the way),
73
+ * so a non-string token is refused too. And a non-boolean `httpInit` (the string `'true'` from `NEST_SERVER_CONFIG`)
74
+ * reads as "not set", so a string cannot open the route by truthiness.
75
+ *
76
+ * @since 11.46.0
77
+ */
78
+ export function resolveSystemSetupHttpInit(httpInit: unknown, env: string | undefined): ISystemSetupHttpInitPolicy {
79
+ if (httpInit === true) {
80
+ return { enabled: true, source: 'config', tokenRequired: false };
81
+ }
82
+ if (httpInit === false) {
83
+ return { enabled: false, source: 'config', tokenRequired: false };
84
+ }
85
+ if (httpInit && typeof httpInit === 'object' && !Array.isArray(httpInit)) {
86
+ const { enabled, token } = httpInit as { enabled?: unknown; token?: unknown };
87
+ if (enabled === false) {
88
+ return { enabled: false, source: 'config', tokenRequired: false };
89
+ }
90
+ const problem = tokenProblem(token);
91
+ if (problem) {
92
+ return { enabled: false, problem, source: 'config', tokenRequired: false };
93
+ }
94
+ return { enabled: true, source: 'config', token: token as string, tokenRequired: true };
95
+ }
96
+ return { enabled: isLocalEnv(env), source: 'default', tokenRequired: false };
97
+ }
98
+
99
+ /**
100
+ * The environment the HTTP-init policy is decided for: the configured `env`, unless it is local only because 11.x fell
101
+ * back to the `local` block.
102
+ *
103
+ * On 11.x `getEnvironmentConfig()` loads `config[NODE_ENV] || config.local`: a stage whose `NODE_ENV` names no block
104
+ * (`staging`, `prod`) or is empty (`NODE_ENV=${NODE_ENV}` in a compose file with the variable unset) runs on the
105
+ * `local` block, and its `env` reads `local` — which would keep the anonymous init open on a deployed instance. So a
106
+ * local configured `env` counts only when `NODE_ENV` is unset or local too. A test runner's `NODE_ENV=test` (vitest and
107
+ * jest set it when nothing else does) stays local while `VITEST` / `JEST_WORKER_ID` is set, as 12.7.0 does it.
108
+ *
109
+ * | configured `env` | `NODE_ENV` | decided for |
110
+ * |------------------|------------------------------------|-----------------------------|
111
+ * | not local | any | the configured `env` |
112
+ * | not set | any | `NODE_ENV` |
113
+ * | local | unset, or local | the configured `env` |
114
+ * | local | `test` under vitest / jest | the configured `env` |
115
+ * | local | anything else, `''` included | `NODE_ENV` (deployed) |
116
+ *
117
+ * @param configuredEnv the `env` of the loaded configuration
118
+ * @param nodeEnv `process.env.NODE_ENV` by default
119
+ * @since 11.46.0
120
+ */
121
+ export function resolveSystemSetupEnv(
122
+ configuredEnv: string | undefined,
123
+ nodeEnv: string | undefined = process.env.NODE_ENV,
124
+ ): string | undefined {
125
+ if (nodeEnv === undefined || !isLocalEnv(configuredEnv)) {
126
+ return configuredEnv ?? nodeEnv;
127
+ }
128
+ if (isLocalEnv(nodeEnv) || (nodeEnv === 'test' && (process.env.VITEST || process.env.JEST_WORKER_ID))) {
129
+ return configuredEnv;
130
+ }
131
+ return nodeEnv;
132
+ }
133
+
134
+ /**
135
+ * Whether `provided` (the header value) matches the configured `expected` token.
136
+ *
137
+ * Both sides are hashed to the same length before `timingSafeEqual`, so neither the content nor the LENGTH of the
138
+ * configured token leaks through the response time. A missing, empty or non-string value never matches.
139
+ *
140
+ * @since 11.46.0
141
+ */
142
+ export function isSystemSetupTokenValid(expected: string | undefined, provided: unknown): boolean {
143
+ if (typeof expected !== 'string' || !expected || typeof provided !== 'string' || !provided) {
144
+ return false;
145
+ }
146
+ const digest = (value: string) => createHash('sha256').update(value, 'utf8').digest();
147
+ return timingSafeEqual(digest(expected), digest(provided));
148
+ }
149
+
150
+ /** Why a configured token cannot be used, or `undefined` when it can */
151
+ function tokenProblem(token: unknown): string | undefined {
152
+ if (token === undefined || token === null) {
153
+ return 'systemSetup.httpInit is an object without a token';
154
+ }
155
+ if (typeof token !== 'string') {
156
+ return (
157
+ `systemSetup.httpInit.token is a ${typeof token}, not a string — an empty or all-digit ` +
158
+ 'NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN is converted to a number; use a token with letters'
159
+ );
160
+ }
161
+ if (token.trim().length < SYSTEM_SETUP_TOKEN_MIN_LENGTH) {
162
+ return `systemSetup.httpInit.token is shorter than ${SYSTEM_SETUP_TOKEN_MIN_LENGTH} characters`;
163
+ }
164
+ return undefined;
165
+ }
package/src/index.ts CHANGED
@@ -250,6 +250,7 @@ export * from './core/modules/permissions/permissions-scanner';
250
250
  export * from './core/modules/system-setup/core-system-setup.controller';
251
251
  export * from './core/modules/system-setup/core-system-setup.module';
252
252
  export * from './core/modules/system-setup/core-system-setup.service';
253
+ export * from './core/modules/system-setup/system-setup-http-init.helper';
253
254
 
254
255
  // =====================================================================================================================
255
256
  // Core - Modules - Tus