@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
|
@@ -470,6 +470,20 @@ After integration, verify:
|
|
|
470
470
|
`302` to `<appUrl>/auth/login?error=state_not_found`, not the API's "Error" page (`betterAuth.errorUrl`)
|
|
471
471
|
- [ ] The login page shows a text of its own for each `error` code and never renders `error_description`
|
|
472
472
|
|
|
473
|
+
### Optional: Sign-in through a provider alone (`emailAndPassword.enabled: false`, no plugin sign-in route, 12.11.0+)
|
|
474
|
+
|
|
475
|
+
The provider decides who gets in, so nothing of the framework's own may keep someone in after it withdrew the
|
|
476
|
+
assignment (README → "Sign-in through a provider alone"):
|
|
477
|
+
|
|
478
|
+
- [ ] `GET /iam/features` answers `emailAndPassword: false`, `passkey: false`, `twoFactor: false`; the login page hides
|
|
479
|
+
the e-mail form on `emailAndPassword: false`
|
|
480
|
+
- [ ] `POST /iam/passkey/verify-authentication` answers `404` — unless the project switched Passkey on deliberately
|
|
481
|
+
with `passkey: true`
|
|
482
|
+
- [ ] `POST /iam/sign-in/social` with `{ "provider": "microsoft", "idToken": { "token": "…" } }` answers
|
|
483
|
+
`ID_TOKEN_NOT_SUPPORTED` (only a native app or Google One Tap sets `disableIdTokenSignIn: false`)
|
|
484
|
+
- [ ] After `POST /iam/sign-out` the JWT of that session answers `401` at once
|
|
485
|
+
- [ ] Where a withdrawal must take effect within a fixed time: `session: { expiresInHours: <n>, extendOnUse: false }`
|
|
486
|
+
|
|
473
487
|
### Additional checks for Migration scenario:
|
|
474
488
|
|
|
475
489
|
- [ ] Sign-in via Legacy Auth works for BetterAuth-created users
|
|
@@ -480,16 +494,18 @@ After integration, verify:
|
|
|
480
494
|
|
|
481
495
|
## Common Mistakes
|
|
482
496
|
|
|
483
|
-
| Mistake
|
|
484
|
-
|
|
|
485
|
-
| Forgot to re-declare decorators in Resolver
|
|
486
|
-
| Forgot `CoreBetterAuthUserMapper` in UserService
|
|
487
|
-
| Missing `fallbackSecrets` in ServerModule
|
|
488
|
-
| Wrong `basePath` in config
|
|
489
|
-
| Using wrong CoreModule signature
|
|
490
|
-
| AuthResolver override missing `checkLegacyGraphQLEnabled()`
|
|
491
|
-
| Missing `signUpValidator` in custom Resolver (v11.13.0+)
|
|
492
|
-
| Missing `termsAndPrivacyAccepted` parameter in Resolver (v11.13.0+)
|
|
497
|
+
| Mistake | Symptom | Fix |
|
|
498
|
+
| ----------------------------------------------------------------------------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
499
|
+
| Forgot to re-declare decorators in Resolver | GraphQL endpoints missing (404) | Copy resolver from reference, keep ALL decorators |
|
|
500
|
+
| Forgot `CoreBetterAuthUserMapper` in UserService | Auth systems not synced, users can't cross-authenticate | Add `@Optional()` parameter and pass to super() |
|
|
501
|
+
| Missing `fallbackSecrets` in ServerModule | Session issues without explicit secret | Add `fallbackSecrets: [envConfig.jwt?.secret, ...]` |
|
|
502
|
+
| Wrong `basePath` in config | 404 on BetterAuth endpoints | Ensure basePath matches controller (default: `/iam`) |
|
|
503
|
+
| Using wrong CoreModule signature | Build errors or missing features | New projects: 1-parameter, Existing: 3-parameter |
|
|
504
|
+
| AuthResolver override missing `checkLegacyGraphQLEnabled()` | Legacy endpoint disabling doesn't work (no HTTP 410) | Call `this.checkLegacyGraphQLEnabled('signIn')` in overrides |
|
|
505
|
+
| Missing `signUpValidator` in custom Resolver (v11.13.0+) | Sign-up validation not working | Add `@Optional() signUpValidator?: CoreBetterAuthSignUpValidatorService` to constructor and pass to `super()` |
|
|
506
|
+
| Missing `termsAndPrivacyAccepted` parameter in Resolver (v11.13.0+) | GraphQL error "Unknown argument" | Add `@Args('termsAndPrivacyAccepted', { nullable: true })` to `betterAuthSignUp` method |
|
|
507
|
+
| A JWT client keeps the JWT it had before `verify-totp` while enabling 2FA (12.11.0+) | `401` right after 2FA was switched on | Use the `token` of the `verify-totp` answer: the first confirmation replaces the session, and a JWT is bound to its session |
|
|
508
|
+
| An SSO-only project (`emailAndPassword.enabled: false`) expects Passkey or 2FA (12.11.0+) | Passkey and 2FA routes answer `404` | Switch them on deliberately with `passkey: true` / `twoFactor: true` — they keep a user signed in after the provider withdrew the assignment |
|
|
493
509
|
|
|
494
510
|
---
|
|
495
511
|
|
|
@@ -407,14 +407,15 @@ const config = {
|
|
|
407
407
|
|
|
408
408
|
The following table shows which features are active based on your configuration:
|
|
409
409
|
|
|
410
|
-
| Configuration
|
|
411
|
-
|
|
|
412
|
-
| _not set_ (no URLs)
|
|
413
|
-
| `env: 'local'/'ci'/'e2e'` (auto URLs)
|
|
414
|
-
| `baseUrl` set
|
|
415
|
-
| `betterAuth: false`
|
|
416
|
-
| `{ passkey: false }`
|
|
417
|
-
| `{ twoFactor: false }`
|
|
410
|
+
| Configuration | BetterAuth | JWT | 2FA | Passkey |
|
|
411
|
+
| ----------------------------------------------------- | :--------: | :-: | :-------------------------: | :-----------------------: |
|
|
412
|
+
| _not set_ (no URLs) | ✅ | ✅ | ✅ | ⚠️ disabled |
|
|
413
|
+
| `env: 'local'/'ci'/'e2e'` (auto URLs) | ✅ | ✅ | ✅ | ✅ auto |
|
|
414
|
+
| `baseUrl` set | ✅ | ✅ | ✅ | ✅ auto |
|
|
415
|
+
| `betterAuth: false` | ❌ | ❌ | ❌ | ❌ |
|
|
416
|
+
| `{ passkey: false }` | ✅ | ✅ | ✅ | ❌ |
|
|
417
|
+
| `{ twoFactor: false }` | ✅ | ✅ | ❌ | ✅ auto |
|
|
418
|
+
| `{ emailAndPassword: { enabled: false } }` (12.11.0+) | ✅ | ✅ | ❌ unless `twoFactor: true` | ❌ unless `passkey: true` |
|
|
418
419
|
|
|
419
420
|
**Key points:**
|
|
420
421
|
|
|
@@ -705,6 +706,34 @@ without a warning. `enabled` is the framework's own switch and is not handed on.
|
|
|
705
706
|
`betterAuth.options.socialProviders` is not the place for provider options: it replaces the whole block, so the
|
|
706
707
|
provider disappears from `GET /iam/features` and `emailAndPassword.disableSignUp` no longer closes it.
|
|
707
708
|
|
|
709
|
+
### Sign-in through a provider alone (12.11.0)
|
|
710
|
+
|
|
711
|
+
A project that signs in through a single sign-on provider alone (`emailAndPassword: { enabled: false }`, e.g.
|
|
712
|
+
Microsoft Entra) expects the provider to decide who gets in. Since 12.11.0 nothing the framework offers keeps someone
|
|
713
|
+
in after the provider withdrew the assignment or role:
|
|
714
|
+
|
|
715
|
+
| What | Since 12.11.0 | Before |
|
|
716
|
+
| -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
717
|
+
| Passkey and two-factor | Off while sign-in runs through a provider alone (`emailAndPassword` off and no plugin with a sign-in route of its own — `username()` / `phoneNumber()` keep both on); `passkey: true` / `twoFactor: true` (or `{ enabled: true, … }`) switches them on deliberately. Their routes answer 404, also for a passkey registered earlier. The boot names what it switched off, as a warning for a factor with settings of its own | On: a passkey registered once after a provider sign-in kept signing its owner in |
|
|
718
|
+
| A client-submitted id token (`POST /iam/sign-in/social` / `/iam/link-social` with `idToken`) | Refused with `ID_TOKEN_NOT_SUPPORTED` for every provider unless the provider sets `disableIdTokenSignIn: false` (native apps, Google One Tap). The redirect flow is unaffected | Accepted: an id token kept from an earlier sign-in (`/iam/get-access-token` hands it out) signed its owner in again for about an hour, without asking the provider |
|
|
719
|
+
| The Better-Auth JWT | Bound to the session it was issued from (claim `sid`): refused once that session is signed out, revoked, expired or its user deleted — at once on this replica and, with `redis`, on every replica; otherwise within 10 s. A JWT without `sid` (issued before 12.11.0) is refused, and the client fetches a new one with its session (`GET /iam/token`). After a session rotation (the first `verify-totp` while enabling 2FA) the answer carries the JWT of the new session | Valid until its own expiry (15 minutes) after a sign-out, and a JWT client's sign-out ended no session at all |
|
|
720
|
+
| `GET /iam/features` | Reports `emailAndPassword` (also in the GraphQL `betterAuthFeatures`), so a frontend can hide the e-mail form | — |
|
|
721
|
+
|
|
722
|
+
A session that is not extended while it is used ends a fixed time after the sign-in, so a withdrawal at the provider
|
|
723
|
+
reaches it at the latest then:
|
|
724
|
+
|
|
725
|
+
```typescript
|
|
726
|
+
betterAuth: {
|
|
727
|
+
emailAndPassword: { enabled: false },
|
|
728
|
+
session: { expiresInHours: 8, extendOnUse: false }, // sign in again after 8 hours, every time
|
|
729
|
+
socialProviders: { microsoft: { clientId, clientSecret, tenantId } },
|
|
730
|
+
},
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
`session.expiresInHours` maps to Better-Auth's `session.expiresIn` (default 7 days), `extendOnUse: false` to
|
|
734
|
+
`session.disableSessionRefresh`. A value of `expiresInHours` that is not a positive number is ignored with a warning.
|
|
735
|
+
`betterAuth.options.session` still wins key by key.
|
|
736
|
+
|
|
708
737
|
#### Microsoft Entra ID: one organization, identity only
|
|
709
738
|
|
|
710
739
|
```typescript
|
|
@@ -13,7 +13,13 @@ import { IBetterAuth, ICorsConfig } from '../../common/interfaces/server-options
|
|
|
13
13
|
import { ConfigService } from '../../common/services/config.service.js';
|
|
14
14
|
import { detectCookiePrefixDrift, resolveBetterAuthCookiePrefix } from './better-auth-cookie-prefix.helper.js';
|
|
15
15
|
import { withSqlStorage } from './better-auth-sql.helper.js';
|
|
16
|
+
import { jwtSessionEnded } from './core-better-auth-jwt-session.cache.js';
|
|
16
17
|
import { projectProvidesOpenApiPlugin } from './core-better-auth-openapi.helper.js';
|
|
18
|
+
import {
|
|
19
|
+
isPasskeyConfigured,
|
|
20
|
+
isTwoFactorConfigured,
|
|
21
|
+
signInFactorsOffWithoutPassword,
|
|
22
|
+
} from './core-better-auth-sign-in-factors.helper.js';
|
|
17
23
|
import { requireBetterAuthMongoAdapter } from '../../common/persistence/mongo/mongo-packages.js';
|
|
18
24
|
|
|
19
25
|
/**
|
|
@@ -552,6 +558,20 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
552
558
|
for (const notice of passkeyNormalization.notices) {
|
|
553
559
|
logger.log(notice);
|
|
554
560
|
}
|
|
561
|
+
const factorsOffWithoutPassword = signInFactorsOffWithoutPassword(config);
|
|
562
|
+
if (factorsOffWithoutPassword.length) {
|
|
563
|
+
const names = factorsOffWithoutPassword.map((factor) => factor.name);
|
|
564
|
+
const message =
|
|
565
|
+
`${names.join(' and ')} off: sign-in runs through a provider alone (emailAndPassword.enabled: false, no plugin ` +
|
|
566
|
+
'with a sign-in route of its own), so the provider alone decides who gets in. Switch them on explicitly with ' +
|
|
567
|
+
`${names.map((name) => `${name}: true`).join(' / ')}.`;
|
|
568
|
+
// A factor that carried settings of its own was meant to be on: say so loudly, since its users lose it
|
|
569
|
+
if (factorsOffWithoutPassword.some((factor) => factor.configured)) {
|
|
570
|
+
logger.warn(message);
|
|
571
|
+
} else {
|
|
572
|
+
logger.log(message);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
555
575
|
for (const warning of passkeyNormalization.warnings) {
|
|
556
576
|
logger.warn(warning);
|
|
557
577
|
}
|
|
@@ -619,6 +639,8 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
619
639
|
// strip `Secure` from the cookies Better-Auth's native handlers forward.
|
|
620
640
|
const secureCookies = betterAuthBaseUrl.startsWith('https://');
|
|
621
641
|
|
|
642
|
+
const sessionOptions = resolveSessionOptions(config);
|
|
643
|
+
|
|
622
644
|
const betterAuthConfig: Record<string, unknown> = {
|
|
623
645
|
// Through Nest's logger; a project's own `options.logger` is merged over it (see below).
|
|
624
646
|
logger: { log: logThroughNest },
|
|
@@ -663,6 +685,7 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
663
685
|
basePath,
|
|
664
686
|
baseURL: betterAuthBaseUrl,
|
|
665
687
|
database: sqlPool ? undefined : (requireBetterAuthMongoAdapter()(db) as any),
|
|
688
|
+
...(sessionOptions && { session: sessionOptions }),
|
|
666
689
|
// Enable email/password authentication by default (required by Better-Auth 1.x)
|
|
667
690
|
// Can be disabled by setting config.emailAndPassword.enabled = false
|
|
668
691
|
emailAndPassword: {
|
|
@@ -810,6 +833,12 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
810
833
|
};
|
|
811
834
|
}
|
|
812
835
|
|
|
836
|
+
// `session` is merged, not replaced: `betterAuth.session` sets expiresIn / disableSessionRefresh, and a project's
|
|
837
|
+
// `options.session` (cookie cache, freshAge, …) keeps them unless it sets them itself.
|
|
838
|
+
if (sessionOptions && restOptions.session && typeof restOptions.session === 'object') {
|
|
839
|
+
finalConfig.session = { ...sessionOptions, ...(restOptions.session as Record<string, unknown>) };
|
|
840
|
+
}
|
|
841
|
+
|
|
813
842
|
// `logger` is merged, not replaced: a project that only sets `level` or `disabled` keeps the Nest routing,
|
|
814
843
|
// one that passes its own `log` handler gets exactly that.
|
|
815
844
|
if (restOptions.logger && typeof restOptions.logger === 'object') {
|
|
@@ -918,7 +947,8 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
|
|
|
918
947
|
|
|
919
948
|
/**
|
|
920
949
|
* Ends the GraphQL WebSocket connections that rode on a session the moment the session is deleted —
|
|
921
|
-
* a sign-out, a revoked session, a password reset with `revokeSessionsOnPasswordReset`, a deleted user
|
|
950
|
+
* a sign-out, a revoked session, a password reset with `revokeSessionsOnPasswordReset`, a deleted user — and, since
|
|
951
|
+
* 12.11.0, the JWTs issued from it (`jwtSessionEnded()`).
|
|
922
952
|
*
|
|
923
953
|
* Without it such a connection stays open until `graphQl.subscriptionRevalidationMs` (30 s by
|
|
924
954
|
* default) catches it on its next event. Better-Auth's `onPasswordReset` cannot do this job: all
|
|
@@ -941,8 +971,12 @@ export function wsSessionRevocationPlugin(): BetterAuthPlugin {
|
|
|
941
971
|
databaseHooks: {
|
|
942
972
|
session: {
|
|
943
973
|
delete: {
|
|
944
|
-
after: async (session: { userId?: unknown }) => {
|
|
974
|
+
after: async (session: { id?: unknown; userId?: unknown }) => {
|
|
945
975
|
try {
|
|
976
|
+
// A JWT issued from this session stops working at once (12.11.0), not when it expires.
|
|
977
|
+
if (session?.id) {
|
|
978
|
+
jwtSessionEnded(String(session.id));
|
|
979
|
+
}
|
|
946
980
|
if (session?.userId) {
|
|
947
981
|
revalidateWsConnectionsOf({ iamId: String(session.userId) });
|
|
948
982
|
}
|
|
@@ -1093,6 +1127,10 @@ function buildPlugins(
|
|
|
1093
1127
|
plugins.push(
|
|
1094
1128
|
jwt({
|
|
1095
1129
|
jwt: {
|
|
1130
|
+
// The id of the session the JWT is issued from (12.11.0): verifyJwtToken() accepts the JWT only while that
|
|
1131
|
+
// session lives (core-better-auth-jwt-session.cache.ts). The rest of the payload is Better-Auth's default,
|
|
1132
|
+
// the session user.
|
|
1133
|
+
definePayload: ({ session, user }) => ({ ...user, sid: session.id }),
|
|
1096
1134
|
expirationTime: jwtConfig.expiresIn || '15m',
|
|
1097
1135
|
},
|
|
1098
1136
|
}),
|
|
@@ -1100,10 +1138,9 @@ function buildPlugins(
|
|
|
1100
1138
|
}
|
|
1101
1139
|
|
|
1102
1140
|
// Two-Factor Authentication Plugin
|
|
1103
|
-
//
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
if (!twoFactorExplicitlyDisabled) {
|
|
1141
|
+
// On unless switched off (twoFactor: false or { enabled: false }); with sign-in through a provider alone only when
|
|
1142
|
+
// switched on explicitly (12.11.0, see isSignInFactorEnabled())
|
|
1143
|
+
if (isTwoFactorConfigured(config)) {
|
|
1107
1144
|
const twoFactorConfig = typeof config.twoFactor === 'object' ? config.twoFactor : {};
|
|
1108
1145
|
plugins.push(
|
|
1109
1146
|
twoFactor({
|
|
@@ -1232,6 +1269,13 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
|
|
|
1232
1269
|
...providerOptions,
|
|
1233
1270
|
clientId: provider.clientId,
|
|
1234
1271
|
clientSecret: provider.clientSecret,
|
|
1272
|
+
// Since 12.11.0 a client cannot sign in or link an account with an id token it submits itself
|
|
1273
|
+
// (`POST /sign-in/social` / `/link-social` with `idToken`) unless the project opens it with an explicit
|
|
1274
|
+
// `false`. Better-Auth verifies such a token's signature, audience and expiry, and asks the provider nothing:
|
|
1275
|
+
// an id token kept from an earlier sign-in (`/get-access-token` hands it out) signed its owner in again for
|
|
1276
|
+
// its whole lifetime (about an hour at Microsoft), after the provider had withdrawn the assignment or role.
|
|
1277
|
+
// The redirect flow never uses it. Native apps and Google One Tap need it and set `false`.
|
|
1278
|
+
disableIdTokenSignIn: provider.disableIdTokenSignIn !== false,
|
|
1235
1279
|
disableSignUp: typeof provider.disableSignUp === 'boolean' ? provider.disableSignUp : signUpClosed,
|
|
1236
1280
|
};
|
|
1237
1281
|
}
|
|
@@ -1241,6 +1285,36 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
|
|
|
1241
1285
|
return socialProvidersConfig;
|
|
1242
1286
|
}
|
|
1243
1287
|
|
|
1288
|
+
/**
|
|
1289
|
+
* Better-Auth's session options from `betterAuth.session` (12.11.0): `expiresIn` in seconds and `disableSessionRefresh`
|
|
1290
|
+
* — `undefined` when nothing is set, so Better-Auth's defaults (7 days, extended daily) apply unchanged.
|
|
1291
|
+
*
|
|
1292
|
+
* An `expiresInHours` that is not a positive finite number is ignored with a warning: a misconfigured lifetime must
|
|
1293
|
+
* fall back to the default, never to a lifetime nobody chose.
|
|
1294
|
+
*/
|
|
1295
|
+
function resolveSessionOptions(config: IBetterAuth): Record<string, unknown> | undefined {
|
|
1296
|
+
const session = config.session;
|
|
1297
|
+
if (!session || typeof session !== 'object') {
|
|
1298
|
+
return undefined;
|
|
1299
|
+
}
|
|
1300
|
+
const options: Record<string, unknown> = {};
|
|
1301
|
+
if (session.expiresInHours !== undefined) {
|
|
1302
|
+
const hours = session.expiresInHours as unknown;
|
|
1303
|
+
if (typeof hours === 'number' && Number.isFinite(hours) && hours > 0) {
|
|
1304
|
+
options.expiresIn = Math.round(hours * 3600);
|
|
1305
|
+
} else {
|
|
1306
|
+
logger.warn(
|
|
1307
|
+
`betterAuth.session.expiresInHours must be a positive number of hours (received ${JSON.stringify(hours)}); ` +
|
|
1308
|
+
"Better-Auth's default of 7 days applies.",
|
|
1309
|
+
);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
if (session.extendOnUse === false) {
|
|
1313
|
+
options.disableSessionRefresh = true;
|
|
1314
|
+
}
|
|
1315
|
+
return Object.keys(options).length ? options : undefined;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1244
1318
|
/**
|
|
1245
1319
|
* Splits a provider's `scope` string on commas and whitespace into the list Better-Auth expects, dropping empty
|
|
1246
1320
|
* entries: `'openid profile email'` and `'openid,profile,email'` both become `['openid', 'profile', 'email']`.
|
|
@@ -1741,12 +1815,9 @@ function normalizePasskeyConfig(
|
|
|
1741
1815
|
const notices: string[] = [];
|
|
1742
1816
|
const warnings: string[] = [];
|
|
1743
1817
|
|
|
1744
|
-
//
|
|
1745
|
-
//
|
|
1746
|
-
|
|
1747
|
-
config.passkey === false || (typeof config.passkey === 'object' && config.passkey?.enabled === false);
|
|
1748
|
-
|
|
1749
|
-
if (isExplicitlyDisabled) {
|
|
1818
|
+
// Passkey switched off: passkey: false OR passkey: { enabled: false } — or, with sign-in through a provider alone, not
|
|
1819
|
+
// switched on explicitly (12.11.0, see isSignInFactorEnabled())
|
|
1820
|
+
if (!isPasskeyConfigured(config)) {
|
|
1750
1821
|
return { enabled: false, normalizedConfig: null, notices, trustedOrigins: null, warnings };
|
|
1751
1822
|
}
|
|
1752
1823
|
|
|
@@ -357,7 +357,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
|
|
|
357
357
|
// Extract session token from cookies or Authorization header.
|
|
358
358
|
// In JWT mode, extractSessionToken correctly returns null for JWTs.
|
|
359
359
|
// Fall back to the session resolved by CoreBetterAuthMiddleware (which
|
|
360
|
-
// resolves
|
|
360
|
+
// resolves a JWT to its own DB session via getJwtSession()).
|
|
361
361
|
let sessionToken = extractSessionToken(req, basePath);
|
|
362
362
|
if (!sessionToken) {
|
|
363
363
|
const betterAuthReq = req as any;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which sessions a Better-Auth JWT may still act for (12.11.0) — an import-free leaf, so the session-deletion hook in
|
|
3
|
+
* `better-auth.config.ts`, `CoreBetterAuthService` and the user mapper's Redis broadcast reach the same entries
|
|
4
|
+
* without importing each other.
|
|
5
|
+
*
|
|
6
|
+
* A JWT carries the id of the session it was issued from (`sid`). `CoreBetterAuthService.verifyJwtToken()` accepts it
|
|
7
|
+
* only while that session exists, belongs to the token's subject and has not expired; the answer is kept here for a
|
|
8
|
+
* few seconds, and a deleted session is forgotten at once (`jwtSessionEnded()`), on every replica where Redis
|
|
9
|
+
* carries the broadcast. Before 12.11.0 a JWT stayed valid until its own expiry (15 minutes by default) after a
|
|
10
|
+
* sign-out, a revoked session or a deleted user.
|
|
11
|
+
*
|
|
12
|
+
* Process-local and bounded: at most {@link JWT_SESSION_CACHE_MAX} entries, the oldest evicted first.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Most sessions the cache holds; beyond it the oldest entry is evicted. */
|
|
16
|
+
export const JWT_SESSION_CACHE_MAX = 10_000;
|
|
17
|
+
|
|
18
|
+
interface JwtSessionEntry {
|
|
19
|
+
live: boolean;
|
|
20
|
+
/** The session with its user, when a lookup fetched them (`CoreBetterAuthService.getJwtSession()`). */
|
|
21
|
+
record?: unknown;
|
|
22
|
+
/** Epoch milliseconds until which the answer stands. */
|
|
23
|
+
until: number;
|
|
24
|
+
userId: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const entries = new Map<string, JwtSessionEntry>();
|
|
28
|
+
|
|
29
|
+
let broadcaster: ((sessionId: string) => void) | undefined;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The cached answer for the session `sessionId` of `userId`: `true` / `false` while it stands, `undefined` when it has
|
|
33
|
+
* to be asked again. An entry for another user never answers `true`.
|
|
34
|
+
*/
|
|
35
|
+
export function cachedJwtSession(sessionId: string, userId: string, now = Date.now()): boolean | undefined {
|
|
36
|
+
const entry = entries.get(sessionId);
|
|
37
|
+
if (!entry) {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
if (entry.until <= now) {
|
|
41
|
+
entries.delete(sessionId);
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
return entry.live && entry.userId === userId;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The cached session with its user for the session `sessionId` of `userId` — only while the answer stands, the
|
|
49
|
+
* session lives and belongs to that user.
|
|
50
|
+
*/
|
|
51
|
+
export function cachedJwtSessionRecord(sessionId: string, userId: string, now = Date.now()): unknown {
|
|
52
|
+
return cachedJwtSession(sessionId, userId, now) ? entries.get(sessionId)?.record : undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Keeps the answer for the session `sessionId` of `userId` until `until` (epoch milliseconds), with the session and
|
|
57
|
+
* its user when the lookup fetched them. An answer without a record keeps a record already held for a live session.
|
|
58
|
+
*/
|
|
59
|
+
export function rememberJwtSession(
|
|
60
|
+
sessionId: string,
|
|
61
|
+
userId: string,
|
|
62
|
+
live: boolean,
|
|
63
|
+
until: number,
|
|
64
|
+
record?: unknown,
|
|
65
|
+
): void {
|
|
66
|
+
const previous = entries.get(sessionId);
|
|
67
|
+
const kept = record ?? (live && previous?.live && previous.userId === userId ? previous.record : undefined);
|
|
68
|
+
entries.delete(sessionId);
|
|
69
|
+
if (entries.size >= JWT_SESSION_CACHE_MAX) {
|
|
70
|
+
const oldest = entries.keys().next().value;
|
|
71
|
+
if (oldest !== undefined) {
|
|
72
|
+
entries.delete(oldest);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
entries.set(sessionId, { live, record: kept, until, userId });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Forgets the answer for the session `sessionId` on this process only — for a broadcast received from a replica. */
|
|
79
|
+
export function forgetJwtSession(sessionId: string): void {
|
|
80
|
+
entries.delete(sessionId);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The session `sessionId` has ended (signed out, revoked, its user deleted): forget it here and tell the other
|
|
85
|
+
* replicas. Never throws — it runs inside Better-Auth's deletion.
|
|
86
|
+
*/
|
|
87
|
+
export function jwtSessionEnded(sessionId: string): void {
|
|
88
|
+
entries.delete(sessionId);
|
|
89
|
+
try {
|
|
90
|
+
broadcaster?.(sessionId);
|
|
91
|
+
} catch {
|
|
92
|
+
// The other replicas forget it when their entry expires.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Registers how an ended session reaches the other replicas (the user mapper's Redis channel); `undefined` removes it. */
|
|
97
|
+
export function setJwtSessionBroadcaster(fn: ((sessionId: string) => void) | undefined): void {
|
|
98
|
+
broadcaster = fn;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Empties the cache — for tests and a module that is torn down. */
|
|
102
|
+
export function clearJwtSessionCache(): void {
|
|
103
|
+
entries.clear();
|
|
104
|
+
}
|
|
@@ -123,6 +123,11 @@ export class CoreBetterAuthPasskeyChallengeModel {
|
|
|
123
123
|
@ObjectType({ description: 'Better-Auth features status' })
|
|
124
124
|
@Restricted(RoleEnum.S_EVERYONE)
|
|
125
125
|
export class CoreBetterAuthFeaturesModel {
|
|
126
|
+
@Field(() => Boolean, {
|
|
127
|
+
description: 'Whether e-mail and password sign-in is enabled (false: sign-in through a provider only)',
|
|
128
|
+
})
|
|
129
|
+
emailAndPassword: boolean;
|
|
130
|
+
|
|
126
131
|
@Field(() => Boolean, { description: 'Whether email verification is required on sign-up' })
|
|
127
132
|
emailVerification: boolean;
|
|
128
133
|
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { IBetterAuth } from '../../common/interfaces/server-options.interface.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Whether e-mail and password sign-in is on: everything but an explicit `emailAndPassword.enabled: false`, the default
|
|
5
|
+
* Better-Auth receives in `better-auth.config.ts`.
|
|
6
|
+
*/
|
|
7
|
+
export function isEmailAndPasswordSignInEnabled(config: IBetterAuth | undefined): boolean {
|
|
8
|
+
return config?.emailAndPassword?.enabled !== false;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The sign-in routes the project's own Better-Auth plugins add (`betterAuth.plugins`, `betterAuth.options.plugins`):
|
|
13
|
+
* `/sign-in/username`, `/sign-in/phone-number`, `/sign-in/magic-link`, `/sign-in/email-otp`, … — every endpoint path
|
|
14
|
+
* under `/sign-in/` but the social one.
|
|
15
|
+
*/
|
|
16
|
+
export function projectSignInRoutes(config: IBetterAuth | undefined): string[] {
|
|
17
|
+
const projectPlugins: unknown = config?.plugins;
|
|
18
|
+
const optionPlugins: unknown = (config?.options as { plugins?: unknown } | undefined)?.plugins;
|
|
19
|
+
const plugins: unknown[] = [
|
|
20
|
+
...(Array.isArray(projectPlugins) ? projectPlugins : []),
|
|
21
|
+
...(Array.isArray(optionPlugins) ? optionPlugins : []),
|
|
22
|
+
];
|
|
23
|
+
const routes: string[] = [];
|
|
24
|
+
for (const plugin of plugins) {
|
|
25
|
+
const endpoints = (plugin as { endpoints?: Record<string, { path?: unknown }> } | null)?.endpoints;
|
|
26
|
+
for (const endpoint of Object.values(endpoints ?? {})) {
|
|
27
|
+
const path = endpoint?.path;
|
|
28
|
+
if (typeof path === 'string' && path.startsWith('/sign-in/') && !path.startsWith('/sign-in/social')) {
|
|
29
|
+
routes.push(path);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return routes;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Whether sign-in runs through a single sign-on provider alone (12.11.0): e-mail and password sign-in is off AND no
|
|
38
|
+
* plugin of the project adds a sign-in route of its own. A project with `emailAndPassword.enabled: false` that signs
|
|
39
|
+
* in by username and password (`username()`) or by phone number is NOT one: there the two-factor plugin is what
|
|
40
|
+
* enforces the second factor on `/sign-in/username` and `/sign-in/phone-number`.
|
|
41
|
+
*/
|
|
42
|
+
export function isProviderOnlySignIn(config: IBetterAuth | undefined): boolean {
|
|
43
|
+
return !isEmailAndPasswordSignInEnabled(config) && projectSignInRoutes(config).length === 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether a sign-in factor (Passkey, two-factor) is on, given its own switch (12.11.0).
|
|
48
|
+
*
|
|
49
|
+
* `false` or `{ enabled: false }` switches it off, as always. While the project signs in with a method of its own (e-mail
|
|
50
|
+
* and password, or a plugin's sign-in route), every other value switches it on (unset included), as before 12.11.0.
|
|
51
|
+
*
|
|
52
|
+
* When sign-in runs through a provider alone ({@link isProviderOnlySignIn}) it is on only when switched on EXPLICITLY:
|
|
53
|
+
* `true` or `{ enabled: true, … }`. Until 12.11.0 Passkey and two-factor stayed on there: whoever registered a passkey
|
|
54
|
+
* after a Microsoft sign-in kept signing in with it after Entra withdrew the assignment, so the provider no longer
|
|
55
|
+
* decided who gets in. An object without `enabled: true` (a `twoFactor: { appName }` kept from a password setup) does
|
|
56
|
+
* not count as that decision.
|
|
57
|
+
*/
|
|
58
|
+
export function isSignInFactorEnabled(value: unknown, config: IBetterAuth | undefined): boolean {
|
|
59
|
+
if (value === false) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
const settings = typeof value === 'object' && value !== null ? (value as { enabled?: unknown }) : undefined;
|
|
63
|
+
if (settings?.enabled === false) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
if (!isProviderOnlySignIn(config)) {
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
return value === true || settings?.enabled === true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether the Passkey plugin is configured on (URL resolution can still turn it off, see `normalizePasskeyConfig`). */
|
|
73
|
+
export function isPasskeyConfigured(config: IBetterAuth | undefined): boolean {
|
|
74
|
+
return isSignInFactorEnabled(config?.passkey, config);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Whether the two-factor plugin is configured on. */
|
|
78
|
+
export function isTwoFactorConfigured(config: IBetterAuth | undefined): boolean {
|
|
79
|
+
return isSignInFactorEnabled(config?.twoFactor, config);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The sign-in factors that are off only because sign-in runs through a provider alone — named once at boot, so a
|
|
84
|
+
* project that relied on them sees why they are gone and how to switch them on again. `configured` marks a factor that
|
|
85
|
+
* carried settings of its own (an object), which deserves a warning rather than a notice.
|
|
86
|
+
*/
|
|
87
|
+
export function signInFactorsOffWithoutPassword(
|
|
88
|
+
config: IBetterAuth | undefined,
|
|
89
|
+
): { configured: boolean; name: 'passkey' | 'twoFactor' }[] {
|
|
90
|
+
if (!isProviderOnlySignIn(config)) {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
const off: { configured: boolean; name: 'passkey' | 'twoFactor' }[] = [];
|
|
94
|
+
for (const [name, value] of [
|
|
95
|
+
['passkey', config?.passkey],
|
|
96
|
+
['twoFactor', config?.twoFactor],
|
|
97
|
+
] as const) {
|
|
98
|
+
const settings = typeof value === 'object' && value !== null ? (value as { enabled?: unknown }) : undefined;
|
|
99
|
+
const explicitlyOff = value === false || settings?.enabled === false;
|
|
100
|
+
if (!explicitlyOff && !isSignInFactorEnabled(value, config)) {
|
|
101
|
+
off.push({ configured: !!settings, name });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return off;
|
|
105
|
+
}
|
|
@@ -20,6 +20,7 @@ import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
|
20
20
|
import { revalidateWsConnectionsOf } from '../../common/helpers/graphql-ws-connection.helper.js';
|
|
21
21
|
import { maskEmail } from '../../common/helpers/logging.helper.js';
|
|
22
22
|
import { CoreRedisService } from '../../common/services/core-redis.service.js';
|
|
23
|
+
import { forgetJwtSession, setJwtSessionBroadcaster } from './core-better-auth-jwt-session.cache.js';
|
|
23
24
|
import { legacyCredentialAccountIssuer } from './core-better-auth-account-issuer.helper.js';
|
|
24
25
|
import { getBetterAuthSqlStore } from './core-better-auth-sql.registry.js';
|
|
25
26
|
import type { BetterAuthSqlStore } from './core-better-auth-sql.store.js';
|
|
@@ -203,6 +204,8 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
|
|
|
203
204
|
}
|
|
204
205
|
};
|
|
205
206
|
this.redisService.getSubscriber().on('message', this.invalidationListener);
|
|
207
|
+
// An ended session reaches the other replicas over the same channel, so their JWT session cache forgets it too
|
|
208
|
+
setJwtSessionBroadcaster((sessionId) => this.publishSessionEnded(sessionId));
|
|
206
209
|
// Registered with the Redis service, so the subscription is established again after every reconnect — also when
|
|
207
210
|
// this first attempt fails because Redis is down at boot.
|
|
208
211
|
await this.redisService.subscribeChannel(channel);
|
|
@@ -219,6 +222,7 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
|
|
|
219
222
|
if (!this.invalidationListener) {
|
|
220
223
|
return;
|
|
221
224
|
}
|
|
225
|
+
setJwtSessionBroadcaster(undefined);
|
|
222
226
|
try {
|
|
223
227
|
if (this.redisService) {
|
|
224
228
|
this.redisService.getSubscriber().off('message', this.invalidationListener);
|
|
@@ -424,11 +428,19 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
|
|
|
424
428
|
*/
|
|
425
429
|
protected applyInvalidation(message: string): void {
|
|
426
430
|
let iamId: unknown;
|
|
431
|
+
let sessionId: unknown;
|
|
427
432
|
try {
|
|
428
|
-
|
|
433
|
+
const parsed = JSON.parse(message);
|
|
434
|
+
iamId = parsed?.iamId;
|
|
435
|
+
sessionId = parsed?.sessionId;
|
|
429
436
|
} catch {
|
|
430
437
|
iamId = undefined;
|
|
431
438
|
}
|
|
439
|
+
// A session ended on another replica (12.11.0): a JWT issued from it must stop working here too
|
|
440
|
+
if (typeof sessionId === 'string' && sessionId) {
|
|
441
|
+
forgetJwtSession(sessionId);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
432
444
|
if (typeof iamId !== 'string' || !iamId) {
|
|
433
445
|
this.logger.debug(`Ignoring malformed IAM user cache invalidation message: ${message}`);
|
|
434
446
|
return;
|
|
@@ -465,6 +477,30 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
|
|
|
465
477
|
}
|
|
466
478
|
}
|
|
467
479
|
|
|
480
|
+
/**
|
|
481
|
+
* Broadcast that a session ended (12.11.0), so every replica's JWT session cache forgets it at once instead of when
|
|
482
|
+
* its entry expires. Fire-and-forget; a no-op without `redis`.
|
|
483
|
+
*/
|
|
484
|
+
protected publishSessionEnded(sessionId: string): void {
|
|
485
|
+
const redisService = this.redisService;
|
|
486
|
+
if (!redisService?.enabled) {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const warn = (error: Error) =>
|
|
490
|
+
this.logger.warn(
|
|
491
|
+
`Ended session could not be broadcast: ${error.message}. JWTs issued from it keep working on other replicas ` +
|
|
492
|
+
'until their session cache entry expires (10 s).',
|
|
493
|
+
);
|
|
494
|
+
try {
|
|
495
|
+
void redisService
|
|
496
|
+
.getClient()
|
|
497
|
+
.publish(this.invalidationChannel(redisService), JSON.stringify({ sessionId }))
|
|
498
|
+
.catch(warn);
|
|
499
|
+
} catch (error) {
|
|
500
|
+
warn(error as Error);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
468
504
|
private invalidationChannel(redisService: CoreRedisService): string {
|
|
469
505
|
return redisService.key('iam-user-cache', 'invalidate');
|
|
470
506
|
}
|
|
@@ -341,6 +341,7 @@ export class CoreBetterAuthController {
|
|
|
341
341
|
@Roles(RoleEnum.S_EVERYONE)
|
|
342
342
|
getFeatures(): Record<string, boolean | number | string[]> {
|
|
343
343
|
return {
|
|
344
|
+
emailAndPassword: this.betterAuthService.isEmailAndPasswordEnabled(),
|
|
344
345
|
emailVerification: this.emailVerificationService?.isEnabled() ?? false,
|
|
345
346
|
enabled: this.betterAuthService.isEnabled(),
|
|
346
347
|
jwt: this.betterAuthService.isJwtEnabled(),
|
|
@@ -814,8 +815,10 @@ export class CoreBetterAuthController {
|
|
|
814
815
|
}
|
|
815
816
|
|
|
816
817
|
try {
|
|
817
|
-
//
|
|
818
|
-
|
|
818
|
+
// The session the middleware validated first — for a JWT request the JWT's own session (12.11.0) —, then the
|
|
819
|
+
// session cookie. Until 12.11.0 a JWT client's sign-out read the cookie alone, found none and ended nothing: the
|
|
820
|
+
// answer said success, and the session and every JWT issued from it lived on.
|
|
821
|
+
const sessionToken = this.getSessionTokenFromRequest(req);
|
|
819
822
|
|
|
820
823
|
if (sessionToken) {
|
|
821
824
|
await this.betterAuthService.revokeSession(sessionToken);
|
|
@@ -975,7 +978,7 @@ export class CoreBetterAuthController {
|
|
|
975
978
|
*
|
|
976
979
|
* JWTs in the Authorization header are NOT returned here because they cannot
|
|
977
980
|
* be used as session tokens for BetterAuth's plugin endpoints (2FA, Passkey, etc.).
|
|
978
|
-
* The middleware resolves
|
|
981
|
+
* The middleware resolves a JWT to its own session separately via getJwtSession().
|
|
979
982
|
*/
|
|
980
983
|
protected extractSessionToken(req: Request): null | string {
|
|
981
984
|
// Check Authorization header - only return session tokens, not JWTs
|