@lenne.tech/nest-server 12.4.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 +2 -1
- package/.claude/rules/testing.md +5 -4
- package/CLAUDE.md +4 -0
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/helpers/config-endpoint.helper.d.ts +3 -0
- package/dist/core/common/helpers/config-endpoint.helper.js +17 -0
- package/dist/core/common/helpers/config-endpoint.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.d.ts +3 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +72 -0
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -0
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/common/services/config.service.d.ts +3 -0
- package/dist/core/common/services/config.service.js +17 -3
- package/dist/core/common/services/config.service.js.map +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/hub/core-hub.service.js +1 -13
- package/dist/core/modules/hub/core-hub.service.js.map +1 -1
- package/dist/core/modules/hub/helpers/hub-mask.helper.d.ts +1 -1
- package/dist/core/modules/hub/helpers/hub-mask.helper.js +1 -42
- package/dist/core/modules/hub/helpers/hub-mask.helper.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/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/server/server.controller.d.ts +1 -1
- package/dist/server/server.controller.js +2 -2
- package/dist/server/server.controller.js.map +1 -1
- package/migration-guides/12.4.x-to-12.5.x.md +136 -0
- package/migration-guides/12.5.x-to-12.6.x.md +213 -0
- package/package.json +5 -4
- package/src/core/common/helpers/config-endpoint.helper.ts +56 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +175 -0
- package/src/core/common/interfaces/server-options.interface.ts +26 -5
- package/src/core/common/services/config.service.ts +41 -3
- 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/hub/README.md +3 -1
- package/src/core/modules/hub/core-hub.service.ts +4 -20
- package/src/core/modules/hub/helpers/hub-mask.helper.ts +4 -92
- package/src/core/modules/system-setup/README.md +20 -4
- package/src/core/modules/system-setup/core-system-setup.service.ts +290 -45
- package/src/index.ts +2 -0
- package/src/server/server.controller.ts +7 -2
|
@@ -1,95 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* The Hub config viewer's masker — since 12.5.0 the framework-wide `redactSecrets()`
|
|
3
|
+
* (`common/helpers/redact-secrets.helper.ts`), which `GET /config` and the `ConfigService` debug output use too.
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
* service-owned object to the response pipeline — `CheckSecurityInterceptor` deletes secret-named
|
|
6
|
-
* keys IN PLACE, which would corrupt the running server config. Cloning here is the guarantee.
|
|
5
|
+
* Kept under its old name so no import path broke.
|
|
7
6
|
*/
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Key-name heuristics that mark a value as secret. Matched case-insensitively against each key.
|
|
11
|
-
*
|
|
12
|
-
* `access[-_]?key` also covers `accessKeyId`: the trailing `(^|[^a-z])key([^a-z]|$)` alternative
|
|
13
|
-
* does NOT, because the `i` flag makes `[^a-z]` reject an uppercase letter, so `…sKeyI…` fails it.
|
|
14
|
-
* `s3.secretAccessKey` was already caught by `secret`; the ID was not.
|
|
15
|
-
*/
|
|
16
|
-
const SECRET_KEY_PATTERN =
|
|
17
|
-
/secret|passwd|password|passphrase|credential|api[-_]?key|access[-_]?key|access[-_]?token|refresh[-_]?token|private[-_]?key|encryption|\btoken\b|\bpass\b|(^|[^a-z])key([^a-z]|$)/i;
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Value-shape heuristic: a connection URI carrying `scheme://user:password@host`.
|
|
21
|
-
*
|
|
22
|
-
* The user part is `*`, not `+`, so the PASSWORD-ONLY form is matched too:
|
|
23
|
-
* `redis://:password@host` is the canonical Redis URL (Redis < 6 has no username, and
|
|
24
|
-
* `redis-cli -u`, Heroku Redis and ElastiCache AUTH all emit it). Requiring a non-empty
|
|
25
|
-
* user printed that shape verbatim in the Hub config panel. `redis.url` became a
|
|
26
|
-
* first-class option in 11.33.0, so the shape is newly reachable here.
|
|
27
|
-
*
|
|
28
|
-
* Still safe against false positives: the password group cannot contain `/`, and the `@`
|
|
29
|
-
* must follow it immediately — so `http://host:8080/x@y` does not match.
|
|
30
|
-
*/
|
|
31
|
-
const URI_CREDENTIAL_PATTERN = /^([a-z][a-z0-9+.-]*:\/\/[^/@:\s]*:)([^@/\s]+)(@)/i;
|
|
32
|
-
|
|
33
|
-
const MASK = '***';
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Deep-clone `value` and mask every secret it contains.
|
|
37
|
-
*
|
|
38
|
-
* A value is masked when its key matches {@link SECRET_KEY_PATTERN} or appears in `extraSecretKeys`.
|
|
39
|
-
* Additionally, any string that looks like a credentialed connection URI has its password segment
|
|
40
|
-
* masked regardless of key name.
|
|
41
|
-
*
|
|
42
|
-
* @param value - the object/value to mask (not mutated)
|
|
43
|
-
* @param extraSecretKeys - additional exact key names to always mask (e.g. `security.secretFields`)
|
|
44
|
-
*/
|
|
45
|
-
export function maskConfigDeep<T>(value: T, extraSecretKeys: string[] = []): T {
|
|
46
|
-
const extra = new Set(extraSecretKeys.map((k) => k.toLowerCase()));
|
|
47
|
-
return maskValue(value, false, extra) as T;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function isSecretKey(key: string, extra: Set<string>): boolean {
|
|
51
|
-
return extra.has(key.toLowerCase()) || SECRET_KEY_PATTERN.test(key);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function maskString(value: string): string {
|
|
55
|
-
const uriMatch = value.match(URI_CREDENTIAL_PATTERN);
|
|
56
|
-
if (uriMatch) {
|
|
57
|
-
return value.replace(URI_CREDENTIAL_PATTERN, `$1${MASK}$3`);
|
|
58
|
-
}
|
|
59
|
-
return value;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
function maskValue(value: unknown, keyIsSecret: boolean, extra: Set<string>): unknown {
|
|
63
|
-
if (value === null || value === undefined) {
|
|
64
|
-
return value;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Primitives.
|
|
68
|
-
if (typeof value !== 'object') {
|
|
69
|
-
if (keyIsSecret) {
|
|
70
|
-
return MASK;
|
|
71
|
-
}
|
|
72
|
-
return typeof value === 'string' ? maskString(value) : value;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// A whole secret-keyed object/array is collapsed to the mask (never leak its interior).
|
|
76
|
-
if (keyIsSecret) {
|
|
77
|
-
return MASK;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// Preserve non-plain objects verbatim (Date, Buffer, etc.) — cloning would lose their type and
|
|
81
|
-
// they never carry framework secrets.
|
|
82
|
-
if (value instanceof Date || Buffer.isBuffer(value)) {
|
|
83
|
-
return value;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
if (Array.isArray(value)) {
|
|
87
|
-
return value.map((item) => maskValue(item, false, extra));
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const out: Record<string, unknown> = {};
|
|
91
|
-
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
|
|
92
|
-
out[key] = maskValue(val, isSecretKey(key, extra), extra);
|
|
93
|
-
}
|
|
94
|
-
return out;
|
|
95
|
-
}
|
|
7
|
+
export { redactSecrets as maskConfigDeep } from '../../../common/helpers/redact-secrets.helper.js';
|
|
@@ -259,7 +259,8 @@ NEST_SERVER_CONFIG='{ "systemSetup": { "initialAdmin": { "email": "admin@example
|
|
|
259
259
|
|
|
260
260
|
### Security Best Practices
|
|
261
261
|
|
|
262
|
-
1. **Remove credentials after first deployment** - Once the admin exists, the ENV vars
|
|
262
|
+
1. **Remove credentials after first deployment** - Once the admin exists, the ENV vars change nothing; the boot only
|
|
263
|
+
reads them to finish a setup that was killed halfway (see Security). Removing them closes that path too
|
|
263
264
|
2. **Use secrets management** - Docker Secrets, Kubernetes Secrets, Vault, etc.
|
|
264
265
|
3. **Never commit credentials** - Use `.env` files (gitignored) or external secret stores
|
|
265
266
|
4. **Use strong passwords** - Minimum 8 characters, recommended 16+
|
|
@@ -277,10 +278,19 @@ NEST_SERVER_CONFIG='{ "systemSetup": { "initialAdmin": { "email": "admin@example
|
|
|
277
278
|
3. **Rollback on failure (12.4.0)** - When a step after creating the user fails (account, sync, role),
|
|
278
279
|
the user is removed again, so `needsSetup` stays `true` and the setup can be retried. Before,
|
|
279
280
|
the deployment kept a user without the admin role and was locked for good
|
|
280
|
-
4. **
|
|
281
|
+
4. **A killed setup is finished at the next boot** - A process killed halfway (SIGKILL, OOM) runs no rollback.
|
|
282
|
+
The admin role is therefore written together with the user, so the worst a kill leaves is an administrator
|
|
283
|
+
without a login account. With `initialAdmin` configured, the next boot finishes the setup for that address: it
|
|
284
|
+
adds the credential account with the configured password and sets the role. It also finishes the leftover of an
|
|
285
|
+
older setup (no role, no administrator in the system, and no account or only a credential account with the
|
|
286
|
+
configured password). A user with another password, a social account, a second account or a legacy password (`users.password`, e.g. a
|
|
287
|
+
Legacy-Auth administrator who has not signed in through IAM yet) is never touched. A
|
|
288
|
+
restart within five minutes of the kill finds the old claim still held and tries once more after it goes stale.
|
|
289
|
+
The anonymous HTTP init finishes nothing: once users exist it refuses, as before
|
|
290
|
+
5. **Race condition protection** - MongoDB unique email index prevents duplicates; auto-creation on
|
|
281
291
|
bootstrap is additionally claimed atomically via the `system-setup-locks` marker
|
|
282
|
-
|
|
283
|
-
|
|
292
|
+
6. **Permanent lock** - Once any user exists, init returns 403
|
|
293
|
+
7. **BetterAuth required** - Returns 403 if BetterAuth is not enabled
|
|
284
294
|
|
|
285
295
|
### How It Bypasses disableSignUp
|
|
286
296
|
|
|
@@ -345,6 +355,12 @@ the user stayed behind without the admin role. Since 12.4.0 such a user is remov
|
|
|
345
355
|
the server log says the partially created user "could not be removed", delete that user and its `account` rows and
|
|
346
356
|
retry.
|
|
347
357
|
|
|
358
|
+
**Cause (a killed setup):** the process was killed between creating the user and finishing it, so no rollback ran.
|
|
359
|
+
With `systemSetup.initialAdmin` set to that address and password, restart the instance: the boot finishes the setup
|
|
360
|
+
and logs `Finished an interrupted initial-admin setup`. A restart within five minutes of the kill logs that the
|
|
361
|
+
claim is still held and retries on its own once it has gone stale. Without `initialAdmin` (the setup ran through the
|
|
362
|
+
HTTP init), set it for one start, or delete the user and its `account` rows and run the init again.
|
|
363
|
+
|
|
348
364
|
### Init returns 403 "System setup not available"
|
|
349
365
|
|
|
350
366
|
**Two different guards raise this, and the response cannot tell you which.**
|
|
@@ -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
|
|
package/src/index.ts
CHANGED
|
@@ -32,6 +32,7 @@ export * from './core/common/filters/http-exception-log.filter.js';
|
|
|
32
32
|
export * from './core/common/filters/mongoose-cast-error.filter.js';
|
|
33
33
|
export * from './core/common/helpers/common.helper.js';
|
|
34
34
|
export * from './core/common/helpers/config.helper.js';
|
|
35
|
+
export * from './core/common/helpers/config-endpoint.helper.js';
|
|
35
36
|
export * from './core/common/helpers/content-disposition.helper.js';
|
|
36
37
|
export * from './core/common/helpers/context.helper.js';
|
|
37
38
|
export * from './core/common/helpers/cookies.helper.js';
|
|
@@ -52,6 +53,7 @@ export * from './core/common/helpers/meta.helper.js';
|
|
|
52
53
|
export * from './core/common/helpers/model.helper.js';
|
|
53
54
|
export * from './core/common/helpers/outbound-url.helper.js';
|
|
54
55
|
export * from './core/common/helpers/process-diagnostics.helper.js';
|
|
56
|
+
export * from './core/common/helpers/redact-secrets.helper.js';
|
|
55
57
|
export * from './core/common/helpers/register-enum.helper.js';
|
|
56
58
|
export * from './core/common/helpers/scim.helper.js';
|
|
57
59
|
export * from './core/common/helpers/service.helper.js';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Controller, Get, Render } from '@nestjs/common';
|
|
2
2
|
|
|
3
|
-
import { ConfigService, RoleEnum, Roles } from '../index.js';
|
|
3
|
+
import { ConfigService, configEndpointResponse, RoleEnum, Roles } from '../index.js';
|
|
4
4
|
|
|
5
5
|
@Controller()
|
|
6
6
|
@Roles(RoleEnum.ADMIN)
|
|
@@ -16,9 +16,14 @@ export class ServerController {
|
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* The configuration with every secret masked, and only where `configEndpoint` opens the route (by default in
|
|
21
|
+
* `local`, `ci` and `e2e`; 404 elsewhere). It used to return the configuration verbatim — database URI, auth
|
|
22
|
+
* secrets, mail password — to every administrator.
|
|
23
|
+
*/
|
|
19
24
|
@Get('config')
|
|
20
25
|
@Roles(RoleEnum.ADMIN)
|
|
21
26
|
config() {
|
|
22
|
-
return
|
|
27
|
+
return configEndpointResponse();
|
|
23
28
|
}
|
|
24
29
|
}
|