@lenne.tech/nest-server 12.10.0 → 12.11.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/better-auth.md +19 -0
- package/.claude/rules/configurable-features.md +12 -10
- package/.claude/rules/package-management.md +10 -8
- package/.claude/rules/role-system.md +4 -1
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +5 -0
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/decorators/unified-field.decorator.js +5 -2
- package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
- package/dist/core/common/helpers/config.helper.js +31 -9
- package/dist/core/common/helpers/config.helper.js.map +1 -1
- package/dist/core/common/helpers/graceful-shutdown.helper.js +3 -1
- package/dist/core/common/helpers/graceful-shutdown.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +2 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +31 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +8 -3
- package/dist/core/common/helpers/graphql-ws-connection.helper.js +44 -0
- package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
- package/dist/core/common/helpers/http-stream-auth.helper.d.ts +13 -0
- package/dist/core/common/helpers/http-stream-auth.helper.js +90 -0
- package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
- package/dist/core/common/helpers/shutdown-state.helper.d.ts +3 -0
- package/dist/core/common/helpers/shutdown-state.helper.js +11 -0
- package/dist/core/common/helpers/shutdown-state.helper.js.map +1 -0
- package/dist/core/common/interfaces/cron-job-config-with-utc-offset.interface.d.ts +1 -1
- package/dist/core/common/interfaces/cron-job-config.interface.d.ts +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +14 -0
- package/dist/core/common/plugins/complexity.plugin.js +73 -9
- package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
- package/dist/core/common/services/core-cron-jobs.service.d.ts +13 -0
- package/dist/core/common/services/core-cron-jobs.service.js +129 -4
- package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +48 -4
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
- package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
- package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +10 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +105 -19
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
- package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
- package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
- package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
- package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
- package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
- package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
- package/dist/core/modules/health-check/core-health-check.module.js +13 -2
- package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
- package/dist/core/modules/health-check/core-health-check.service.js +66 -29
- package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
- package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
- package/dist/core/modules/sync/core-sync.service.js +11 -1
- package/dist/core/modules/sync/core-sync.service.js.map +1 -1
- package/dist/core.module.js +5 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +18 -6
- package/docs/offline-sync-protocol.md +5 -3
- package/migration-guides/12.10.0-to-12.10.1.md +182 -0
- package/migration-guides/12.10.x-to-12.11.x.md +295 -0
- package/package.json +17 -17
- package/src/core/common/decorators/unified-field.decorator.ts +14 -4
- package/src/core/common/helpers/config.helper.ts +55 -8
- package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
- package/src/core/common/helpers/graphql-upload.helper.ts +93 -0
- package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
- package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
- package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
- package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
- package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
- package/src/core/common/interfaces/server-options.interface.ts +113 -1
- package/src/core/common/plugins/complexity.plugin.ts +150 -9
- package/src/core/common/services/core-cron-jobs.service.ts +241 -14
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +26 -10
- package/src/core/modules/better-auth/README.md +37 -8
- package/src/core/modules/better-auth/better-auth.config.ts +83 -12
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
- package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
- package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
- package/src/core/modules/better-auth/core-better-auth.controller.ts +6 -3
- package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
- package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
- package/src/core/modules/better-auth/core-better-auth.service.ts +160 -27
- package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
- package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
- package/src/core/modules/health-check/core-health-check.module.ts +37 -2
- package/src/core/modules/health-check/core-health-check.service.ts +154 -59
- package/src/core/modules/sync/README.md +18 -6
- package/src/core/modules/sync/core-sync.service.ts +35 -6
- package/src/core.module.ts +9 -1
- package/src/index.ts +4 -0
- package/src/main.ts +2 -1
|
@@ -96,9 +96,10 @@ export class CoreBetterAuthMiddleware implements NestMiddleware {
|
|
|
96
96
|
|
|
97
97
|
// Also resolve the real session from DB so that BetterAuth's plugin endpoints
|
|
98
98
|
// (2FA, Passkey, etc.) can authenticate via session token.
|
|
99
|
-
// Without this, JWT-only clients cannot use plugin routes.
|
|
99
|
+
// Without this, JWT-only clients cannot use plugin routes. The JWT's OWN session (its `sid`), since
|
|
100
|
+
// 12.11.0 — before, the user's newest one, so a sign-out with one device's JWT ended another device.
|
|
100
101
|
try {
|
|
101
|
-
const sessionResult = await this.betterAuthService.
|
|
102
|
+
const sessionResult = await this.betterAuthService.getJwtSession(jwtPayload);
|
|
102
103
|
if (sessionResult?.session && sessionResult?.user) {
|
|
103
104
|
req.betterAuthSession = { session: sessionResult.session, user: sessionResult.user };
|
|
104
105
|
}
|
|
@@ -169,7 +170,7 @@ export class CoreBetterAuthMiddleware implements NestMiddleware {
|
|
|
169
170
|
|
|
170
171
|
// Resolve real DB session for plugin endpoints (2FA, Passkey, etc.)
|
|
171
172
|
try {
|
|
172
|
-
const sessionResult = await this.betterAuthService.
|
|
173
|
+
const sessionResult = await this.betterAuthService.getJwtSession(jwtPayload);
|
|
173
174
|
if (sessionResult?.session && sessionResult?.user) {
|
|
174
175
|
req.betterAuthSession = { session: sessionResult.session, user: sessionResult.user };
|
|
175
176
|
}
|
|
@@ -432,7 +432,7 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
|
|
|
432
432
|
* Middleware order (important!):
|
|
433
433
|
* 1. CoreBetterAuthMiddleware - Session validation and user mapping for all routes
|
|
434
434
|
* Must run FIRST so that req.betterAuthSession is available for downstream middleware.
|
|
435
|
-
* In JWT mode, this resolves the JWT to
|
|
435
|
+
* In JWT mode, this resolves the JWT to its own DB session (via getJwtSession(), by its `sid`).
|
|
436
436
|
* 2. CoreBetterAuthPathGuardMiddleware - Refuses a non-canonical path under the base path (400), before
|
|
437
437
|
* anything below reads it
|
|
438
438
|
* 3. CoreBetterAuthRateLimitMiddleware - Rate limiting for auth endpoints
|
|
@@ -188,6 +188,7 @@ export class CoreBetterAuthResolver {
|
|
|
188
188
|
@Roles(RoleEnum.S_EVERYONE)
|
|
189
189
|
betterAuthFeatures(): CoreBetterAuthFeaturesModel {
|
|
190
190
|
return {
|
|
191
|
+
emailAndPassword: this.betterAuthService.isEmailAndPasswordEnabled(),
|
|
191
192
|
emailVerification: this.emailVerificationService?.isEnabled() ?? false,
|
|
192
193
|
enabled: this.betterAuthService.isEnabled(),
|
|
193
194
|
jwt: this.betterAuthService.isJwtEnabled(),
|
|
@@ -42,6 +42,12 @@ import {
|
|
|
42
42
|
unavailableBetterAuthOperations,
|
|
43
43
|
} from './core-better-auth-openapi.helper.js';
|
|
44
44
|
import type { IBetterAuthOpenApiDocument, IBetterAuthRuntime } from './core-better-auth-openapi.helper.js';
|
|
45
|
+
import { cachedJwtSession, cachedJwtSessionRecord, rememberJwtSession } from './core-better-auth-jwt-session.cache.js';
|
|
46
|
+
import {
|
|
47
|
+
isEmailAndPasswordSignInEnabled,
|
|
48
|
+
isPasskeyConfigured,
|
|
49
|
+
isTwoFactorConfigured,
|
|
50
|
+
} from './core-better-auth-sign-in-factors.helper.js';
|
|
45
51
|
import { isJwtShaped } from './core-better-auth-token.helper.js';
|
|
46
52
|
import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
|
|
47
53
|
import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
|
|
@@ -657,31 +663,29 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
657
663
|
}
|
|
658
664
|
|
|
659
665
|
/**
|
|
660
|
-
* Checks if 2FA is enabled.
|
|
661
|
-
*
|
|
662
|
-
* Only disabled when explicitly set to:
|
|
663
|
-
* - `false`
|
|
664
|
-
* - `{ enabled: false }`
|
|
666
|
+
* Checks if 2FA is enabled: on by default, off with `false` / `{ enabled: false }` — and since 12.11.0 off while
|
|
667
|
+
* sign-in runs through a provider alone, unless switched on with `true` / `{ enabled: true }` (`isSignInFactorEnabled()`).
|
|
665
668
|
*/
|
|
666
669
|
isTwoFactorEnabled(): boolean {
|
|
667
|
-
|
|
668
|
-
if (this.config.twoFactor === false) return false;
|
|
669
|
-
if (typeof this.config.twoFactor === 'object' && this.config.twoFactor?.enabled === false) return false;
|
|
670
|
-
return true;
|
|
670
|
+
return this.isEnabled() && isTwoFactorConfigured(this.config);
|
|
671
671
|
}
|
|
672
672
|
|
|
673
673
|
/**
|
|
674
|
-
* Checks if Passkey/WebAuthn is enabled.
|
|
675
|
-
*
|
|
676
|
-
*
|
|
677
|
-
* - `false`
|
|
678
|
-
* - `{ enabled: false }`
|
|
674
|
+
* Checks if Passkey/WebAuthn is enabled: on by default, off with `false` / `{ enabled: false }` — and since 12.11.0
|
|
675
|
+
* off while sign-in runs through a provider alone, unless switched on with `true` / `{ enabled: true }`
|
|
676
|
+
* (`isSignInFactorEnabled()`).
|
|
679
677
|
*/
|
|
680
678
|
isPasskeyEnabled(): boolean {
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
679
|
+
return this.isEnabled() && isPasskeyConfigured(this.config);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Checks if e-mail and password sign-in is enabled: on by default, off with `emailAndPassword.enabled: false`
|
|
684
|
+
* (reported by `GET /iam/features` as `emailAndPassword` since 12.11.0, so a frontend that signs in through a
|
|
685
|
+
* provider alone can hide the form).
|
|
686
|
+
*/
|
|
687
|
+
isEmailAndPasswordEnabled(): boolean {
|
|
688
|
+
return this.isEnabled() && isEmailAndPasswordSignInEnabled(this.config);
|
|
685
689
|
}
|
|
686
690
|
|
|
687
691
|
/**
|
|
@@ -1534,24 +1538,153 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1534
1538
|
const alg = header.alg;
|
|
1535
1539
|
const kid = header.kid;
|
|
1536
1540
|
|
|
1537
|
-
|
|
1541
|
+
let payload: null | { [key: string]: any; email?: string; sub: string } = null;
|
|
1538
1542
|
if (alg === 'HS256') {
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1543
|
+
// For HS256 (symmetric), verify with the BetterAuth secret
|
|
1544
|
+
payload = await this.verifyHs256Token(token);
|
|
1545
|
+
} else if (kid) {
|
|
1546
|
+
// For asymmetric algorithms (EdDSA, RS256, ES256), use JWKS — from MongoDB or the SQL source, whichever holds them
|
|
1547
|
+
payload = await this.verifyJwksToken(token, kid, alg);
|
|
1548
|
+
} else {
|
|
1549
|
+
this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
|
|
1550
|
+
return null;
|
|
1545
1551
|
}
|
|
1546
1552
|
|
|
1547
|
-
|
|
1548
|
-
return null;
|
|
1553
|
+
// A signature and an expiry are not enough (12.11.0): the session the JWT was issued from must still live
|
|
1554
|
+
return payload && (await this.isJwtSessionLive(payload)) ? payload : null;
|
|
1549
1555
|
} catch (error) {
|
|
1550
1556
|
this.logger.debug(`JWT verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
1551
1557
|
return null;
|
|
1552
1558
|
}
|
|
1553
1559
|
}
|
|
1554
1560
|
|
|
1561
|
+
/**
|
|
1562
|
+
* The session a Better-Auth JWT was issued from, with its user (12.11.0) — what the middleware hands Better-Auth's
|
|
1563
|
+
* plugin routes (`req.betterAuthSession`) for a JWT request.
|
|
1564
|
+
*
|
|
1565
|
+
* Before 12.11.0 the middleware took the user's NEWEST active session instead (`getActiveSessionForUser()`), whatever
|
|
1566
|
+
* session the JWT came from: `POST /iam/sign-out` with the JWT of one device signed out the device that signed in
|
|
1567
|
+
* last, and the first device's JWT kept working. Asked through Better-Auth's own adapter by the JWT's `sid`, and
|
|
1568
|
+
* cached with the liveness answer of {@link isJwtSessionLive} for {@link jwtSessionCacheTtlMs}.
|
|
1569
|
+
*
|
|
1570
|
+
* @returns the session and its user, or nulls for a JWT without `sid`, a session that is gone, expired or belongs to
|
|
1571
|
+
* another user, and a failed lookup
|
|
1572
|
+
*/
|
|
1573
|
+
async getJwtSession(payload: { [key: string]: any; sub: string } | null | undefined): Promise<SessionResult> {
|
|
1574
|
+
const none: SessionResult = { session: null, user: null };
|
|
1575
|
+
const sessionId: unknown = payload?.sid;
|
|
1576
|
+
const userId = payload?.sub ? String(payload.sub) : '';
|
|
1577
|
+
if (!this.isEnabled() || typeof sessionId !== 'string' || !sessionId || !userId) {
|
|
1578
|
+
return none;
|
|
1579
|
+
}
|
|
1580
|
+
const now = Date.now();
|
|
1581
|
+
if (this.jwtSessionCacheTtlMs > 0) {
|
|
1582
|
+
const cached = cachedJwtSessionRecord(sessionId, userId, now) as SessionResult | undefined;
|
|
1583
|
+
if (cached) {
|
|
1584
|
+
return cached;
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
try {
|
|
1588
|
+
const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
|
|
1589
|
+
const session = await context?.adapter?.findOne?.({
|
|
1590
|
+
model: 'session',
|
|
1591
|
+
where: [{ field: 'id', value: sessionId }],
|
|
1592
|
+
});
|
|
1593
|
+
const expiresAt = session?.expiresAt ? new Date(session.expiresAt).getTime() : NaN;
|
|
1594
|
+
if (!session || String(session.userId) !== userId || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
|
|
1595
|
+
return none;
|
|
1596
|
+
}
|
|
1597
|
+
const user = await context.internalAdapter?.findUserById?.(userId);
|
|
1598
|
+
if (!user) {
|
|
1599
|
+
return none;
|
|
1600
|
+
}
|
|
1601
|
+
const result: SessionResult = {
|
|
1602
|
+
session: {
|
|
1603
|
+
expiresAt: new Date(expiresAt),
|
|
1604
|
+
id: String(session.id),
|
|
1605
|
+
token: session.token,
|
|
1606
|
+
userId,
|
|
1607
|
+
},
|
|
1608
|
+
user: { email: user.email, emailVerified: user.emailVerified, id: String(user.id), name: user.name },
|
|
1609
|
+
};
|
|
1610
|
+
if (this.jwtSessionCacheTtlMs > 0) {
|
|
1611
|
+
rememberJwtSession(sessionId, userId, true, Math.min(now + this.jwtSessionCacheTtlMs, expiresAt), result);
|
|
1612
|
+
}
|
|
1613
|
+
return result;
|
|
1614
|
+
} catch (error) {
|
|
1615
|
+
this.logger.debug(`getJwtSession error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
1616
|
+
return none;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
/**
|
|
1621
|
+
* How long the answer "this JWT's session lives" is kept before the session is asked again, in milliseconds
|
|
1622
|
+
* (12.11.0). A deleted session is forgotten at once, so this bounds only what no deletion hook reports — a session
|
|
1623
|
+
* removed directly in the database, a broadcast lost while Redis was down. A subclass may set another value; `0`
|
|
1624
|
+
* asks for every request.
|
|
1625
|
+
*/
|
|
1626
|
+
protected jwtSessionCacheTtlMs = 10_000;
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* Whether the session a Better-Auth JWT was issued from still lives (12.11.0): it exists, belongs to the token's
|
|
1630
|
+
* subject and has not expired.
|
|
1631
|
+
*
|
|
1632
|
+
* Before 12.11.0 the JWT carried no reference to its session and was accepted on its signature and expiry alone:
|
|
1633
|
+
* after `POST /iam/sign-out`, a revoked session or a deleted user it kept reading and writing for the rest of its
|
|
1634
|
+
* lifetime (15 minutes by default), and so did a copy of it. A JWT without `sid` — issued before 12.11.0 — is refused;
|
|
1635
|
+
* a client fetches a new one with its session (`GET /iam/token`), which the frontend libraries do on the 401.
|
|
1636
|
+
*
|
|
1637
|
+
* Asked through Better-Auth's own adapter by the session id, so it reads wherever Better-Auth keeps its sessions;
|
|
1638
|
+
* with sessions held only in `secondaryStorage` through the user's session list. The answer is cached for
|
|
1639
|
+
* {@link jwtSessionCacheTtlMs} in `core-better-auth-jwt-session.cache.ts`, and a deleted session is forgotten at once
|
|
1640
|
+
* there (on every replica with `redis`). A failed lookup refuses the JWT and is not cached.
|
|
1641
|
+
*/
|
|
1642
|
+
protected async isJwtSessionLive(payload: { [key: string]: any; sub: string }): Promise<boolean> {
|
|
1643
|
+
const sessionId: unknown = payload.sid;
|
|
1644
|
+
const userId = String(payload.sub);
|
|
1645
|
+
if (typeof sessionId !== 'string' || !sessionId) {
|
|
1646
|
+
this.logger.debug('JWT without a session reference refused (issued before 12.11.0)');
|
|
1647
|
+
return false;
|
|
1648
|
+
}
|
|
1649
|
+
const now = Date.now();
|
|
1650
|
+
const cached = this.jwtSessionCacheTtlMs > 0 ? cachedJwtSession(sessionId, userId, now) : undefined;
|
|
1651
|
+
if (cached !== undefined) {
|
|
1652
|
+
return cached;
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
let session: undefined | { expiresAt?: unknown; id?: unknown; userId?: unknown };
|
|
1656
|
+
try {
|
|
1657
|
+
const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
|
|
1658
|
+
if (!context) {
|
|
1659
|
+
return false;
|
|
1660
|
+
}
|
|
1661
|
+
const options = context.options ?? {};
|
|
1662
|
+
if (options.secondaryStorage && !options.session?.storeSessionInDatabase) {
|
|
1663
|
+
const sessions: unknown = await context.internalAdapter?.listSessions?.(userId, { onlyActiveSessions: true });
|
|
1664
|
+
session = (Array.isArray(sessions) ? sessions : []).find(
|
|
1665
|
+
(candidate: { id?: unknown }) => String(candidate?.id) === sessionId,
|
|
1666
|
+
);
|
|
1667
|
+
} else {
|
|
1668
|
+
session =
|
|
1669
|
+
(await context.adapter?.findOne?.({ model: 'session', where: [{ field: 'id', value: sessionId }] })) ??
|
|
1670
|
+
undefined;
|
|
1671
|
+
}
|
|
1672
|
+
} catch (error) {
|
|
1673
|
+
this.logger.warn(
|
|
1674
|
+
`JWT refused: its session could not be looked up (${error instanceof Error ? error.message : 'Unknown error'})`,
|
|
1675
|
+
);
|
|
1676
|
+
return false;
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
const expiresAt = session?.expiresAt ? new Date(session.expiresAt as Date | number | string).getTime() : NaN;
|
|
1680
|
+
const live = !!session && String(session.userId) === userId && Number.isFinite(expiresAt) && expiresAt > Date.now();
|
|
1681
|
+
if (this.jwtSessionCacheTtlMs > 0) {
|
|
1682
|
+
const until = Math.min(now + this.jwtSessionCacheTtlMs, live ? expiresAt : Number.POSITIVE_INFINITY);
|
|
1683
|
+
rememberJwtSession(sessionId, userId, live, until);
|
|
1684
|
+
}
|
|
1685
|
+
return live;
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1555
1688
|
/**
|
|
1556
1689
|
* Verifies an HS256 JWT token using the BetterAuth secret
|
|
1557
1690
|
*/
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Controller, Get } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
import { Roles } from '../../common/decorators/roles.decorator.js';
|
|
4
|
+
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
5
|
+
import { CoreHealthCheckService } from './core-health-check.service.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `GET /health-check/ready` (12.11.0): the readiness check beside the liveness check `GET /health-check`.
|
|
9
|
+
*
|
|
10
|
+
* Registered by `CoreHealthCheckModule.forRoot()` only with `healthCheck.readiness`, so without it the route does not
|
|
11
|
+
* exist (404). Public like the liveness check: a load balancer or a Kubernetes readiness probe sends no credential.
|
|
12
|
+
* 200 while every check is up, 503 when one is down or the application shuts down. A project replaces it with a
|
|
13
|
+
* subclass through `CoreModule.forRoot(env, { healthCheck: { readinessController } })` — a subclass that re-declares
|
|
14
|
+
* `readinessCheck()` re-declares its `@Get()` and `@Roles()` too.
|
|
15
|
+
*/
|
|
16
|
+
@Controller()
|
|
17
|
+
@Roles(RoleEnum.ADMIN)
|
|
18
|
+
export class CoreHealthCheckReadinessController {
|
|
19
|
+
constructor(protected readonly healthCheckService: CoreHealthCheckService) {}
|
|
20
|
+
|
|
21
|
+
/** The readiness check: the checks `healthCheck.readiness.checks` lists and the project's readiness indicators */
|
|
22
|
+
@Get('health-check/ready')
|
|
23
|
+
@Roles(RoleEnum.S_EVERYONE)
|
|
24
|
+
async readinessCheck() {
|
|
25
|
+
return this.healthCheckService.readinessCheck();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Logger } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
|
|
4
|
+
|
|
5
|
+
/** The checks `healthCheck.configs` configures, in the order they report */
|
|
6
|
+
export const CORE_HEALTH_CHECK_NAMES = ['database', 'memoryHeap', 'memoryRss', 'storage', 'build'] as const;
|
|
7
|
+
|
|
8
|
+
/** A check `healthCheck.configs` configures */
|
|
9
|
+
export type CoreHealthCheckName = (typeof CORE_HEALTH_CHECK_NAMES)[number];
|
|
10
|
+
|
|
11
|
+
/** Which endpoint a health check answers for: `GET /health-check` (liveness) or `GET /health-check/ready` (readiness) */
|
|
12
|
+
export type CoreHealthCheckKind = 'liveness' | 'readiness';
|
|
13
|
+
|
|
14
|
+
/** The checks the readiness endpoint runs without `healthCheck.readiness.checks` */
|
|
15
|
+
export const DEFAULT_READINESS_CHECKS: readonly CoreHealthCheckName[] = ['database', 'build'];
|
|
16
|
+
|
|
17
|
+
/** The readiness endpoint as the configuration describes it */
|
|
18
|
+
export interface IResolvedHealthCheckReadiness {
|
|
19
|
+
/** The configured checks the readiness endpoint runs, in report order */
|
|
20
|
+
checks: CoreHealthCheckName[];
|
|
21
|
+
/** Whether `GET /health-check/ready` is registered */
|
|
22
|
+
enabled: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const logger = new Logger('CoreHealthCheck');
|
|
26
|
+
const warnedUnknownChecks = new Set<string>();
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolve `healthCheck.readiness` (12.11.0): boolean shorthand and "presence implies enabled".
|
|
30
|
+
*
|
|
31
|
+
* - absent (or `false`, `{ enabled: false }`): no readiness endpoint — the health check is what it was
|
|
32
|
+
* - `true` / `{}`: `GET /health-check/ready` with the default checks (`database`, `build`)
|
|
33
|
+
* - `{ checks: [...] }`: the listed checks of `healthCheck.configs` — a list (or a comma-separated string, which is
|
|
34
|
+
* what an `NSC__HEALTH_CHECK__READINESS__CHECKS` variable gives) of `database`, `memoryHeap`, `memoryRss`, `storage`,
|
|
35
|
+
* `build`. Unknown names are ignored with one warning each; `[]` runs only the project's own readiness indicators.
|
|
36
|
+
*
|
|
37
|
+
* A listed check runs in the readiness check whatever `configs.<check>.enabled` says: that flag decides for
|
|
38
|
+
* `GET /health-check`. Key, thresholds and options come from `configs.<check>`.
|
|
39
|
+
*/
|
|
40
|
+
export function resolveHealthCheckReadiness(healthCheck: IServerOptions['healthCheck']): IResolvedHealthCheckReadiness {
|
|
41
|
+
const readiness = healthCheck?.readiness;
|
|
42
|
+
const enabled = readiness === true || (!!readiness && typeof readiness === 'object' && readiness.enabled !== false);
|
|
43
|
+
if (!enabled || typeof readiness !== 'object' || readiness.checks === undefined || readiness.checks === null) {
|
|
44
|
+
return { checks: enabled ? [...DEFAULT_READINESS_CHECKS] : [], enabled };
|
|
45
|
+
}
|
|
46
|
+
const listed = typeof readiness.checks === 'string' ? readiness.checks.split(',') : readiness.checks;
|
|
47
|
+
if (!Array.isArray(listed)) {
|
|
48
|
+
warnOnce(`healthCheck.readiness.checks is neither a list nor a string — the default checks run`);
|
|
49
|
+
return { checks: [...DEFAULT_READINESS_CHECKS], enabled };
|
|
50
|
+
}
|
|
51
|
+
const names = listed.map((name) => (typeof name === 'string' ? name.trim() : name)).filter((name) => name !== '');
|
|
52
|
+
for (const name of names) {
|
|
53
|
+
if (!(CORE_HEALTH_CHECK_NAMES as readonly unknown[]).includes(name)) {
|
|
54
|
+
warnOnce(`healthCheck.readiness.checks names an unknown check "${String(name)}" — it is ignored`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { checks: CORE_HEALTH_CHECK_NAMES.filter((name) => names.includes(name)), enabled };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function warnOnce(message: string): void {
|
|
61
|
+
if (!warnedUnknownChecks.has(message)) {
|
|
62
|
+
warnedUnknownChecks.add(message);
|
|
63
|
+
logger.warn(message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -1,16 +1,35 @@
|
|
|
1
|
-
import { Module } from '@nestjs/common';
|
|
1
|
+
import { type DynamicModule, Module, type Type } from '@nestjs/common';
|
|
2
2
|
import { ModuleRef } from '@nestjs/core';
|
|
3
3
|
import { HealthIndicatorService, MongooseHealthIndicator, TerminusModule } from '@nestjs/terminus';
|
|
4
4
|
|
|
5
|
+
import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
|
|
5
6
|
import { getConnectionToken } from '../../common/persistence/mongo/mongoose-compat.js';
|
|
6
7
|
|
|
8
|
+
import { CoreHealthCheckReadinessController } from './core-health-check-readiness.controller.js';
|
|
7
9
|
import { CoreHealthCheckController } from './core-health-check.controller.js';
|
|
10
|
+
import { resolveHealthCheckReadiness } from './core-health-check.helpers.js';
|
|
8
11
|
import { CoreHealthCheckResolver } from './core-health-check.resolver.js';
|
|
9
12
|
import { CoreHealthCheckService } from './core-health-check.service.js';
|
|
10
13
|
|
|
14
|
+
/** Options of {@link CoreHealthCheckModule.forRoot} — what `CoreModule.forRoot()` passes on */
|
|
15
|
+
export interface ICoreHealthCheckModuleOptions {
|
|
16
|
+
/** `healthCheck.readiness`: registers `GET /health-check/ready` when set (boolean shorthand) */
|
|
17
|
+
readiness?: NonNullable<IServerOptions['healthCheck']>['readiness'];
|
|
18
|
+
|
|
19
|
+
/** Replaces `CoreHealthCheckReadinessController`; must extend it */
|
|
20
|
+
readinessController?: Type<any>;
|
|
21
|
+
|
|
22
|
+
/** Replaces `CoreHealthCheckService`; must extend it — the way to add checks (`additionalHealthIndicators()`) */
|
|
23
|
+
service?: Type<CoreHealthCheckService>;
|
|
24
|
+
}
|
|
25
|
+
|
|
11
26
|
/**
|
|
12
27
|
* This is a module that imports the TerminusModule and includes a HealthController.
|
|
13
28
|
* Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
|
|
29
|
+
*
|
|
30
|
+
* Imported as it is, the module registers the liveness check (`GET /health-check`, the `healthCheck` query) exactly as
|
|
31
|
+
* before 12.11.0. `forRoot()` adds what the configuration and the overrides ask for: the readiness endpoint and a
|
|
32
|
+
* project's subclass of `CoreHealthCheckService`.
|
|
14
33
|
*/
|
|
15
34
|
@Module({
|
|
16
35
|
controllers: [CoreHealthCheckController],
|
|
@@ -28,4 +47,20 @@ import { CoreHealthCheckService } from './core-health-check.service.js';
|
|
|
28
47
|
},
|
|
29
48
|
],
|
|
30
49
|
})
|
|
31
|
-
export class CoreHealthCheckModule {
|
|
50
|
+
export class CoreHealthCheckModule {
|
|
51
|
+
/**
|
|
52
|
+
* The module with the readiness endpoint and the service override (12.11.0). A dynamic module EXTENDS the static
|
|
53
|
+
* metadata above, so only what is not there is added: the readiness controller (only with `readiness`), and a project
|
|
54
|
+
* service registered under its own class and — replacing the core one — under `CoreHealthCheckService`, which the
|
|
55
|
+
* controllers and the resolver inject.
|
|
56
|
+
*/
|
|
57
|
+
static forRoot(options: ICoreHealthCheckModuleOptions = {}): DynamicModule {
|
|
58
|
+
const readiness = resolveHealthCheckReadiness({ readiness: options.readiness });
|
|
59
|
+
const controllers = readiness.enabled ? [options.readinessController || CoreHealthCheckReadinessController] : [];
|
|
60
|
+
const providers =
|
|
61
|
+
options.service && options.service !== CoreHealthCheckService
|
|
62
|
+
? [options.service, { provide: CoreHealthCheckService, useExisting: options.service }]
|
|
63
|
+
: [];
|
|
64
|
+
return { controllers, module: CoreHealthCheckModule, providers };
|
|
65
|
+
}
|
|
66
|
+
}
|