@lenne.tech/nest-server 12.11.1 → 12.11.3
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 +1 -0
- package/.claude/rules/role-system.md +8 -0
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/helpers/http-stream-auth.helper.js +2 -2
- package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -1
- package/dist/core/common/persistence/policies/tenant.policy.js +3 -1
- package/dist/core/common/persistence/policies/tenant.policy.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-cookie-prefix.helper.d.ts +2 -0
- package/dist/core/modules/better-auth/better-auth-cookie-prefix.helper.js +5 -0
- package/dist/core/modules/better-auth/better-auth-cookie-prefix.helper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.middleware.js +4 -2
- package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +3 -3
- package/migration-guides/12.11.1-to-12.11.2.md +76 -0
- package/migration-guides/12.11.2-to-12.11.3.md +96 -0
- package/package.json +13 -13
- package/src/core/common/helpers/http-stream-auth.helper.ts +6 -6
- package/src/core/common/persistence/policies/tenant.policy.ts +10 -5
- package/src/core/modules/better-auth/README.md +18 -0
- package/src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts +17 -0
- package/src/core/modules/better-auth/core-better-auth.middleware.ts +9 -4
- package/src/core/modules/sync/README.md +1 -1
- package/src/core/modules/system-setup/README.md +4 -0
- package/src/core/modules/tenant/INTEGRATION-CHECKLIST.md +3 -3
- package/src/core/modules/tenant/README.md +4 -4
|
@@ -687,6 +687,7 @@ handed Better-Auth the user's NEWEST session for a JWT request.
|
|
|
687
687
|
| A session deleted outside Better-Auth's adapter is caught by the cache interval only (`jwtSessionCacheTtlMs`, 10 s) | the immediate forget runs from Better-Auth's `session.delete` hook (`wsSessionRevocationPlugin()`); delete through Better-Auth |
|
|
688
688
|
| The cache lives in the import-free leaf `core-better-auth-jwt-session.cache.ts`, bounded, keyed by session id and checked against the user | config, service and user mapper reach it without importing each other; an entry never vouches for another user |
|
|
689
689
|
| After a session rotation the answer's `token` is the JWT of the NEW session — also when Better-Auth's answer names no token (two-factor disable, 12.11.1) | the old JWT names a deleted session and answers 401 |
|
|
690
|
+
| The JWT cookie is read under `resolveJwtCookieName()`: `<COOKIE_PREFIX>-jwt-token`, else `lt-jwt-token`, no fallback while a prefix is set (12.11.2) | `@lenne.tech/nuxt-extensions` names it after `NUXT_PUBLIC_COOKIE_PREFIX`; a fixed `lt-jwt-token` left every cookie-only request (SSR, passkey, stream re-check) anonymous with a prefix. Mutations `jwt-cookie-name-ignores-cookie-prefix`, `middleware-jwt-cookie-ignores-prefix`, `stream-recheck-jwt-cookie-ignores-prefix` |
|
|
690
691
|
|
|
691
692
|
Pinned by `tests/unit/better-auth-jwt-session-binding.spec.ts` and `tests/better-auth-jwt-session.e2e-spec.ts`.
|
|
692
693
|
|
|
@@ -540,6 +540,14 @@ permission error returned as 401 kicks a logged-in user out of the whole app.
|
|
|
540
540
|
`S_NO_ONE` is 403 even without a session because authenticating can *never* unlock it — a 401 would
|
|
541
541
|
tell the client to log in and retry, which is a lie.
|
|
542
542
|
|
|
543
|
+
"Not authenticated" includes a session that has ENDED: a browser keeps sending the cookie of an expired session, and
|
|
544
|
+
the API answers it like no cookie at all. Since 12.11.3 the tenant safety net (`resolveTenantFilter()`) follows the
|
|
545
|
+
rule too — 401 for a client operation nobody is signed in to, 403 for a signed-in caller and for server work; before,
|
|
546
|
+
it answered 403 to everyone, so a frontend with an expired session reading tenant data from a public route showed an
|
|
547
|
+
error instead of the sign-in (DEV-4393). Pinned against both role guards, REST and GraphQL, by
|
|
548
|
+
`tests/session-expired-status.e2e-spec.ts` (`RolesGuard`) and `tests/session-expired-status-iam.e2e-spec.ts`
|
|
549
|
+
(`BetterAuthRolesGuard`); the cases live in `tests/helpers/session-expiry-cases.ts`.
|
|
550
|
+
|
|
543
551
|
Exception: `ErrorCode.EMAIL_VERIFICATION_REQUIRED` is a legitimate **401** (thrown at sign-in, where
|
|
544
552
|
no session exists yet). Frontends must branch on the ErrorCode, not on the status alone, so this one
|
|
545
553
|
does not trigger the logout flow.
|
package/.claude/rules/testing.md
CHANGED
|
@@ -412,7 +412,7 @@ pnpm run check:mutations -- --id=<id> # one mutation
|
|
|
412
412
|
pnpm run check:mutations -- --list # the registry, without running anything
|
|
413
413
|
pnpm run check:mutations -- --allow-dirty # when the fix and its evidence share a working tree
|
|
414
414
|
pnpm run check:mutations -- --jobs=4 # N mutations at a time (default: 2, or 4 on >=12 cores)
|
|
415
|
-
pnpm run check:mutations -- --no-infra # only the
|
|
415
|
+
pnpm run check:mutations -- --no-infra # only the 519 that need no MongoDB
|
|
416
416
|
pnpm run check:mutations -- --since=<ref> # only mutations touching files changed since <ref>
|
|
417
417
|
pnpm run check:mutations -- --shard=2/4 # this job's quarter of the selection (CI splits the full run)
|
|
418
418
|
```
|
|
@@ -432,7 +432,7 @@ when the registry, a vitest config or a setup file changed, since those can move
|
|
|
432
432
|
commit, and in CI alongside the publish without blocking it. The price of caching is a cache that
|
|
433
433
|
has to model each spec's full dependency closure correctly, and getting that wrong produces a stale
|
|
434
434
|
PASS for a test that has since gone vacuous — exactly what the gate is there to prevent. Bad trade
|
|
435
|
-
at
|
|
435
|
+
at 770 mutations.
|
|
436
436
|
|
|
437
437
|
**Decided 2026-10-03 (repo owner): keep the full run.** Measured at 128 mutations, the CI job for
|
|
438
438
|
11.41.6 took **14 minutes**. The trigger to revisit is that wall time, not the mutation count —
|
|
@@ -503,9 +503,9 @@ exactly the environment where the answer matters.
|
|
|
503
503
|
|
|
504
504
|
### The cost is vitest's cold start, not the tests
|
|
505
505
|
|
|
506
|
-
Worth knowing before optimising the wrong thing: the specs behind all
|
|
506
|
+
Worth knowing before optimising the wrong thing: the specs behind all 251 e2e mutations add up to
|
|
507
507
|
**~40 seconds**. The step takes ~740s. The remaining ~700s is paying vitest's startup — process
|
|
508
|
-
spawn, transform, module graph, mongod connect, DB create and drop — once per mutation,
|
|
508
|
+
spawn, transform, module graph, mongod connect, DB create and drop — once per mutation, 770 times.
|
|
509
509
|
That work is largely single-threaded I/O and barely scales with cores: the full registry measures
|
|
510
510
|
**744s on a 12-core laptop and 777s on a 4-vCPU CI runner**.
|
|
511
511
|
|
package/FRAMEWORK-API.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @lenne.tech/nest-server — Framework API Reference
|
|
2
2
|
|
|
3
|
-
> Auto-generated from source code as of 2026-11-
|
|
3
|
+
> Auto-generated from source code as of 2026-11-25 (v12.11.3)
|
|
4
4
|
> File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code
|
|
5
5
|
|
|
6
6
|
## CoreModule.forRoot()
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { hasApiTokenCredential } from '../../modules/api-token/core-api-token.helpers.js';
|
|
2
|
+
import { resolveJwtCookieName } from '../../modules/better-auth/better-auth-cookie-prefix.helper.js';
|
|
2
3
|
import { isLegacyJwt } from '../../modules/better-auth/core-better-auth-token.helper.js';
|
|
3
4
|
import { extractSessionToken, parseCookieHeader } from '../../modules/better-auth/core-better-auth-web.helper.js';
|
|
4
5
|
import { getBetterAuthTokenService } from '../../modules/better-auth/core-better-auth.registry.js';
|
|
5
6
|
import { ConfigService } from '../services/config.service.js';
|
|
6
7
|
import { getWsConnection, noteWsConnectionTenant, readWsTenantHeader, recheckHttpStreamInPlace, registerWsConnection, } from './graphql-ws-connection.helper.js';
|
|
7
|
-
const JWT_COOKIE_NAME = 'lt-jwt-token';
|
|
8
8
|
function firstHeaderValue(value) {
|
|
9
9
|
const first = Array.isArray(value) ? value[0] : value;
|
|
10
10
|
return typeof first === 'string' && first ? first : undefined;
|
|
@@ -30,7 +30,7 @@ function credentialTokens(credential) {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
else {
|
|
33
|
-
const jwt = cookies?.[
|
|
33
|
+
const jwt = cookies?.[resolveJwtCookieName()];
|
|
34
34
|
if (typeof jwt === 'string' && jwt.split('.').length === 3 && !isLegacy(jwt)) {
|
|
35
35
|
add(jwt);
|
|
36
36
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http-stream-auth.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/http-stream-auth.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mDAAmD,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,MAAM,4DAA4D,CAAC;AACzF,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,0DAA0D,CAAC;AAClH,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EACL,eAAe,EAEf,sBAAsB,EACtB,kBAAkB,EAClB,wBAAwB,EACxB,oBAAoB,GAErB,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"http-stream-auth.helper.js","sourceRoot":"","sources":["../../../../src/core/common/helpers/http-stream-auth.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mDAAmD,CAAC;AAC1F,OAAO,EAAE,oBAAoB,EAAE,MAAM,+DAA+D,CAAC;AACrG,OAAO,EAAE,WAAW,EAAE,MAAM,4DAA4D,CAAC;AACzF,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,0DAA0D,CAAC;AAClH,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EACL,eAAe,EAEf,sBAAsB,EACtB,kBAAkB,EAClB,wBAAwB,EACxB,oBAAoB,GAErB,MAAM,mCAAmC,CAAC;AA4B3C,SAAS,gBAA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;QACnC,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,CAAC,YAAY,CAAC,cAAc,IAAI,+BAA+B,CAAC,OAAO,CAAC,CAAC,CAAC;IAChF,IAAI,cAAc,EAAE,CAAC;QACnB,MAAM,wBAAwB,CAAC,UAAU,EAAE,EAAE,cAAc,EAAE,YAAY,EAAE,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC5G,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ForbiddenException, Logger } from '@nestjs/common';
|
|
2
|
+
import { accessDeniedException } from '../../exceptions/access-denied.exception.js';
|
|
2
3
|
import { ConfigService } from '../../services/config.service.js';
|
|
3
4
|
import { RequestContext } from '../../services/request-context.service.js';
|
|
4
5
|
const isolationDisabledWarned = new Set();
|
|
@@ -51,7 +52,8 @@ export function resolveTenantFilter(modelName) {
|
|
|
51
52
|
return { tenantId: { $in: tenantIds } };
|
|
52
53
|
if (context?.isAdminBypass)
|
|
53
54
|
return {};
|
|
54
|
-
|
|
55
|
+
const message = 'Tenant context required: this data is tenant-scoped but no valid tenant context was provided';
|
|
56
|
+
throw context?.fromRequest ? accessDeniedException(context.currentUser, message) : new ForbiddenException(message);
|
|
55
57
|
}
|
|
56
58
|
export function resolveTenantScope() {
|
|
57
59
|
if (isTenantPolicyBypassed()) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tenant.policy.js","sourceRoot":"","sources":["../../../../../src/core/common/persistence/policies/tenant.policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE5D,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,2CAA2C,CAAC;AAY3E,MAAM,uBAAuB,GAAG,IAAI,GAAG,EAAU,CAAC;AAoBlD,SAAS,qBAAqB,CAAC,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EAAE,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;QAC9D,qBAAqB,CAAC,SAAS,CAAC,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;
|
|
1
|
+
{"version":3,"file":"tenant.policy.js","sourceRoot":"","sources":["../../../../../src/core/common/persistence/policies/tenant.policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,6CAA6C,CAAC;AACpF,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,2CAA2C,CAAC;AAY3E,MAAM,uBAAuB,GAAG,IAAI,GAAG,EAAU,CAAC;AAoBlD,SAAS,qBAAqB,CAAC,SAAiB;IAC9C,IAAI,uBAAuB,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;QAC3C,OAAO;IACT,CAAC;IACD,uBAAuB,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAEvC,MAAM,eAAe,GAAG,aAAa,CAAC,qBAAqB,EAAE,YAAY,EAAE,eAAe,IAAI,cAAc,CAAC;IAC7G,IAAI,SAAS,KAAK,eAAe,EAAE,CAAC;QAClC,OAAO;IACT,CAAC;IAED,IAAI,MAAM,CAAC,sBAAsB,CAAC,CAAC,IAAI,CACrC,qCAAqC,SAAS,+CAA+C;QAC3F,IAAI,SAAS,kFAAkF;QAC/F,wFAAwF;QACxF,iCAAiC,CACpC,CAAC;AACJ,CAAC;AAaD,MAAM,UAAU,eAAe,CAAC,KAAc,EAAE,WAAmB,EAAE,KAAc;IACjF,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,WAAW,EAAE,CAAC;QACnE,OAAO;IACT,CAAC;IACD,MAAM,IAAI,kBAAkB,CAC1B,KAAK;QACH,CAA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CAC1B,kGAAkG;QAChG,8BAA8B,CACjC,CAAC;AACJ,CAAC"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export declare function resolveBetterAuthCookiePrefix(basePath: string, env?: NodeJS.ProcessEnv): string;
|
|
2
2
|
export declare function resolveBetterAuthSessionCookieName(basePath: string, env?: NodeJS.ProcessEnv): string;
|
|
3
|
+
export declare const DEFAULT_JWT_COOKIE_NAME = "lt-jwt-token";
|
|
4
|
+
export declare function resolveJwtCookieName(env?: NodeJS.ProcessEnv): string;
|
|
3
5
|
export declare function detectCookiePrefixDrift(resolvedPrefix: string, programmaticOptionsAdvanced: unknown): null | string;
|
|
@@ -9,6 +9,11 @@ export function resolveBetterAuthCookiePrefix(basePath, env = process.env) {
|
|
|
9
9
|
export function resolveBetterAuthSessionCookieName(basePath, env = process.env) {
|
|
10
10
|
return `${resolveBetterAuthCookiePrefix(basePath, env)}.session_token`;
|
|
11
11
|
}
|
|
12
|
+
export const DEFAULT_JWT_COOKIE_NAME = 'lt-jwt-token';
|
|
13
|
+
export function resolveJwtCookieName(env = process.env) {
|
|
14
|
+
const explicit = sanitizeCookiePrefix(typeof env.COOKIE_PREFIX === 'string' ? env.COOKIE_PREFIX : '');
|
|
15
|
+
return explicit ? `${explicit}-jwt-token` : DEFAULT_JWT_COOKIE_NAME;
|
|
16
|
+
}
|
|
12
17
|
export function detectCookiePrefixDrift(resolvedPrefix, programmaticOptionsAdvanced) {
|
|
13
18
|
if (!programmaticOptionsAdvanced || typeof programmaticOptionsAdvanced !== 'object')
|
|
14
19
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"better-auth-cookie-prefix.helper.js","sourceRoot":"","sources":["../../../../src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts"],"names":[],"mappings":"AAqBA,SAAS,oBAAoB,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC;AACpD,CAAC;AAsBD,MAAM,UAAU,6BAA6B,CAAC,QAAgB,EAAE,MAAyB,OAAO,CAAC,GAAG;IAClG,MAAM,cAAc,GAAG,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACnF,MAAM,QAAQ,GAAG,oBAAoB,CAAC,OAAO,GAAG,CAAC,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACtG,OAAO,QAAQ,IAAI,cAAc,CAAC;AACpC,CAAC;AAOD,MAAM,UAAU,kCAAkC,CAAC,QAAgB,EAAE,MAAyB,OAAO,CAAC,GAAG;IACvG,OAAO,GAAG,6BAA6B,CAAC,QAAQ,EAAE,GAAG,CAAC,gBAAgB,CAAC;AACzE,CAAC;AAgBD,MAAM,UAAU,uBAAuB,CAAC,cAAsB,EAAE,2BAAoC;IAClG,IAAI,CAAC,2BAA2B,IAAI,OAAO,2BAA2B,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACjG,MAAM,kBAAkB,GAAI,2BAAuD,CAAC,YAAY,CAAC;IACjG,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,KAAK,cAAc;QAAE,OAAO,IAAI,CAAC;IACjG,OAAO,CACL,kCAAkC,kBAAkB,kCAAkC;QACtF,4BAA4B,cAAc,iDAAiD;QAC3F,2EAA2E,CAC5E,CAAC;AACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"better-auth-cookie-prefix.helper.js","sourceRoot":"","sources":["../../../../src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts"],"names":[],"mappings":"AAqBA,SAAS,oBAAoB,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC;AACpD,CAAC;AA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AkC,kBAAkB,kCAAkC;QACtF,4BAA4B,cAAc,iDAAiD;QAC3F,2EAA2E,CAC5E,CAAC;AACJ,CAAC"}
|
|
@@ -10,6 +10,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var CoreBetterAuthMiddleware_1;
|
|
11
11
|
import { Injectable, Logger } from '@nestjs/common';
|
|
12
12
|
import { hasApiTokenCredential } from '../api-token/core-api-token.helpers.js';
|
|
13
|
+
import { resolveJwtCookieName } from './better-auth-cookie-prefix.helper.js';
|
|
13
14
|
import { isLegacyJwt } from './core-better-auth-token.helper.js';
|
|
14
15
|
import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
|
|
15
16
|
import { convertExpressHeaders, extractSessionToken } from './core-better-auth-web.helper.js';
|
|
@@ -86,9 +87,10 @@ let CoreBetterAuthMiddleware = CoreBetterAuthMiddleware_1 = class CoreBetterAuth
|
|
|
86
87
|
}
|
|
87
88
|
if (!req.user && !req.headers.authorization && this.betterAuthService.isJwtEnabled()) {
|
|
88
89
|
try {
|
|
89
|
-
|
|
90
|
+
const jwtCookieName = resolveJwtCookieName();
|
|
91
|
+
let jwtFromCookie = req.cookies?.[jwtCookieName];
|
|
90
92
|
if (!jwtFromCookie && req.headers.cookie) {
|
|
91
|
-
const match = req.headers.cookie.match(
|
|
93
|
+
const match = req.headers.cookie.match(new RegExp(`(?:^|;\\s*)${jwtCookieName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}=([^;]+)`));
|
|
92
94
|
if (match) {
|
|
93
95
|
jwtFromCookie = decodeURIComponent(match[1]);
|
|
94
96
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core-better-auth.middleware.js","sourceRoot":"","sources":["../../../../src/core/modules/better-auth/core-better-auth.middleware.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAkB,MAAM,gBAAgB,CAAC;AAGpE,OAAO,EAAE,qBAAqB,E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CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;wBACd,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC;wBAC5E,IAAI,aAAa,EAAE,IAAI,EAAE,CAAC;4BACxB,GAAG,CAAC,iBAAiB,GAAG,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,EAAE,IAAI,EAAE,aAAa,CAAC,IAAI,EAAE,CAAC;4BACrF,GAAG,CAAC,cAAc,GAAG,aAAa,CAAC,IAAI,CAAC;4BAExC,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;4BAC5E,IAAI,UAAU,EAAE,CAAC;gCACf,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,UAAU,EAAE,2BAA2B,EAAE,IAAI,EAAE,CAAC;gCAChE,OAAO,IAAI,EAAE,CAAC;4BAChB,CAAC;wBACH,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,2CAA2C,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE,CACtG,CAAC;YACJ,CAAC;QACH,CAAC;QAMD,IAAI,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,IAAI,IAAI,CAAC,iBAAiB,CAAC,YAAY,EAAE,EAAE,CAAC;YACrF,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"core-better-auth.middleware.js","sourceRoot":"","sources":["../../../../src/core/modules/better-auth/core-better-auth.middleware.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAkB,MAAM,gBAAgB,CAAC;AAGpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,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IACH,CAAC;CACF,CAAA;AAxPY,wBAAwB;IADpC,UAAU,EAAE;qCAK2B,qBAAqB;QAC5B,wBAAwB;GAL5C,wBAAwB,CAwPpC"}
|
|
@@ -119,7 +119,7 @@ JWT-based authentication for existing projects:
|
|
|
119
119
|
| **Query Complexity** | GraphQL query complexity analysis to prevent DoS |
|
|
120
120
|
| **Tenant Isolation** | Header-based multi-tenant isolation with membership validation (opt-in) |
|
|
121
121
|
| **Tenant Guard** | `CoreTenantGuard` validates tenant membership — and, with `multiTenancy.isTenantActive` (11.42.0), that the tenant is not deactivated; system roles (`S_EVERYONE`, `S_USER`, `S_VERIFIED`) are checked as OR alternatives before real roles; hierarchy roles (`@Roles(DefaultHR.MEMBER)`), `@SkipTenantCheck()`, BetterAuth auto-skip (`betterAuth.skipTenantCheck`). It runs AFTER the role guard (4 → 4b below); where registration order puts it first — `CoreModule` registers it ahead of a project's `AuthModule`, so with legacy JWTs nobody is identified yet — it lets the application's role guard (`ROLE_GUARD` token) identify the caller first |
|
|
122
|
-
| **Tenant Plugin Safety Net** | Mongoose tenant plugin
|
|
122
|
+
| **Tenant Plugin Safety Net** | Mongoose tenant plugin refuses a tenant-schema access without valid tenant context: 401 for a client operation nobody is signed in to (an expired session included — 12.11.3), 403 for a signed-in caller and for server work. Its post hooks (`find`, `findOne`, `findOneAnd*`) additionally check every RETURNED row (`assertRowsInTenantScope()`): a row of a tenant outside the caller's scope withholds the whole result with 403. The decisions live in `common/persistence/policies/tenant.policy.ts`, which every data store shares |
|
|
123
123
|
| **Data Store** | `DataStore<T>` (`common/persistence/`) is the database-neutral port below the CrudService pipeline; every `ModuleService` has one (`this.dataStore`, derived from `mainDbModel`, or passed as `dataStore`). On MongoDB it runs through Mongoose model methods, so every plugin fires. On PostgreSQL (`SqlDataStore`, phase 1) the same pipeline runs on plain records: before every statement the store applies the policies the plugins call (tenant filter and stamping, safety net, audit, password, role guard, system roles), the statement runs in its own transaction with the request's tenant scope so FORCED row-level security binds it (a query without a scope fails with 42501 → 403), and every returned row passes the tenant row check. References populate with one batched `id $in` read through the target model's store. Mongoose-only APIs (`aggregate`, `getModel`, native collection/connection) refuse on a SQL-stored model, and so does the Mongoose model itself (every data method of a model routed to SQL throws a named error). Since phase 2 the core's own models — users, tenant memberships, API tokens — are registered this way and their services run on the routed store; the port gained `updateOne` / `deleteOne` (atomic first match), `updateMany`, `deleteMany` and `updateById(…, { timestamps: false })`. Since phase 3 Better-Auth follows the user model: with the users on a SQL source (PostgreSQL; MySQL / MariaDB since 12.1.1) it runs its own Kysely adapter on that source's application pool, one `users` row per user, and the framework's reads of Better-Auth's data (session lookup by token in the middleware, token service, JWKS, passkey challenge mappings, e-mail-verified hook, user mapper, system setup, migration status, the MCP OAuth subject's roles) go through `BetterAuthSqlStore` — see `.claude/rules/better-auth.md` §11. Since phase 4 the AI module (eleven models, MCP OAuth clients, codes and refresh tokens) and the S3 / filesystem file metadata (`fileMetadataCollection()`, used by the file service, the TUS hand-off and the Hub) follow their routed store too; the port gained `sum()` and `find(…, { exclude })`, and an expiry sweep removes expired rows of TTL models and expired Better-Auth sessions on SQL, where no TTL index does. `CorePersistenceModule.forFeature()` + `@InjectStore()` register and inject the store; the `database` configuration routes each model to its source. Since phase 5 (12.1.0) MongoDB's libraries are optional peers: the core reaches them through `common/persistence/mongo/` (decorators that record the declaration and apply `@nestjs/mongoose`'s where installed, tokens, ObjectIds, GridFS), `CoreModule` connects MongoDB only when a source uses it, `forFeature()` provides the model tokens itself (a stand-in that refuses data access where no MongoDB is connected), and `database: false` runs without any database; the port gained `find(…, { sample })`, and the SQL update compiler skips a field given as `undefined` as Mongoose does |
|
|
124
124
|
| **API Tokens** | `apiTokens` config (opt-in): USER tokens act as their user without global roles; TENANT tokens (multi-tenancy only) act with the lowest tenant role in their own tenant. `CoreApiTokenMiddleware` authenticates `Authorization: Bearer` / `x-api-key`; every guard denies a token unless the route declares `@ApiTokenScopes()`. Signed short-lived assertions for embedded pages. See `src/core/modules/api-token/README.md` |
|
|
125
125
|
|
|
@@ -301,7 +301,7 @@ nest-server implements **defense-in-depth security** with three complementary la
|
|
|
301
301
|
| | - Role Guard | | - TranslateResponse | |
|
|
302
302
|
| | - Audit Fields | | - CheckSecurity (secrets) | |
|
|
303
303
|
| | - Tenant Isolation | | - CheckResponse (@Restrict) | |
|
|
304
|
-
| |
|
|
304
|
+
| | (Safety Net: 401/403) | | | |
|
|
305
305
|
| +--------------------------+ +------------------------------+ |
|
|
306
306
|
| |
|
|
307
307
|
+===================================================================+
|
|
@@ -1107,7 +1107,7 @@ When the service performs write operations (save, update), Mongoose plugins fire
|
|
|
1107
1107
|
Enabled via `multiTenancy: {}` in config. Auto-activates only on schemas with a `tenantId` field.
|
|
1108
1108
|
The `tenantId` is read from RequestContext (set by CoreTenantGuard via `req.tenantId`), not the raw header.
|
|
1109
1109
|
|
|
1110
|
-
**Safety Net:** If a tenant-schema is accessed without a valid tenant context (no `tenantId` and no bypass), the plugin
|
|
1110
|
+
**Safety Net:** If a tenant-schema is accessed without a valid tenant context (no `tenantId` and no bypass), the plugin refuses it — with 401 when nobody is signed in to the request (signing in is the only way to a tenant context, and a frontend signs out only on a 401), with 403 for a signed-in caller and for server work. This prevents accidental cross-tenant data leaks when developers forget to set the tenant header or bypass.
|
|
1111
1111
|
|
|
1112
1112
|
**Row check after reads:** the pre hooks decide which rows a query may touch; post hooks on `find`, `findOne` and `findOneAnd*` check what came back, with the same policy a SQL store applies (`assertRowsInTenantScope()`). On a correct path the filter already holds and nothing changes; a row of another tenant — a filter built with the wrong scope — withholds the result with 403 and logs an error naming the model, never the foreign tenant. Rows without a `tenantId` property (a projection left it out) cannot be verified and pass. Aggregations are not checked: their output is reshaped.
|
|
1113
1113
|
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Migration Guide: 12.11.1 → 12.11.2
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None |
|
|
8
|
+
| **New Features** | None. `resolveJwtCookieName()` and `DEFAULT_JWT_COOKIE_NAME` name the JWT cookie |
|
|
9
|
+
| **Bugfixes** | With `COOKIE_PREFIX`, the API reads a JWT-mode frontend's JWT cookie under `<prefix>-jwt-token`, the name `@lenne.tech/nuxt-extensions` writes (§1) |
|
|
10
|
+
| **Security** | None |
|
|
11
|
+
| **Migration Effort** | Package update. Only projects that set `COOKIE_PREFIX` and run in JWT mode (`cookies: false`) notice a difference |
|
|
12
|
+
|
|
13
|
+
## Quick Migration
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pnpm add @lenne.tech/nest-server@12.11.2
|
|
17
|
+
pnpm run update # nest-server-starter based projects
|
|
18
|
+
pnpm run build
|
|
19
|
+
pnpm test
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
|
|
23
|
+
|
|
24
|
+
## 1. Bugfix: the JWT cookie follows `COOKIE_PREFIX`
|
|
25
|
+
|
|
26
|
+
**No action needed.** Keep `COOKIE_PREFIX` (API) and `NUXT_PUBLIC_COOKIE_PREFIX` (app) equal, as before.
|
|
27
|
+
|
|
28
|
+
In JWT mode the frontend keeps the Better-Auth JWT in a cookie as well as sending it as a bearer token. A request that
|
|
29
|
+
carries the cookie but no `Authorization` header is authenticated by `CoreBetterAuthMiddleware` from that cookie: a
|
|
30
|
+
server-side rendered page that forwards the browser's cookies, a passkey request from the app, and the in-place re-check
|
|
31
|
+
of an SSE stream (`registerHttpStream()`).
|
|
32
|
+
|
|
33
|
+
`@lenne.tech/nuxt-extensions` names that cookie `<NUXT_PUBLIC_COOKIE_PREFIX>-jwt-token` when a prefix is set. Up to
|
|
34
|
+
12.11.1 the API read `lt-jwt-token` only. With a prefix such a request was anonymous, and Better-Auth's plugin routes
|
|
35
|
+
(passkey registration, two-factor) answered `401`.
|
|
36
|
+
|
|
37
|
+
| `COOKIE_PREFIX` | JWT cookie read since 12.11.2 | Before |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| not set | `lt-jwt-token` | `lt-jwt-token` |
|
|
40
|
+
| `acme` | `acme-jwt-token` | `lt-jwt-token` |
|
|
41
|
+
|
|
42
|
+
The prefix is sanitised by the same rule as on the frontend (`[A-Za-z0-9._-]`). The base path does not enter the name,
|
|
43
|
+
unlike the session cookie (`<prefix>.session_token`, else `iam.session_token`). There is no fallback to `lt-jwt-token`
|
|
44
|
+
while `COOKIE_PREFIX` is set: the prefix keeps the apps on one host apart, and the session cookie does not fall back
|
|
45
|
+
either.
|
|
46
|
+
|
|
47
|
+
## 2. Dependencies
|
|
48
|
+
|
|
49
|
+
| Package | 12.11.1 | 12.11.2 |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| `ai` (optional peer) | 7.0.179 | 7.0.181 |
|
|
52
|
+
| `@aws-sdk/client-s3`, `@aws-sdk/lib-storage`, `@aws-sdk/s3-request-presigner` (optional peers) | 3.1175.0 | 3.1176.0 |
|
|
53
|
+
|
|
54
|
+
Maintenance releases without advisories; the peer ranges are unchanged. The dated `minimumReleaseAgeExclude` entry for
|
|
55
|
+
`mongoose@9.13.0` from 12.11.1 is removed; mongoose 9.13.0 has cleared the release-age gate.
|
|
56
|
+
|
|
57
|
+
## Compatibility Notes
|
|
58
|
+
|
|
59
|
+
| Pattern | Status |
|
|
60
|
+
|---|---|
|
|
61
|
+
| No `COOKIE_PREFIX` | Unchanged |
|
|
62
|
+
| `COOKIE_PREFIX` with cookies (the default `cookies: true`) | Unchanged; the session cookie already followed the prefix |
|
|
63
|
+
| `COOKIE_PREFIX` with `cookies: false` and a matching `NUXT_PUBLIC_COOKIE_PREFIX` | Fixed: the JWT cookie is read |
|
|
64
|
+
| A frontend that sets `COOKIE_PREFIX` on the API but writes `lt-jwt-token` | No longer authenticated through the cookie. Set the same prefix on both sides |
|
|
65
|
+
|
|
66
|
+
## Troubleshooting
|
|
67
|
+
|
|
68
|
+
| Symptom | Cause | Fix |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| Passkey or 2FA routes answer `401` in JWT mode with a cookie prefix | 12.11.1 or older read only `lt-jwt-token` | Update to 12.11.2 |
|
|
71
|
+
| Still `401` after the update | The API and the app use different prefixes | Set `COOKIE_PREFIX` and `NUXT_PUBLIC_COOKIE_PREFIX` to the same value |
|
|
72
|
+
|
|
73
|
+
## Module Documentation
|
|
74
|
+
|
|
75
|
+
- `src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts`: `resolveJwtCookieName()`, `resolveBetterAuthCookiePrefix()`
|
|
76
|
+
- `migration-guides/11.26.1-to-11.26.2.md`, §1: `COOKIE_PREFIX` and the frontend pairing
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Migration Guide: 12.11.2 → 12.11.3
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
| Category | Details |
|
|
6
|
+
|---|---|
|
|
7
|
+
| **Breaking Changes** | None |
|
|
8
|
+
| **New Features** | None |
|
|
9
|
+
| **Bugfixes** | With `multiTenancy`, the tenant safety net answers a request nobody is signed in to with `401` instead of `403` — also a request whose session has expired (§1) |
|
|
10
|
+
| **Security** | None |
|
|
11
|
+
| **Migration Effort** | Package update. Only multi-tenant projects whose own tests or client code expect `403` for an anonymous request to tenant-scoped data adjust that expectation |
|
|
12
|
+
|
|
13
|
+
## Quick Migration
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pnpm add @lenne.tech/nest-server@12.11.3
|
|
17
|
+
pnpm run update # nest-server-starter based projects
|
|
18
|
+
pnpm run build
|
|
19
|
+
pnpm test
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
|
|
23
|
+
|
|
24
|
+
## 1. Bugfix: an expired session reaches the sign-in, also on tenant-scoped data
|
|
25
|
+
|
|
26
|
+
**No action needed** for most projects. A multi-tenant project whose tests assert `403` for an ANONYMOUS request that
|
|
27
|
+
reads tenant-scoped data changes them to `401`.
|
|
28
|
+
|
|
29
|
+
When a request reads tenant-scoped data without a valid tenant context, the tenant safety net
|
|
30
|
+
(`resolveTenantFilter()`, used by the Mongoose tenant plugin and the SQL stores) refuses it instead of returning
|
|
31
|
+
unfiltered rows. Up to 12.11.2 it answered `403` to everyone. A browser keeps sending the cookie of an expired
|
|
32
|
+
session, so a public route that reads tenant-scoped data answered such a user `403`, and the frontend showed
|
|
33
|
+
"data could not be loaded" instead of the sign-in: `@lenne.tech/nuxt-extensions` signs out on a `401` and on nothing
|
|
34
|
+
else.
|
|
35
|
+
|
|
36
|
+
The safety net now follows the rule every other permission layer already follows (`accessDeniedException()`):
|
|
37
|
+
|
|
38
|
+
| Caller | Since 12.11.3 | Before |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| A client request nobody is signed in to (no credential, an unknown or expired session, an expired JWT) | `401` | `403` |
|
|
41
|
+
| A signed-in caller without a tenant context | `403` | `403` |
|
|
42
|
+
| Server work inside a request context of its own (no client request) | `403` | `403` |
|
|
43
|
+
|
|
44
|
+
The message (`Tenant context required: …`) is unchanged, and the refusal is the same: only its status differs. The
|
|
45
|
+
role guards (`RolesGuard`, `BetterAuthRolesGuard`) and `CoreTenantGuard` already answered an expired or unknown session
|
|
46
|
+
with `401`; 12.11.3 adds tests that pin it on both guards, over REST and GraphQL, for an unknown session cookie, an
|
|
47
|
+
expired session, the JWT cookie of an expired session and an expired JWT.
|
|
48
|
+
|
|
49
|
+
## 2. Documentation: the first administrator of a project that signs in through a provider alone
|
|
50
|
+
|
|
51
|
+
`src/core/modules/better-auth/README.md` → "The first administrator" describes how the administrator created by
|
|
52
|
+
`POST /system-setup/init` reaches the project when `emailAndPassword` is off: the init password is a credential nobody
|
|
53
|
+
can use while e-mail and password sign-in is off (use a long random value and do not keep it), and the first provider
|
|
54
|
+
sign-in is linked to the administrator only when the provider reports the address as verified — Microsoft Entra ID
|
|
55
|
+
only with the optional ID token claim `verified_primary_email`. Do not make linking work through
|
|
56
|
+
`betterAuth.options.account.accountLinking.trustedProviders` or `emailVerified: true` from `mapProfileToUser`: both
|
|
57
|
+
skip that check, and an Entra tenant administrator can give any user any address.
|
|
58
|
+
|
|
59
|
+
## 3. Dependencies
|
|
60
|
+
|
|
61
|
+
| Package | 12.11.2 | 12.11.3 |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `graphql-ws` | 6.4.1 | 6.4.3 |
|
|
64
|
+
| `better-auth`, `@better-auth/core`, `@better-auth/passkey` (required peers, tested version) | 1.7.23 | 1.7.28 |
|
|
65
|
+
| `mongoose` (optional peer) | 9.13.0 | 9.13.1 |
|
|
66
|
+
| `bullmq` (optional peer) | 6.7.8 | 6.7.10 |
|
|
67
|
+
| `@aws-sdk/client-s3`, `@aws-sdk/lib-storage`, `@aws-sdk/s3-request-presigner` (optional peers) | 3.1176.0 | 3.1177.0 |
|
|
68
|
+
|
|
69
|
+
Maintenance releases without advisories; every peer range is unchanged (`better-auth` stays `>=1.7.16 <1.8.0`). The
|
|
70
|
+
better-auth version is the one this release is tested against: a project keeps its own `better-auth` pin and may raise
|
|
71
|
+
it to 1.7.28, together with `@better-auth/passkey` and `@better-auth/core` and with the app's pin in a fullstack
|
|
72
|
+
project. `pnpm run update` raises `graphql-ws` and the optional peers a project declares.
|
|
73
|
+
|
|
74
|
+
## Compatibility Notes
|
|
75
|
+
|
|
76
|
+
| Pattern | Status |
|
|
77
|
+
|---|---|
|
|
78
|
+
| No `multiTenancy` | Unchanged |
|
|
79
|
+
| `multiTenancy`, signed-in requests | Unchanged (`403` where the tenant context is missing) |
|
|
80
|
+
| `multiTenancy`, anonymous request to tenant-scoped data (public route, expired session) | `401` instead of `403` |
|
|
81
|
+
| Code that catches `ForbiddenException` from the safety net for an anonymous request | Catch `UnauthorizedException` as well, or both via `HttpException` |
|
|
82
|
+
| `GET /iam/features` | Unchanged; `jwt` follows the JWT plugin registration (now pinned by a test) |
|
|
83
|
+
|
|
84
|
+
## Troubleshooting
|
|
85
|
+
|
|
86
|
+
| Symptom | Cause | Fix |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| A project test expects `403` for an anonymous tenant-scoped read and now gets `401` | 12.11.3 answers the safety net by the requester's auth state | Expect `401` for the anonymous case, `403` for a signed-in caller |
|
|
89
|
+
| The frontend still shows a load error after the session expired | A project's own guard or exception answers `403` without a user | Throw `accessDeniedException(currentUser)` instead of a fixed `ForbiddenException` |
|
|
90
|
+
|
|
91
|
+
## Module Documentation
|
|
92
|
+
|
|
93
|
+
- `src/core/common/persistence/policies/tenant.policy.ts`: `resolveTenantFilter()`
|
|
94
|
+
- `src/core/common/exceptions/access-denied.exception.ts`: `accessDeniedException()`
|
|
95
|
+
- `src/core/modules/tenant/README.md`: Safety Net
|
|
96
|
+
- `src/core/modules/better-auth/README.md`: "Sign-in through a provider alone", "The first administrator"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lenne.tech/nest-server",
|
|
3
|
-
"version": "12.11.
|
|
3
|
+
"version": "12.11.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
|
|
6
6
|
"keywords": [
|
|
@@ -134,7 +134,7 @@
|
|
|
134
134
|
"graphql-query-complexity": "2.0.0",
|
|
135
135
|
"graphql-subscriptions": "3.1.0",
|
|
136
136
|
"graphql-upload": "17.1.0",
|
|
137
|
-
"graphql-ws": "6.4.
|
|
137
|
+
"graphql-ws": "6.4.3",
|
|
138
138
|
"http-errors": "2.0.1",
|
|
139
139
|
"jose": "6.2.18",
|
|
140
140
|
"js-sha256": "1.1.0",
|
|
@@ -244,11 +244,11 @@
|
|
|
244
244
|
}
|
|
245
245
|
},
|
|
246
246
|
"devDependencies": {
|
|
247
|
-
"@aws-sdk/client-s3": "3.
|
|
248
|
-
"@aws-sdk/lib-storage": "3.
|
|
249
|
-
"@aws-sdk/s3-request-presigner": "3.
|
|
250
|
-
"@better-auth/core": "1.7.
|
|
251
|
-
"@better-auth/passkey": "1.7.
|
|
247
|
+
"@aws-sdk/client-s3": "3.1177.0",
|
|
248
|
+
"@aws-sdk/lib-storage": "3.1177.0",
|
|
249
|
+
"@aws-sdk/s3-request-presigner": "3.1177.0",
|
|
250
|
+
"@better-auth/core": "1.7.28",
|
|
251
|
+
"@better-auth/passkey": "1.7.28",
|
|
252
252
|
"@compodoc/compodoc": "2.0.0",
|
|
253
253
|
"@modelcontextprotocol/server": "2.4.0",
|
|
254
254
|
"@nestjs/ai": "0.0.2",
|
|
@@ -269,24 +269,24 @@
|
|
|
269
269
|
"@types/http-errors": "2.0.5",
|
|
270
270
|
"@types/lodash": "4.17.27",
|
|
271
271
|
"@types/multer": "2.3.0",
|
|
272
|
-
"@types/node": "26.6.
|
|
272
|
+
"@types/node": "26.6.9",
|
|
273
273
|
"@types/object-path": "0.11.4",
|
|
274
274
|
"@types/passport": "1.0.17",
|
|
275
275
|
"@types/pg": "8.23.1",
|
|
276
276
|
"@vitest/coverage-v8": "5.1.1",
|
|
277
|
-
"ai": "7.0.
|
|
278
|
-
"better-auth": "1.7.
|
|
279
|
-
"bullmq": "6.7.
|
|
277
|
+
"ai": "7.0.181",
|
|
278
|
+
"better-auth": "1.7.28",
|
|
279
|
+
"bullmq": "6.7.10",
|
|
280
280
|
"cross-env": "10.1.0",
|
|
281
281
|
"drizzle-orm": "1.0.0-rc.5",
|
|
282
282
|
"ioredis": "6.1.0",
|
|
283
283
|
"kysely": "0.29.9",
|
|
284
284
|
"mongodb": "7.9.1",
|
|
285
|
-
"mongoose": "9.13.
|
|
285
|
+
"mongoose": "9.13.1",
|
|
286
286
|
"mysql2": "3.24.6",
|
|
287
287
|
"nodemon": "3.1.14",
|
|
288
288
|
"otpauth": "9.6.0",
|
|
289
|
-
"oxfmt": "0.
|
|
289
|
+
"oxfmt": "0.80.0",
|
|
290
290
|
"oxlint": "1.94.0",
|
|
291
291
|
"oxlint-tsgolint": "7.0.2008",
|
|
292
292
|
"pg": "8.23.1",
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { hasApiTokenCredential } from '../../modules/api-token/core-api-token.helpers.js';
|
|
2
|
+
import { resolveJwtCookieName } from '../../modules/better-auth/better-auth-cookie-prefix.helper.js';
|
|
2
3
|
import { isLegacyJwt } from '../../modules/better-auth/core-better-auth-token.helper.js';
|
|
3
4
|
import { extractSessionToken, parseCookieHeader } from '../../modules/better-auth/core-better-auth-web.helper.js';
|
|
4
5
|
import { getBetterAuthTokenService } from '../../modules/better-auth/core-better-auth.registry.js';
|
|
@@ -25,15 +26,13 @@ import type { ResolvedTenantContext } from '../services/core-tenant-context.regi
|
|
|
25
26
|
* re-checked in place like a GraphQL WebSocket (`recheckHttpStreamInPlace()`).
|
|
26
27
|
*
|
|
27
28
|
* WHICH CREDENTIALS: the ones `CoreBetterAuthMiddleware` resolves, in its order — the bearer token of the
|
|
28
|
-
* `Authorization` header (a Better-Auth JWT or session token), the
|
|
29
|
+
* `Authorization` header (a Better-Auth JWT or session token), the JWT cookie when no header was sent (`lt-jwt-token`, or
|
|
30
|
+
* `<COOKIE_PREFIX>-jwt-token` with a prefix), then
|
|
29
31
|
* the Better-Auth session cookie (`<prefix>.session_token`, signed or not) — each verified and loaded through
|
|
30
32
|
* Better-Auth's token service, the one the IAM role guard uses. A legacy JWT is Passport's and an API token has checks
|
|
31
33
|
* of its own: neither can be re-run here, and such a stream keeps ending on every re-check.
|
|
32
34
|
*/
|
|
33
35
|
|
|
34
|
-
/** The cookie a JWT-mode frontend keeps the Better-Auth JWT in — the one `CoreBetterAuthMiddleware` reads. */
|
|
35
|
-
const JWT_COOKIE_NAME = 'lt-jwt-token';
|
|
36
|
-
|
|
37
36
|
/** What a request carried to authenticate, as it was when the stream was opened. */
|
|
38
37
|
interface HttpStreamCredential {
|
|
39
38
|
authorization?: string;
|
|
@@ -73,7 +72,8 @@ function credentialTokens(credential: HttpStreamCredential): string[] {
|
|
|
73
72
|
add(token);
|
|
74
73
|
}
|
|
75
74
|
} else {
|
|
76
|
-
|
|
75
|
+
// The cookie `CoreBetterAuthMiddleware` reads: `<COOKIE_PREFIX>-jwt-token`, else `lt-jwt-token` (12.11.2)
|
|
76
|
+
const jwt = cookies?.[resolveJwtCookieName()];
|
|
77
77
|
if (typeof jwt === 'string' && jwt.split('.').length === 3 && !isLegacy(jwt)) {
|
|
78
78
|
add(jwt);
|
|
79
79
|
}
|
|
@@ -90,7 +90,7 @@ function credentialTokens(credential: HttpStreamCredential): string[] {
|
|
|
90
90
|
|
|
91
91
|
/**
|
|
92
92
|
* Build the re-authentication of an HTTP stream from the request that opened it: a function that re-runs the
|
|
93
|
-
* request's Better-Auth credential (bearer token,
|
|
93
|
+
* request's Better-Auth credential (bearer token, JWT cookie, session cookie — see the file comment) and
|
|
94
94
|
* resolves to the user it authenticates as NOW, or to `null` when it no longer does (a signed-out or expired session,
|
|
95
95
|
* an expired JWT).
|
|
96
96
|
*
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ForbiddenException, Logger } from '@nestjs/common';
|
|
2
2
|
|
|
3
|
+
import { accessDeniedException } from '../../exceptions/access-denied.exception.js';
|
|
3
4
|
import { ConfigService } from '../../services/config.service.js';
|
|
4
5
|
import { RequestContext } from '../../services/request-context.service.js';
|
|
5
6
|
|
|
@@ -100,14 +101,15 @@ export function isTenantPolicyBypassed(modelName?: string): boolean {
|
|
|
100
101
|
* Resolve tenant filter from RequestContext for read operations (queries, aggregates).
|
|
101
102
|
*
|
|
102
103
|
* Defense-in-depth: If a schema has tenantId but there is no valid tenant context,
|
|
103
|
-
* throws
|
|
104
|
+
* throws instead of returning unfiltered data (Safety Net) — 401 for a client operation without a user, 403 otherwise.
|
|
104
105
|
*
|
|
105
106
|
* @returns
|
|
106
107
|
* - `undefined` → no filter should be applied (bypass active or plugin disabled)
|
|
107
108
|
* - `{}` → empty filter (admin bypass without header — sees all data)
|
|
108
109
|
* - `{ tenantId: string }` → filter by single validated tenant
|
|
109
110
|
* - `{ tenantId: { $in: string[] } }` → filter by user's tenant memberships
|
|
110
|
-
* @throws
|
|
111
|
+
* @throws when tenantId-schema is accessed without valid tenant context: UnauthorizedException (401) for a client
|
|
112
|
+
* operation without a user, ForbiddenException (403) for a signed-in caller and for server work
|
|
111
113
|
*/
|
|
112
114
|
export function resolveTenantFilter(modelName?: string): Record<string, any> | undefined {
|
|
113
115
|
if (isTenantPolicyBypassed(modelName)) return undefined;
|
|
@@ -127,9 +129,12 @@ export function resolveTenantFilter(modelName?: string): Record<string, any> | u
|
|
|
127
129
|
|
|
128
130
|
// SAFETY NET: Schema has tenantId but no valid tenant context.
|
|
129
131
|
// Throw instead of returning unfiltered data to prevent data leaks.
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
132
|
+
const message = 'Tenant context required: this data is tenant-scoped but no valid tenant context was provided';
|
|
133
|
+
// A CLIENT operation without a user (an expired session, a public route) is answered 401: a tenant context comes
|
|
134
|
+
// from a membership, so signing in is the remedy, and a 403 kept a frontend with an expired session from signing
|
|
135
|
+
// out (it reads only 401 as "signed out"). A signed-in caller keeps the 403 — the same rule as every other
|
|
136
|
+
// permission layer (`accessDeniedException()`). Server work without a request keeps the 403 as well.
|
|
137
|
+
throw context?.fromRequest ? accessDeniedException(context.currentUser, message) : new ForbiddenException(message);
|
|
133
138
|
}
|
|
134
139
|
|
|
135
140
|
/**
|
|
@@ -734,6 +734,24 @@ betterAuth: {
|
|
|
734
734
|
`session.disableSessionRefresh`. A value of `expiresInHours` that is not a positive number is ignored with a warning.
|
|
735
735
|
`betterAuth.options.session` still wins key by key.
|
|
736
736
|
|
|
737
|
+
#### The first administrator
|
|
738
|
+
|
|
739
|
+
`POST /system-setup/init` (or `systemSetup.initialAdmin`) creates the administrator with a verified address. It still
|
|
740
|
+
asks for a password: that becomes a credential account nobody can use while `emailAndPassword` is off, and it starts to
|
|
741
|
+
work if e-mail and password sign-in is switched on later. Use a long random value and do not keep it.
|
|
742
|
+
|
|
743
|
+
The administrator then signs in through the provider with the same address. Better-Auth adds the provider account to
|
|
744
|
+
the existing user only when the provider reports the address as verified; otherwise the sign-in ends with
|
|
745
|
+
`error=account_not_linked`. Google and GitHub report it. **Microsoft Entra ID reports it only with the optional ID token
|
|
746
|
+
claim `verified_primary_email`** (app registration → Token configuration → Add optional claim → ID;
|
|
747
|
+
`verified_secondary_email` covers further addresses).
|
|
748
|
+
|
|
749
|
+
**Never make linking work by trusting the provider instead.** Listing it in
|
|
750
|
+
`betterAuth.options.account.accountLinking.trustedProviders`, or returning `emailVerified: true` from
|
|
751
|
+
`mapProfileToUser`, skips that check. An administrator of an Entra tenant can give any user any e-mail address (with
|
|
752
|
+
`tenantId` unset: of any tenant), and that user then signs in as the account holding the address — your administrator
|
|
753
|
+
included. Microsoft advises against identifying users by the e-mail claim for this reason.
|
|
754
|
+
|
|
737
755
|
#### Microsoft Entra ID: one organization, identity only
|
|
738
756
|
|
|
739
757
|
```typescript
|
|
@@ -58,6 +58,23 @@ export function resolveBetterAuthSessionCookieName(basePath: string, env: NodeJS
|
|
|
58
58
|
return `${resolveBetterAuthCookiePrefix(basePath, env)}.session_token`;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/** The name of the JWT cookie without `COOKIE_PREFIX`, the one `@lenne.tech/nuxt-extensions` writes by default. */
|
|
62
|
+
export const DEFAULT_JWT_COOKIE_NAME = 'lt-jwt-token';
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The cookie a JWT-mode frontend keeps the Better-Auth JWT in (12.11.2): `<COOKIE_PREFIX>-jwt-token` when `COOKIE_PREFIX`
|
|
66
|
+
* is set, otherwise `lt-jwt-token`. `@lenne.tech/nuxt-extensions` names it the same way from `NUXT_PUBLIC_COOKIE_PREFIX`,
|
|
67
|
+
* sanitised by the same rule. Unlike the session cookie, the basePath never enters the name.
|
|
68
|
+
*
|
|
69
|
+
* There is no fallback to `lt-jwt-token` while `COOKIE_PREFIX` is set: the prefix isolates the apps on one host, and
|
|
70
|
+
* the session cookie does not fall back either. Before 12.11.2 the API read `lt-jwt-token` only, so with a prefix
|
|
71
|
+
* every request without an `Authorization` header (SSR with forwarded cookies, a stream re-check) was anonymous.
|
|
72
|
+
*/
|
|
73
|
+
export function resolveJwtCookieName(env: NodeJS.ProcessEnv = process.env): string {
|
|
74
|
+
const explicit = sanitizeCookiePrefix(typeof env.COOKIE_PREFIX === 'string' ? env.COOKIE_PREFIX : '');
|
|
75
|
+
return explicit ? `${explicit}-jwt-token` : DEFAULT_JWT_COOKIE_NAME;
|
|
76
|
+
}
|
|
77
|
+
|
|
61
78
|
/**
|
|
62
79
|
* Detect a Better-Auth cookie-prefix drift between the value the NestJS layer
|
|
63
80
|
* resolves (via {@link resolveBetterAuthCookiePrefix}) and a programmatic
|
|
@@ -2,6 +2,7 @@ import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
|
|
|
2
2
|
import { NextFunction, Request, Response } from 'express';
|
|
3
3
|
|
|
4
4
|
import { hasApiTokenCredential } from '../api-token/core-api-token.helpers.js';
|
|
5
|
+
import { resolveJwtCookieName } from './better-auth-cookie-prefix.helper.js';
|
|
5
6
|
import { isLegacyJwt } from './core-better-auth-token.helper.js';
|
|
6
7
|
import { BetterAuthSessionUser, CoreBetterAuthUserMapper, MappedUser } from './core-better-auth-user.mapper.js';
|
|
7
8
|
import { convertExpressHeaders, extractSessionToken } from './core-better-auth-web.helper.js';
|
|
@@ -143,14 +144,18 @@ export class CoreBetterAuthMiddleware implements NestMiddleware {
|
|
|
143
144
|
|
|
144
145
|
// Strategy 2: Try JWT from cookie (for JWT mode when frontend stores JWT as cookie)
|
|
145
146
|
// In JWT mode (cookies=false), the frontend may store the JWT in a cookie
|
|
146
|
-
// (
|
|
147
|
+
// (`lt-jwt-token`, `<COOKIE_PREFIX>-jwt-token` with a prefix) instead of sending it as an Authorization header.
|
|
147
148
|
// This bridges the gap between cookie-based frontend storage and JWT verification.
|
|
148
149
|
if (!req.user && !req.headers.authorization && this.betterAuthService.isJwtEnabled()) {
|
|
149
150
|
try {
|
|
150
|
-
// Try parsed cookies first, then raw header (cookie-parser may not have run yet)
|
|
151
|
-
|
|
151
|
+
// Try parsed cookies first, then raw header (cookie-parser may not have run yet). The name follows
|
|
152
|
+
// COOKIE_PREFIX like the frontend's (`<prefix>-jwt-token`, else `lt-jwt-token`; 12.11.2).
|
|
153
|
+
const jwtCookieName = resolveJwtCookieName();
|
|
154
|
+
let jwtFromCookie = req.cookies?.[jwtCookieName];
|
|
152
155
|
if (!jwtFromCookie && req.headers.cookie) {
|
|
153
|
-
const match = req.headers.cookie.match(
|
|
156
|
+
const match = req.headers.cookie.match(
|
|
157
|
+
new RegExp(`(?:^|;\\s*)${jwtCookieName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}=([^;]+)`),
|
|
158
|
+
);
|
|
154
159
|
if (match) {
|
|
155
160
|
jwtFromCookie = decodeURIComponent(match[1]);
|
|
156
161
|
}
|
|
@@ -141,7 +141,7 @@ A hint tells a connected client that pulling is worthwhile; sync works without t
|
|
|
141
141
|
stream is registered in the same registry and re-checked at once on an invalidation naming the caller or their
|
|
142
142
|
tenant, and otherwise before the first hint after `graphQl.subscriptionRevalidationMs`.
|
|
143
143
|
- **In place (12.11.0)** when the stream was opened with a Better-Auth credential — the session cookie, a bearer
|
|
144
|
-
session token or Better-Auth JWT, the `lt-jwt-token`
|
|
144
|
+
session token or Better-Auth JWT, the JWT cookie (`lt-jwt-token`, `<COOKIE_PREFIX>-jwt-token` with a prefix): the re-check runs that credential again
|
|
145
145
|
(`createHttpStreamReauthenticator()`) and the tenant resolution, like a WebSocket's. Unchanged rights keep the
|
|
146
146
|
stream open and the hint is delivered without a reconnect; changed user id, roles, verification or tenant scope
|
|
147
147
|
close it (`Closing SSE hint stream of user …: User authorization changed` / `Session no longer valid` /
|
|
@@ -103,6 +103,10 @@ Creates the initial admin user. Only works when zero users exist, and only where
|
|
|
103
103
|
| `password` | string | Yes | Minimum 8 characters |
|
|
104
104
|
| `name` | string | No | Defaults to email prefix |
|
|
105
105
|
|
|
106
|
+
On a project that signs in through a provider alone (`betterAuth.emailAndPassword.enabled: false`) the password is
|
|
107
|
+
required as well but cannot be used for signing in; the administrator signs in through the provider, which must report
|
|
108
|
+
the address as verified. See "The first administrator" in `src/core/modules/better-auth/README.md`.
|
|
109
|
+
|
|
106
110
|
**Success Response (201):**
|
|
107
111
|
|
|
108
112
|
```json
|
|
@@ -194,12 +194,12 @@ See the module README: "Removing a Tenant".
|
|
|
194
194
|
- [ ] Admin user can access any tenant (if adminBypass: true)
|
|
195
195
|
- [ ] Non-member gets 403 `#LTNS_0103: Not a member of this tenant`
|
|
196
196
|
- [ ] Unauthenticated + header → 401 `#LTNS_0100` (re-authentication is the remedy, so it is not a 403)
|
|
197
|
-
- [ ] Public endpoint accessing tenantId-schema without context
|
|
197
|
+
- [ ] Public endpoint accessing tenantId-schema without context is refused by the Safety Net: 401 without a session (an expired one included), 403 when signed in
|
|
198
198
|
- [ ] IAM endpoints work without `X-Tenant-Id` header when `skipTenantCheck: true` (default)
|
|
199
199
|
|
|
200
200
|
## Security
|
|
201
201
|
|
|
202
|
-
> **Defense-in-Depth:** The guard validates membership and sets `req.tenantId`. The Mongoose plugin only uses this validated value (via RequestContext) — never the raw header. Additionally, the plugin's Safety Net
|
|
202
|
+
> **Defense-in-Depth:** The guard validates membership and sets `req.tenantId`. The Mongoose plugin only uses this validated value (via RequestContext) — never the raw header. Additionally, the plugin's Safety Net refuses access to a tenantId-scoped schema without valid tenant context (401 when nobody is signed in, 403 otherwise).
|
|
203
203
|
|
|
204
204
|
> **Tenant overrides user.roles:** When a tenant header is present, only `membership.role` is checked. `user.roles` is ignored (except ADMIN bypass). This prevents users from claiming higher privileges via `user.roles` when operating within a specific tenant.
|
|
205
205
|
|
|
@@ -213,7 +213,7 @@ See the module README: "Removing a Tenant".
|
|
|
213
213
|
| Forgetting `X-Tenant-Id` header | 403 or Safety Net exception | Add header to all tenant-scoped API calls |
|
|
214
214
|
| Using only `@Roles(S_USER)` for tenant endpoints | No tenant membership check | Use `@Roles(DefaultHR.MEMBER)` for tenant-level access |
|
|
215
215
|
| Querying membership without bypass | Empty results due to tenant filter | Use `RequestContext.runWithBypassTenantGuard()` |
|
|
216
|
-
| Public endpoint accessing tenantId-schema | 403 Safety Net exception
|
|
216
|
+
| Public endpoint accessing tenantId-schema | 401 / 403 Safety Net exception | Use `@SkipTenantCheck()` + `RequestContext.runWithBypassTenantGuard()` |
|
|
217
217
|
| Passing user-supplied tenantId to create() | Cross-tenant write possible | Let plugin auto-set tenantId from context |
|
|
218
218
|
| Custom hierarchy doesn't match config | Roles fail unexpectedly | Ensure `createHierarchyRoles()` input matches `multiTenancy.roleHierarchy` |
|
|
219
219
|
| `@SkipTenantCheck()` on BetterAuth handler | Redundant since v11.21.2 | Remove — auto-skip handles this via `betterAuth.skipTenantCheck` (default) |
|
|
@@ -24,7 +24,7 @@ Request + X-Tenant-Id Header
|
|
|
24
24
|
**Defense-in-depth:** Two layers of protection:
|
|
25
25
|
|
|
26
26
|
1. **Guard level:** CoreTenantGuard validates membership and sets `tenantId` (only after successful check)
|
|
27
|
-
2. **Plugin level:** Safety Net —
|
|
27
|
+
2. **Plugin level:** Safety Net — refuses access to a tenantId-scoped schema without valid tenant context: 401 when nobody is signed in (since 12.11.3 — an expired session must reach the sign-in), 403 for a signed-in caller
|
|
28
28
|
|
|
29
29
|
## Configuration
|
|
30
30
|
|
|
@@ -309,8 +309,8 @@ anonymous caller of a public route through.
|
|
|
309
309
|
|
|
310
310
|
| User State | Filter Applied |
|
|
311
311
|
| ----------------------------------------------------- | ------------------------------------------------------------------- |
|
|
312
|
-
| Not authenticated, no context | Safety Net: `
|
|
313
|
-
| Authenticated, no memberships | Safety Net: `ForbiddenException` on tenantId-schemas
|
|
312
|
+
| Not authenticated, no context | Safety Net: 401 `UnauthorizedException` on tenantId-schemas |
|
|
313
|
+
| Authenticated, no memberships | Safety Net: 403 `ForbiddenException` on tenantId-schemas |
|
|
314
314
|
| Authenticated, has memberships | `{ tenantId: { $in: [user's tenant IDs] } }` |
|
|
315
315
|
| Authenticated + hierarchy role | `{ tenantId: { $in: [qualified tenant IDs] } }` (filtered by level) |
|
|
316
316
|
| Admin without header | No filter (sees all data via `isAdminBypass`) |
|
|
@@ -442,7 +442,7 @@ For high-frequency endpoints that don't access tenant-scoped data, use `@SkipTen
|
|
|
442
442
|
|
|
443
443
|
## Security Notes
|
|
444
444
|
|
|
445
|
-
> **Defense-in-Depth:** The Mongoose tenant plugin uses `tenantId` from `RequestContext`, which is only set by `CoreTenantGuard` after successful membership validation. The raw `X-Tenant-Id` header is **never** used directly for filtering. Even if the guard is bypassed (e.g., via `@SkipTenantCheck()`), the plugin's Safety Net
|
|
445
|
+
> **Defense-in-Depth:** The Mongoose tenant plugin uses `tenantId` from `RequestContext`, which is only set by `CoreTenantGuard` after successful membership validation. The raw `X-Tenant-Id` header is **never** used directly for filtering. Even if the guard is bypassed (e.g., via `@SkipTenantCheck()`), the plugin's Safety Net refuses access to a tenantId-scoped schema without valid tenant context (401 when nobody is signed in, 403 otherwise).
|
|
446
446
|
|
|
447
447
|
> **Explicit tenantId on writes:** The plugin only auto-sets `tenantId` on new documents when no explicit value is provided. Service-layer code that accepts user-supplied `tenantId` as a creation parameter could allow cross-tenant writes. Never pass user-supplied `tenantId` directly to `create()` or `new Model()`.
|
|
448
448
|
|