@lenne.tech/nest-server 12.5.0 → 12.6.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 +1 -1
- package/.claude/rules/testing.md +5 -4
- package/CLAUDE.md +4 -0
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/services/rate-limit-store.d.ts +1 -0
- package/dist/core/common/services/rate-limit-store.js +3 -3
- package/dist/core/common/services/rate-limit-store.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +23 -0
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +31 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +96 -14
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js +8 -1
- package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.d.ts +3 -0
- package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js +29 -0
- package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth.controller.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth.controller.js +51 -0
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.module.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth.module.js +10 -1
- package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
- package/dist/core/modules/system-setup/core-system-setup.service.d.ts +59 -2
- package/dist/core/modules/system-setup/core-system-setup.service.js +157 -28
- package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
- package/migration-guides/12.5.x-to-12.6.x.md +213 -0
- package/package.json +5 -4
- package/src/core/common/interfaces/server-options.interface.ts +6 -5
- package/src/core/common/services/rate-limit-store.ts +9 -3
- package/src/core/modules/better-auth/README.md +27 -0
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +33 -0
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +218 -35
- package/src/core/modules/better-auth/core-better-auth-openapi.helper.ts +8 -1
- package/src/core/modules/better-auth/core-better-auth-verification-link.helper.ts +53 -0
- package/src/core/modules/better-auth/core-better-auth.controller.ts +61 -0
- package/src/core/modules/better-auth/core-better-auth.module.ts +18 -2
- package/src/core/modules/system-setup/README.md +20 -4
- package/src/core/modules/system-setup/core-system-setup.service.ts +290 -45
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { hostname } from 'node:os';
|
|
3
3
|
|
|
4
|
-
import { ForbiddenException, Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
|
4
|
+
import { ForbiddenException, Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
|
5
5
|
import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
|
|
6
6
|
import { isEmail } from 'class-validator';
|
|
7
7
|
import type { Collection } from 'mongodb';
|
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
SYSTEM_SETUP_LOCK_KEY,
|
|
15
15
|
systemSetupMongoLocks,
|
|
16
16
|
} from '../../common/persistence/infrastructure-locks.js';
|
|
17
|
+
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
17
18
|
import type { LockStore } from '../../common/persistence/lock-store.interface.js';
|
|
18
19
|
import { isLocalEnv } from '../../common/helpers/cookies.helper.js';
|
|
19
20
|
import type { ISystemSetupInitialAdmin } from '../../common/interfaces/server-options.interface.js';
|
|
@@ -48,6 +49,15 @@ const SETUP_LOCK_COLLECTION = SYSTEM_SETUP_LOCK_COLLECTION;
|
|
|
48
49
|
*/
|
|
49
50
|
const INITIAL_ADMIN_CLAIM_STALE_AFTER_MS = SYSTEM_SETUP_CLAIM_STALE_AFTER_MS;
|
|
50
51
|
|
|
52
|
+
/** How long after the claim goes stale the boot looks at an interrupted setup again (see scheduleInterruptedSetupRetry) */
|
|
53
|
+
const INTERRUPTED_SETUP_RETRY_MARGIN_MS = 5_000;
|
|
54
|
+
|
|
55
|
+
/** An initial admin a killed setup left behind, and whether its credential account is still missing */
|
|
56
|
+
interface IInterruptedInitialAdmin {
|
|
57
|
+
iamUser: { email?: string; id: string; name?: string };
|
|
58
|
+
linkCredential: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
51
61
|
/**
|
|
52
62
|
* Input for creating the initial admin user
|
|
53
63
|
*/
|
|
@@ -105,11 +115,16 @@ export interface SystemSetupStatus {
|
|
|
105
115
|
* - Once any user exists, the init endpoint is permanently locked
|
|
106
116
|
* - Race conditions handled by an atomic claim shared by both entry points
|
|
107
117
|
* - A creation that fails after the user was created removes that user again, so `needsSetup` stays true
|
|
118
|
+
* - The admin role is written together with the user, and a setup that was killed halfway (no rollback ran) is
|
|
119
|
+
* finished at the next boot for the address `initialAdmin` names ({@link resumeInterruptedInitialAdmin})
|
|
108
120
|
*/
|
|
109
121
|
@Injectable()
|
|
110
|
-
export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
122
|
+
export class CoreSystemSetupService implements OnApplicationBootstrap, OnApplicationShutdown {
|
|
111
123
|
private readonly logger = new Logger(CoreSystemSetupService.name);
|
|
112
124
|
|
|
125
|
+
/** The one planned retry of an interrupted setup whose claim was still held (see scheduleInterruptedSetupRetry) */
|
|
126
|
+
private interruptedSetupRetry?: ReturnType<typeof setTimeout>;
|
|
127
|
+
|
|
113
128
|
/** Who holds the claim: one owner per instance, so a second concurrent claim of the same process is refused too */
|
|
114
129
|
private readonly claimOwner = `${hostname()}:${process.pid}:${randomUUID()}`;
|
|
115
130
|
|
|
@@ -132,6 +147,12 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
132
147
|
await this.reportSetupReachability();
|
|
133
148
|
}
|
|
134
149
|
|
|
150
|
+
/** Cancel a planned retry of an interrupted setup, so a closing application leaves no timer behind */
|
|
151
|
+
onApplicationShutdown(): void {
|
|
152
|
+
clearTimeout(this.interruptedSetupRetry);
|
|
153
|
+
this.interruptedSetupRetry = undefined;
|
|
154
|
+
}
|
|
155
|
+
|
|
135
156
|
/**
|
|
136
157
|
* Create the initial admin from `systemSetup.initialAdmin` when zero users exist (the boot half of
|
|
137
158
|
* {@link onApplicationBootstrap}). Not gated by `systemSetup.httpInit`: it is the deployment's own configuration,
|
|
@@ -145,6 +166,11 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
145
166
|
|
|
146
167
|
const status = await this.getSetupStatus();
|
|
147
168
|
if (!status.needsSetup) {
|
|
169
|
+
// Users exist. One of them may be the initial admin of a setup that was killed halfway (SIGKILL, OOM): no
|
|
170
|
+
// rollback ran, so it has no login account or no admin role, and the setup refuses from now on. Finish it.
|
|
171
|
+
if (status.betterAuthEnabled && (await this.resumeInterruptedInitialAdmin(initialAdmin)) === 'claimed') {
|
|
172
|
+
this.scheduleInterruptedSetupRetry(initialAdmin);
|
|
173
|
+
}
|
|
148
174
|
return;
|
|
149
175
|
}
|
|
150
176
|
|
|
@@ -373,6 +399,260 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
373
399
|
}
|
|
374
400
|
}
|
|
375
401
|
|
|
402
|
+
/**
|
|
403
|
+
* Everything the initial admin needs after its user exists: the credential account (unless it has one), the link
|
|
404
|
+
* to the app user, the admin role, the legacy password. {@link createInitialAdmin} runs it for a new user,
|
|
405
|
+
* {@link resumeInterruptedInitialAdmin} for one a killed setup left behind — so both finish the same way.
|
|
406
|
+
*
|
|
407
|
+
* Throws on the first failure; the caller decides what to undo.
|
|
408
|
+
*/
|
|
409
|
+
protected async finishInitialAdmin(
|
|
410
|
+
context: {
|
|
411
|
+
internalAdapter: { linkAccount(account: Record<string, unknown>): Promise<unknown> };
|
|
412
|
+
password: { hash(password: string): Promise<string> };
|
|
413
|
+
},
|
|
414
|
+
iamUser: { email?: string; id: string; name?: string },
|
|
415
|
+
input: SystemSetupInitInput,
|
|
416
|
+
normalizedPassword: string,
|
|
417
|
+
options: { linkCredential: boolean },
|
|
418
|
+
): Promise<void> {
|
|
419
|
+
if (options.linkCredential) {
|
|
420
|
+
// Hash password and create credential account
|
|
421
|
+
const hashedPassword = await context.password.hash(normalizedPassword);
|
|
422
|
+
// better-auth 1.7.0–1.7.2 key accounts by (issuer, accountId) and require the issuer;
|
|
423
|
+
// credential accounts carry a synthetic one, always derived via the helper, never a
|
|
424
|
+
// hand-written literal. better-auth 1.7.3+ went back to (providerId, accountId) and knows no
|
|
425
|
+
// issuer field, so the helper answers `undefined` there and nothing is written.
|
|
426
|
+
//
|
|
427
|
+
// The parameter type above is structural, so a vendored core compiled against better-auth 1.7.0–1.7.2 (whose
|
|
428
|
+
// own type requires `issuer`, which a conditional spread reads as optional) builds as well.
|
|
429
|
+
const credentialIssuer = legacyCredentialAccountIssuer();
|
|
430
|
+
await context.internalAdapter.linkAccount({
|
|
431
|
+
accountId: iamUser.id,
|
|
432
|
+
...(credentialIssuer ? { issuer: credentialIssuer } : {}),
|
|
433
|
+
password: hashedPassword,
|
|
434
|
+
providerId: 'credential',
|
|
435
|
+
userId: iamUser.id,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Sync to nest-server users collection
|
|
440
|
+
const syncedUser = await this.userMapper.linkOrCreateUser({
|
|
441
|
+
email: iamUser.email,
|
|
442
|
+
emailVerified: true,
|
|
443
|
+
id: iamUser.id,
|
|
444
|
+
name: iamUser.name,
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
if (!syncedUser) {
|
|
448
|
+
throw new Error('Failed to sync user to nest-server collection');
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Set admin role directly — the framework's own decision, as system work. createUser already wrote it for a new
|
|
452
|
+
// user; this write is what gives it to the leftover of an older setup, and keeps it when the sync touched the row.
|
|
453
|
+
const sql = getBetterAuthSqlStore();
|
|
454
|
+
if (sql) {
|
|
455
|
+
await sql.updateUserAsSystem(String(syncedUser._id), { roles: [RoleEnum.ADMIN] });
|
|
456
|
+
} else {
|
|
457
|
+
await this.connection
|
|
458
|
+
.collection('users')
|
|
459
|
+
.updateOne({ _id: syncedUser._id }, { $set: { roles: [RoleEnum.ADMIN], updatedAt: new Date() } });
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// Sync password to Legacy Auth for backwards compatibility
|
|
463
|
+
await this.userMapper.syncPasswordToLegacy(iamUser.id, input.email, input.password);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Whether any user holds the admin role, wherever the `users` table lives (see {@link countUsers})
|
|
468
|
+
*/
|
|
469
|
+
protected async hasAdmin(): Promise<boolean> {
|
|
470
|
+
const store = getBetterAuthSqlStore()?.users ?? (await getPersistenceRuntime()?.iamStorage())?.users;
|
|
471
|
+
const admins = store
|
|
472
|
+
? await store.count({ roles: RoleEnum.ADMIN })
|
|
473
|
+
: await this.connection.collection('users').countDocuments({ roles: RoleEnum.ADMIN });
|
|
474
|
+
return admins > 0;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* The initial admin a killed setup left behind for `email`, or `undefined` when the user with that address is
|
|
479
|
+
* anything else. A user qualifies only where nothing but the setup can have produced its state:
|
|
480
|
+
*
|
|
481
|
+
* - an administrator without any account: killed between createUser (which writes the role) and linkAccount;
|
|
482
|
+
* - no administrator in the system, and the user has no account: the same, from a setup before the role moved into
|
|
483
|
+
* createUser;
|
|
484
|
+
* - no administrator in the system, and the user's only account is a credential account with the configured
|
|
485
|
+
* password: killed between linkAccount and the role update of such a setup. The password is the evidence — a
|
|
486
|
+
* user who signed up with the administrator's address has a password of their own.
|
|
487
|
+
*
|
|
488
|
+
* A social account, a second account, another password or a legacy password ({@link hasLegacyPassword}) never
|
|
489
|
+
* qualifies, and a finished setup (administrator with an account) is answered without comparing the password.
|
|
490
|
+
*/
|
|
491
|
+
protected async findInterruptedInitialAdmin(
|
|
492
|
+
context: {
|
|
493
|
+
internalAdapter: {
|
|
494
|
+
findUserByEmail(
|
|
495
|
+
email: string,
|
|
496
|
+
options: { includeAccounts: boolean },
|
|
497
|
+
): Promise<null | {
|
|
498
|
+
accounts: Array<{ password?: null | string; providerId: string }>;
|
|
499
|
+
user: { email?: string; id: string; name?: string; roles?: unknown };
|
|
500
|
+
}>;
|
|
501
|
+
};
|
|
502
|
+
password: { verify(data: { hash: string; password: string }): Promise<boolean> };
|
|
503
|
+
},
|
|
504
|
+
email: string,
|
|
505
|
+
normalizedPassword: string,
|
|
506
|
+
): Promise<IInterruptedInitialAdmin | undefined> {
|
|
507
|
+
const found = await context.internalAdapter.findUserByEmail(email, { includeAccounts: true });
|
|
508
|
+
if (!found?.user) {
|
|
509
|
+
return undefined;
|
|
510
|
+
}
|
|
511
|
+
const isAdmin = Array.isArray(found.user.roles) && found.user.roles.includes(RoleEnum.ADMIN);
|
|
512
|
+
const accounts = found.accounts ?? [];
|
|
513
|
+
|
|
514
|
+
if (accounts.length === 0) {
|
|
515
|
+
if (!isAdmin && (await this.hasAdmin())) {
|
|
516
|
+
return undefined;
|
|
517
|
+
}
|
|
518
|
+
return (await this.hasLegacyPassword(found.user, email))
|
|
519
|
+
? undefined
|
|
520
|
+
: { iamUser: found.user, linkCredential: true };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
if (isAdmin || accounts.length !== 1) {
|
|
524
|
+
return undefined;
|
|
525
|
+
}
|
|
526
|
+
const [account] = accounts;
|
|
527
|
+
if (account.providerId !== 'credential' || !account.password) {
|
|
528
|
+
return undefined;
|
|
529
|
+
}
|
|
530
|
+
if (!(await context.password.verify({ hash: account.password, password: normalizedPassword }))) {
|
|
531
|
+
return undefined;
|
|
532
|
+
}
|
|
533
|
+
if (await this.hasAdmin()) {
|
|
534
|
+
return undefined;
|
|
535
|
+
}
|
|
536
|
+
return (await this.hasLegacyPassword(found.user, email))
|
|
537
|
+
? undefined
|
|
538
|
+
: { iamUser: found.user, linkCredential: false };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Whether the app user behind `iamUser` carries a legacy password (`users.password`). A killed setup never has one:
|
|
543
|
+
* syncing it is the last step of {@link finishInitialAdmin}, and neither createUser nor the sync writes it. So a user
|
|
544
|
+
* with one did not come from the setup — typically a Legacy-Auth administrator who has not signed in through IAM
|
|
545
|
+
* yet, who has no Better-Auth account either. Finishing such a user would replace their own password with the
|
|
546
|
+
* configured one.
|
|
547
|
+
*/
|
|
548
|
+
protected async hasLegacyPassword(iamUser: { email?: string; id: string }, email: string): Promise<boolean> {
|
|
549
|
+
const store = getBetterAuthSqlStore()?.users ?? (await getPersistenceRuntime()?.iamStorage())?.users;
|
|
550
|
+
const row = store
|
|
551
|
+
? await store.findById(iamUser.id, { select: ['password'] })
|
|
552
|
+
: await this.connection
|
|
553
|
+
.collection('users')
|
|
554
|
+
.findOne({ email: iamUser.email ?? email }, { projection: { password: 1 } });
|
|
555
|
+
return typeof row?.password === 'string' && row.password.length > 0;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Finish the initial admin a killed setup left behind (see {@link findInterruptedInitialAdmin}) for the address and
|
|
560
|
+
* password `systemSetup.initialAdmin` configures — the boot path only. The anonymous `POST /system-setup/init` never
|
|
561
|
+
* gets here: once users exist it refuses, as before, because finishing would set a password on an existing account.
|
|
562
|
+
*
|
|
563
|
+
* Runs under the same claim as {@link createInitialAdmin}, so of N booting replicas one finishes it. Never throws: a
|
|
564
|
+
* failure is logged and the user is kept (it existed before this call), so the next boot can try again.
|
|
565
|
+
*
|
|
566
|
+
* @returns `'claimed'` when the claim is held (by the killed attempt, until it goes stale), `'none'` when there is
|
|
567
|
+
* nothing to finish
|
|
568
|
+
*/
|
|
569
|
+
protected async resumeInterruptedInitialAdmin(
|
|
570
|
+
initialAdmin: ISystemSetupInitialAdmin,
|
|
571
|
+
): Promise<'claimed' | 'done' | 'failed' | 'none'> {
|
|
572
|
+
const authInstance = this.betterAuthService.getInstance();
|
|
573
|
+
if (!authInstance) {
|
|
574
|
+
return 'none';
|
|
575
|
+
}
|
|
576
|
+
const input: SystemSetupInitInput = {
|
|
577
|
+
email: initialAdmin.email,
|
|
578
|
+
name: initialAdmin.name,
|
|
579
|
+
password: initialAdmin.password,
|
|
580
|
+
};
|
|
581
|
+
let claimed = false;
|
|
582
|
+
try {
|
|
583
|
+
const context = await authInstance.$context;
|
|
584
|
+
const normalizedPassword = this.userMapper.normalizePasswordForIam(input.password);
|
|
585
|
+
if (!(await this.findInterruptedInitialAdmin(context, input.email, normalizedPassword))) {
|
|
586
|
+
return 'none';
|
|
587
|
+
}
|
|
588
|
+
if (!(await this.claimInitialAdminSetup())) {
|
|
589
|
+
return 'claimed';
|
|
590
|
+
}
|
|
591
|
+
claimed = true;
|
|
592
|
+
|
|
593
|
+
// Look again under the claim: another replica may have finished it in between
|
|
594
|
+
const interrupted = await this.findInterruptedInitialAdmin(context, input.email, normalizedPassword);
|
|
595
|
+
if (!interrupted) {
|
|
596
|
+
await this.releaseInitialAdminSetupClaim();
|
|
597
|
+
return 'none';
|
|
598
|
+
}
|
|
599
|
+
await this.finishInitialAdmin(context, interrupted.iamUser, input, normalizedPassword, {
|
|
600
|
+
linkCredential: interrupted.linkCredential,
|
|
601
|
+
});
|
|
602
|
+
this.logger.warn(
|
|
603
|
+
`Finished an interrupted initial-admin setup for ${input.email}: the previous attempt was stopped before ` +
|
|
604
|
+
`it completed (${interrupted.linkCredential ? 'no login account' : 'no admin role'}).`,
|
|
605
|
+
);
|
|
606
|
+
return 'done';
|
|
607
|
+
} catch (error) {
|
|
608
|
+
if (claimed) {
|
|
609
|
+
await this.releaseInitialAdminSetupClaim();
|
|
610
|
+
}
|
|
611
|
+
this.logger.error(
|
|
612
|
+
`Finishing the interrupted initial-admin setup for ${input.email} failed ` +
|
|
613
|
+
`(${error instanceof Error ? error.message : 'Unknown error'}); the next start tries again.`,
|
|
614
|
+
);
|
|
615
|
+
return 'failed';
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Try an interrupted setup once more after the claim of the killed attempt has gone stale. A process restarted
|
|
621
|
+
* within that window (the usual case after an OOM kill) finds the claim held, and without this retry the deployment
|
|
622
|
+
* would stay without a way in until the next deploy. One retry, cancelled at shutdown.
|
|
623
|
+
*/
|
|
624
|
+
protected scheduleInterruptedSetupRetry(initialAdmin: ISystemSetupInitialAdmin): void {
|
|
625
|
+
const delayMs = INITIAL_ADMIN_CLAIM_STALE_AFTER_MS + INTERRUPTED_SETUP_RETRY_MARGIN_MS;
|
|
626
|
+
this.logger.warn(
|
|
627
|
+
`An interrupted initial-admin setup for ${initialAdmin.email} was found, but the claim of the previous attempt ` +
|
|
628
|
+
`is still held; trying again in ${Math.ceil(delayMs / 60_000)} minutes.`,
|
|
629
|
+
);
|
|
630
|
+
clearTimeout(this.interruptedSetupRetry);
|
|
631
|
+
this.interruptedSetupRetry = setTimeout(() => {
|
|
632
|
+
this.interruptedSetupRetry = undefined;
|
|
633
|
+
// Cannot reject: retryInterruptedInitialAdmin() catches everything it awaits.
|
|
634
|
+
void this.retryInterruptedInitialAdmin(initialAdmin);
|
|
635
|
+
}, delayMs);
|
|
636
|
+
this.interruptedSetupRetry.unref?.();
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** The retry {@link scheduleInterruptedSetupRetry} planned; names how to clear the claim when it is still held */
|
|
640
|
+
protected async retryInterruptedInitialAdmin(initialAdmin: ISystemSetupInitialAdmin): Promise<void> {
|
|
641
|
+
try {
|
|
642
|
+
if ((await this.resumeInterruptedInitialAdmin(initialAdmin)) === 'claimed') {
|
|
643
|
+
const claim = await this.setupClaimLocation();
|
|
644
|
+
this.logger.error(
|
|
645
|
+
`The interrupted initial-admin setup for ${initialAdmin.email} is still blocked by the claim in ` +
|
|
646
|
+
`${claim.where}. If no other instance is setting up, ${claim.remedy} and restart.`,
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
} catch (error) {
|
|
650
|
+
this.logger.error(
|
|
651
|
+
`Retrying the interrupted initial-admin setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
376
656
|
/**
|
|
377
657
|
* Remove the user a failed {@link createInitialAdmin} had already created: Better-Auth's sessions and accounts and
|
|
378
658
|
* the `users` row, which Better-Auth and the user model share. Without it the deployment keeps a user without the
|
|
@@ -531,11 +811,18 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
531
811
|
// FORBIDDEN/validation_context_missing and no initial admin is created. Fail-closed, but
|
|
532
812
|
// opaque. A project using that hook must provision the first admin another way — see
|
|
533
813
|
// migration-guides/11.36.x-to-11.37.0.md §7.
|
|
814
|
+
//
|
|
815
|
+
// The admin role is part of this write (`roles` is a Better-Auth field of the shared users row; `input: false`
|
|
816
|
+
// binds only the API, not the internal adapter). Written in a separate step after it, a process killed in
|
|
817
|
+
// between (SIGKILL, OOM) left a user without the role: users existed, `needsSetup` was false, and the
|
|
818
|
+
// deployment had no administrator and no way to one. Now the worst a killed setup leaves is an administrator
|
|
819
|
+
// without a login account, which the next boot finishes (resumeInterruptedInitialAdmin).
|
|
534
820
|
const iamUser = await context.internalAdapter.createUser(
|
|
535
821
|
{
|
|
536
822
|
email: input.email,
|
|
537
823
|
emailVerified: true,
|
|
538
824
|
name: input.name || input.email.split('@')[0],
|
|
825
|
+
roles: [RoleEnum.ADMIN],
|
|
539
826
|
},
|
|
540
827
|
{ method: 'admin' },
|
|
541
828
|
);
|
|
@@ -545,49 +832,7 @@ export class CoreSystemSetupService implements OnApplicationBootstrap {
|
|
|
545
832
|
}
|
|
546
833
|
createdIamUserId = iamUser.id;
|
|
547
834
|
|
|
548
|
-
|
|
549
|
-
const hashedPassword = await context.password.hash(normalizedPassword);
|
|
550
|
-
// better-auth 1.7.0–1.7.2 key accounts by (issuer, accountId) and require the issuer;
|
|
551
|
-
// credential accounts carry a synthetic one, always derived via the helper, never a
|
|
552
|
-
// hand-written literal. better-auth 1.7.3+ went back to (providerId, accountId) and knows no
|
|
553
|
-
// issuer field, so the helper answers `undefined` there and nothing is written.
|
|
554
|
-
//
|
|
555
|
-
// Cast to the adapter's OWN parameter type: against better-auth 1.7.0–1.7.2 that type requires
|
|
556
|
-
// `issuer`, and a conditional spread reads as optional — a vendored core compiled against
|
|
557
|
-
// those versions would otherwise not build.
|
|
558
|
-
const credentialIssuer = legacyCredentialAccountIssuer();
|
|
559
|
-
await context.internalAdapter.linkAccount({
|
|
560
|
-
accountId: iamUser.id,
|
|
561
|
-
...(credentialIssuer ? { issuer: credentialIssuer } : {}),
|
|
562
|
-
password: hashedPassword,
|
|
563
|
-
providerId: 'credential',
|
|
564
|
-
userId: iamUser.id,
|
|
565
|
-
} as Parameters<typeof context.internalAdapter.linkAccount>[0]);
|
|
566
|
-
|
|
567
|
-
// Sync to nest-server users collection
|
|
568
|
-
const syncedUser = await this.userMapper.linkOrCreateUser({
|
|
569
|
-
email: iamUser.email,
|
|
570
|
-
emailVerified: true,
|
|
571
|
-
id: iamUser.id,
|
|
572
|
-
name: iamUser.name,
|
|
573
|
-
});
|
|
574
|
-
|
|
575
|
-
if (!syncedUser) {
|
|
576
|
-
throw new Error('Failed to sync user to nest-server collection');
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
// Set admin role directly — the framework's own decision, as system work
|
|
580
|
-
const sql = getBetterAuthSqlStore();
|
|
581
|
-
if (sql) {
|
|
582
|
-
await sql.updateUserAsSystem(String(syncedUser._id), { roles: ['admin'] });
|
|
583
|
-
} else {
|
|
584
|
-
await this.connection
|
|
585
|
-
.collection('users')
|
|
586
|
-
.updateOne({ _id: syncedUser._id }, { $set: { roles: ['admin'], updatedAt: new Date() } });
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
// Sync password to Legacy Auth for backwards compatibility
|
|
590
|
-
await this.userMapper.syncPasswordToLegacy(iamUser.id, input.email, input.password);
|
|
835
|
+
await this.finishInitialAdmin(context, iamUser, input, normalizedPassword, { linkCredential: true });
|
|
591
836
|
|
|
592
837
|
this.logger.log(`Initial admin user created: ${input.email}`);
|
|
593
838
|
|