@lenne.tech/nest-server 12.6.1 → 12.7.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 +9 -2
- package/.claude/rules/configurable-features.md +3 -2
- package/.claude/rules/testing.md +7 -5
- package/CLAUDE.md +4 -0
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/helpers/config.helper.js +26 -2
- package/dist/core/common/helpers/config.helper.js.map +1 -1
- package/dist/core/common/helpers/cookies.helper.js +0 -3
- package/dist/core/common/helpers/cookies.helper.js.map +1 -1
- package/dist/core/common/helpers/swagger-enabled.helper.d.ts +2 -0
- package/dist/core/common/helpers/swagger-enabled.helper.js +10 -0
- package/dist/core/common/helpers/swagger-enabled.helper.js.map +1 -0
- package/dist/core/common/helpers/swagger.helper.d.ts +1 -1
- package/dist/core/common/helpers/swagger.helper.js +10 -3
- package/dist/core/common/helpers/swagger.helper.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/modules/ai/core-ai.controller.d.ts +1 -1
- package/dist/core/modules/ai/core-ai.controller.js +13 -3
- package/dist/core/modules/ai/core-ai.controller.js.map +1 -1
- package/dist/core/modules/ai/core-ai.resolver.d.ts +1 -1
- package/dist/core/modules/ai/core-ai.resolver.js +8 -3
- package/dist/core/modules/ai/core-ai.resolver.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-prompt.service.d.ts +3 -1
- package/dist/core/modules/ai/services/core-ai-prompt.service.js +3 -2
- package/dist/core/modules/ai/services/core-ai-prompt.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +18 -0
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +24 -2
- package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +15 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +13 -5
- package/migration-guides/12.6.x-to-12.7.x.md +299 -0
- package/package.json +1 -1
- package/src/core/common/helpers/config.helper.ts +58 -2
- package/src/core/common/helpers/cookies.helper.ts +13 -10
- package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
- package/src/core/common/helpers/swagger.helper.ts +30 -6
- package/src/core/common/interfaces/server-options.interface.ts +26 -5
- package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +4 -1
- package/src/core/modules/ai/core-ai.controller.ts +18 -3
- package/src/core/modules/ai/core-ai.resolver.ts +14 -3
- package/src/core/modules/ai/services/core-ai-prompt.service.ts +11 -5
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +33 -0
- package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +41 -4
- package/src/core/modules/better-auth/core-better-auth.service.ts +27 -0
- package/src/core/modules/tus/README.md +2 -1
- package/src/index.ts +1 -0
- package/src/main.ts +3 -2
|
@@ -64,6 +64,60 @@ export function loadLocalConfigFile(
|
|
|
64
64
|
return loaded?.default ?? loaded;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** Whether the test-runner fallback for `NODE_ENV=test` has been reported in this module instance */
|
|
68
|
+
let testRunnerFallbackReported = false;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The block of `config` that `NODE_ENV` selects — or a refusal.
|
|
72
|
+
*
|
|
73
|
+
* Until 12.7.0 a `NODE_ENV` without a block (and an empty one, via `'' || 'local'`) got the `local` block, whose
|
|
74
|
+
* `env` then claimed `local` on a deployed stage: public dummy secrets, the anonymous system setup, `GET /config`,
|
|
75
|
+
* the SSRF guard's private targets and the development MCP OAuth secret, all opened by a typo or a missing block.
|
|
76
|
+
* Now:
|
|
77
|
+
*
|
|
78
|
+
* - `NODE_ENV` unset → `defaultEnv` (`local`), as before.
|
|
79
|
+
* - `NODE_ENV` empty or blank → refused. `NODE_ENV=${NODE_ENV}` in a compose file passes `''` when the host does not
|
|
80
|
+
* set the variable, and that must not read as "local".
|
|
81
|
+
* - `NODE_ENV` without a block → refused, naming the blocks that exist.
|
|
82
|
+
* - The one exception: `NODE_ENV=test` while a test runner is active (`VITEST` or `JEST_WORKER_ID`), because vitest
|
|
83
|
+
* sets that value and many repositories have no `test` block. It keeps the `local` block, with one warning.
|
|
84
|
+
*/
|
|
85
|
+
function selectEnvironmentBlock(
|
|
86
|
+
config: Record<string, any>,
|
|
87
|
+
defaultEnv: string,
|
|
88
|
+
// `any`, not `Record<string, any>`: it is what getEnvironmentConfig() returns, and a project spreading that result
|
|
89
|
+
// (`{ ...envConfig, auth }`) loses every other field under the narrower type — a type break in consumer code
|
|
90
|
+
): { env: string; envConfig: any } {
|
|
91
|
+
const requested = process.env['NODE_ENV'];
|
|
92
|
+
if (requested === undefined) {
|
|
93
|
+
return { env: defaultEnv, envConfig: config[defaultEnv] || config.local || {} };
|
|
94
|
+
}
|
|
95
|
+
const known = Object.keys(config).join(', ') || 'none';
|
|
96
|
+
if (requested.trim() === '') {
|
|
97
|
+
throw new Error(
|
|
98
|
+
`NODE_ENV is set but empty (known: ${known}). Set it to one of them, or unset it for local. ` +
|
|
99
|
+
'A compose file with NODE_ENV=${NODE_ENV} passes an empty value when the host does not set the variable.',
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
if (Object.hasOwn(config, requested) && config[requested]) {
|
|
103
|
+
return { env: requested, envConfig: config[requested] };
|
|
104
|
+
}
|
|
105
|
+
if (requested === 'test' && (process.env['VITEST'] || process.env['JEST_WORKER_ID'])) {
|
|
106
|
+
if (!testRunnerFallbackReported) {
|
|
107
|
+
testRunnerFallbackReported = true;
|
|
108
|
+
console.warn(
|
|
109
|
+
"NODE_ENV='test' has no block in the configuration; a test runner is active, so the local block is used. " +
|
|
110
|
+
'Add a test block to silence this.',
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return { env: requested, envConfig: config.local || {} };
|
|
114
|
+
}
|
|
115
|
+
throw new Error(
|
|
116
|
+
`NODE_ENV='${requested}' has no block in the configuration (known: ${known}). Add a block for it, or set NODE_ENV ` +
|
|
117
|
+
'to one of the known environments. Prefer the block: other libraries read NODE_ENV themselves.',
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
67
121
|
/**
|
|
68
122
|
* Get environment configuration (deeply merged into config object set via options)
|
|
69
123
|
*
|
|
@@ -71,6 +125,9 @@ export function loadLocalConfigFile(
|
|
|
71
125
|
* 1. config[env] (if set)
|
|
72
126
|
* 2.
|
|
73
127
|
*
|
|
128
|
+
* `NODE_ENV` must name a block of `config` (12.7.0): an empty value or one without a block throws, except
|
|
129
|
+
* `NODE_ENV=test` under a test runner — see `selectEnvironmentBlock()`.
|
|
130
|
+
*
|
|
74
131
|
* @param options options for processing
|
|
75
132
|
* @param options.config config object with different environments as main keys (see config.env.ts) to merge environment configurations into (default: {})
|
|
76
133
|
* @param options.defaultEnv default environment to use if no NODE_ENV is set (default: 'local')
|
|
@@ -92,8 +149,7 @@ export function getEnvironmentConfig(options: { config?: Record<string, any>; de
|
|
|
92
149
|
dotenv.config({ quiet: true });
|
|
93
150
|
}
|
|
94
151
|
|
|
95
|
-
const env =
|
|
96
|
-
const envConfig = config[env] || config.local || {};
|
|
152
|
+
const { env, envConfig } = selectEnvironmentBlock(config, defaultEnv);
|
|
97
153
|
|
|
98
154
|
// Merge with localConfig (e.g. config.json)
|
|
99
155
|
if (envConfig.loadLocalConfig) {
|
|
@@ -545,11 +545,18 @@ export function resolveServerUrls(input: {
|
|
|
545
545
|
*
|
|
546
546
|
* Resolution priority:
|
|
547
547
|
* 1. CORS disabled → empty object (no CORS)
|
|
548
|
-
* 2.
|
|
549
|
-
* 3. `cors.
|
|
550
|
-
* 4.
|
|
551
|
-
* 5.
|
|
552
|
-
*
|
|
548
|
+
* 2. `cors.allowAll` → `{ credentials: true, origin: true }` (mirror request origin)
|
|
549
|
+
* 3. `cors.allowedOrigins` + resolved `appUrl`/`baseUrl` → deduplicated origin list
|
|
550
|
+
* 4. Only resolved `appUrl`/`baseUrl` → those origins
|
|
551
|
+
* 5. Nothing configured → `{}` (no credentialed CORS — caller decides fallback)
|
|
552
|
+
*
|
|
553
|
+
* The same in JWT mode (`cookies: false`) since 12.7.0. Until then it answered `{}` there, and callers fell back to
|
|
554
|
+
* `enableCors()` without credentials (`Access-Control-Allow-Origin: *`). A browser refuses `*` on a credentialed
|
|
555
|
+
* request, and JWT mode still makes them: the stack's client sends `credentials: 'include'`, and after a second
|
|
556
|
+
* factor it turns the session cookie Better-Auth set into a JWT through `/iam/token` — so a split app/API deployment
|
|
557
|
+
* in JWT mode could not finish a 2FA sign-in. Credentialed CORS answers only the listed origins — the ones cookie
|
|
558
|
+
* mode already trusts; it lets them READ credentialed responses and grants nothing to any other origin (CORS
|
|
559
|
+
* decides who may read, not what a browser sends; cookie requests from other sites are bounded by `SameSite=Lax`).
|
|
553
560
|
*
|
|
554
561
|
* `appUrl`/`baseUrl` are resolved via {@link resolveServerUrls}, the same function BetterAuth
|
|
555
562
|
* uses, so all three CORS layers (GraphQL, REST, BetterAuth `trustedOrigins`) agree.
|
|
@@ -559,7 +566,7 @@ export function resolveServerUrls(input: {
|
|
|
559
566
|
* - `main.ts` reference implementation for REST (Express) CORS
|
|
560
567
|
*
|
|
561
568
|
* Security notes:
|
|
562
|
-
* - When no origins are resolvable
|
|
569
|
+
* - When no origins are resolvable, the function returns `{}` rather
|
|
563
570
|
* than `{ credentials: true, origin: true }`. Returning open CORS with credentials would
|
|
564
571
|
* allow any website to make credentialed requests. Callers should either configure
|
|
565
572
|
* `appUrl`/`baseUrl`/`allowedOrigins`, enable `cors.allowAll` explicitly (for development),
|
|
@@ -580,10 +587,6 @@ export function buildCorsConfig(options: Partial<IServerOptions>): Record<string
|
|
|
580
587
|
return {};
|
|
581
588
|
}
|
|
582
589
|
|
|
583
|
-
if (!isCookiesEnabled(options?.cookies)) {
|
|
584
|
-
return {};
|
|
585
|
-
}
|
|
586
|
-
|
|
587
590
|
const corsObj = typeof options?.cors === 'object' ? options.cors : {};
|
|
588
591
|
|
|
589
592
|
// allowAll → mirror request origin (explicit opt-in for dev/test)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { IServerOptions } from '../interfaces/server-options.interface.js';
|
|
2
|
+
import { ConfigService } from '../services/config.service.js';
|
|
3
|
+
import { isLocalEnv } from './cookies.helper.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Whether `setupSwagger()` serves the API documentation (`swagger`, 12.7.0+).
|
|
7
|
+
*
|
|
8
|
+
* | `swagger` | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
|
|
9
|
+
* |-----------|------------------------|---------------------------------------------------------------|
|
|
10
|
+
* | not set | served | **off** — none of the four paths is mounted |
|
|
11
|
+
* | `true` | served | served |
|
|
12
|
+
* | `false` | off | off |
|
|
13
|
+
*
|
|
14
|
+
* Off means nothing is mounted: neither the UI (`/swagger`, `/swagger-api-tokens`) nor the JSON documents
|
|
15
|
+
* (`/api-docs-json`, `/api-docs-api-tokens-json`), so they answer 404 like any unknown route. Before 12.7.0 every
|
|
16
|
+
* project that called `setupSwagger()` published the full API description on every stage, production included.
|
|
17
|
+
*
|
|
18
|
+
* A value that is not a boolean (the string `'true'` from `NEST_SERVER_CONFIG`) counts as not set, so a string
|
|
19
|
+
* cannot switch the documentation on by truthiness; `NSC__SWAGGER=true` arrives as a boolean. The environment is the
|
|
20
|
+
* configured `env`, else `NODE_ENV`, compared with `isLocalEnv()`.
|
|
21
|
+
*
|
|
22
|
+
* @param config - defaults to the running configuration
|
|
23
|
+
* @since 12.7.0
|
|
24
|
+
*/
|
|
25
|
+
export function isSwaggerEnabled(
|
|
26
|
+
config: Partial<IServerOptions> | undefined = ConfigService.configFastButReadOnly,
|
|
27
|
+
): boolean {
|
|
28
|
+
const setting = config?.swagger;
|
|
29
|
+
if (setting === true || setting === false) {
|
|
30
|
+
return setting;
|
|
31
|
+
}
|
|
32
|
+
return isLocalEnv(config?.env ?? process.env.NODE_ENV);
|
|
33
|
+
}
|
|
@@ -30,6 +30,7 @@ import { mergeRolesMetadata } from '../../modules/tenant/core-tenant.helpers.js'
|
|
|
30
30
|
import { RoleEnum } from '../enums/role.enum.js';
|
|
31
31
|
import { ConfigService } from '../services/config.service.js';
|
|
32
32
|
import { isCookiesEnabled } from './cookies.helper.js';
|
|
33
|
+
import { isSwaggerEnabled } from './swagger-enabled.helper.js';
|
|
33
34
|
|
|
34
35
|
import type { INestApplication, Type } from '@nestjs/common';
|
|
35
36
|
import type {
|
|
@@ -154,10 +155,28 @@ const logger = new Logger('Swagger');
|
|
|
154
155
|
/**
|
|
155
156
|
* Build the enriched document and serve it — plus the API-token view, when configured. Both documents are
|
|
156
157
|
* built on the first request, when every module is initialised.
|
|
158
|
+
*
|
|
159
|
+
* Since 12.7.0 only where `swagger` switches it on ({@link isSwaggerEnabled}): by default in `local`, `ci` and `e2e`,
|
|
160
|
+
* everywhere with `swagger: true`. Otherwise nothing is mounted — no UI, no JSON document — and one line in the log
|
|
161
|
+
* says so.
|
|
162
|
+
*
|
|
163
|
+
* @param config - server configuration; the running configuration by default
|
|
157
164
|
*/
|
|
158
|
-
export function setupSwagger(
|
|
165
|
+
export function setupSwagger(
|
|
166
|
+
app: INestApplication,
|
|
167
|
+
options: ISwaggerSetupOptions,
|
|
168
|
+
config: Partial<IServerOptions> = ConfigService.configFastButReadOnly ?? {},
|
|
169
|
+
): void {
|
|
170
|
+
if (!isSwaggerEnabled(config)) {
|
|
171
|
+
logger.log(
|
|
172
|
+
`Swagger is off in this environment (${config.env ?? process.env.NODE_ENV ?? 'unknown'}): nothing is served at ` +
|
|
173
|
+
`/${options.path ?? 'swagger'} or ${options.jsonDocumentUrl ?? '/api-docs-json'}. Set \`swagger: true\` ` +
|
|
174
|
+
`(NSC__SWAGGER=true) to serve the API documentation here.`,
|
|
175
|
+
);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
159
178
|
let document: OpenAPIObject | undefined;
|
|
160
|
-
const fullDocument = () => (document ??= buildSwaggerDocument(app, options));
|
|
179
|
+
const fullDocument = () => (document ??= buildSwaggerDocument(app, options, config));
|
|
161
180
|
|
|
162
181
|
SwaggerModule.setup(options.path ?? 'swagger', app, fullDocument, {
|
|
163
182
|
...options.customOptions,
|
|
@@ -169,10 +188,15 @@ export function setupSwagger(app: INestApplication, options: ISwaggerSetupOption
|
|
|
169
188
|
return;
|
|
170
189
|
}
|
|
171
190
|
let viewDocument: OpenAPIObject | undefined;
|
|
172
|
-
SwaggerModule.setup(
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
191
|
+
SwaggerModule.setup(
|
|
192
|
+
view.path,
|
|
193
|
+
app,
|
|
194
|
+
() => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view, config)),
|
|
195
|
+
{
|
|
196
|
+
...options.customOptions,
|
|
197
|
+
jsonDocumentUrl: view.jsonDocumentUrl,
|
|
198
|
+
},
|
|
199
|
+
);
|
|
176
200
|
}
|
|
177
201
|
|
|
178
202
|
/**
|
|
@@ -1698,9 +1698,11 @@ export interface IApiTokens {
|
|
|
1698
1698
|
*
|
|
1699
1699
|
* When cookies are enabled, the server:
|
|
1700
1700
|
* - Loads `cookie-parser` middleware
|
|
1701
|
-
* - Sets `credentials: true` in CORS configuration
|
|
1702
1701
|
* - Sets signed httpOnly session cookies on authentication responses
|
|
1703
1702
|
*
|
|
1703
|
+
* CORS answers the resolved origins with `credentials: true` in BOTH modes since 12.7.0 (`buildCorsConfig()`);
|
|
1704
|
+
* until then JWT mode got `*` without credentials.
|
|
1705
|
+
*
|
|
1704
1706
|
* JWT authentication via `Authorization: Bearer` header works independently
|
|
1705
1707
|
* of the cookie configuration — it is always available regardless of this setting.
|
|
1706
1708
|
*
|
|
@@ -1741,8 +1743,8 @@ export interface ICookiesConfig {
|
|
|
1741
1743
|
* - `{ allowedOrigins: [...] }`: Additional origins beyond `appUrl`/`baseUrl`
|
|
1742
1744
|
* - `{ allowAll: true }`: Allow all origins (mirrors request origin — NOT recommended for production)
|
|
1743
1745
|
*
|
|
1744
|
-
*
|
|
1745
|
-
* Browsers reject `Access-Control-Allow-Origin: *` with credentials, so origins must
|
|
1746
|
+
* CORS includes `credentials: true` for the resolved origins — with cookies and, since 12.7.0, in JWT mode
|
|
1747
|
+
* (`cookies: false`) too. Browsers reject `Access-Control-Allow-Origin: *` with credentials, so origins must
|
|
1746
1748
|
* be explicitly listed or `allowAll` must be set (which mirrors the request origin).
|
|
1747
1749
|
*
|
|
1748
1750
|
* @default undefined (enabled, origins auto-derived from appUrl/baseUrl)
|
|
@@ -3621,6 +3623,25 @@ export interface IServerOptions {
|
|
|
3621
3623
|
*/
|
|
3622
3624
|
sync?: boolean | ISync;
|
|
3623
3625
|
|
|
3626
|
+
/**
|
|
3627
|
+
* Whether `setupSwagger()` serves the API documentation (12.7.0+), decided by `isSwaggerEnabled()`.
|
|
3628
|
+
*
|
|
3629
|
+
* | Value | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
|
|
3630
|
+
* |-------|------------------------|---------------------------------------------------------------|
|
|
3631
|
+
* | not set | served | **off** |
|
|
3632
|
+
* | `true` | served | served |
|
|
3633
|
+
* | `false` | off | off |
|
|
3634
|
+
*
|
|
3635
|
+
* Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and
|
|
3636
|
+
* `/api-docs-api-tokens-json` (or the paths `setupSwagger()` was given) — they answer 404. Before 12.7.0 every
|
|
3637
|
+
* project that called `setupSwagger()` published its full API description on every stage. A value that is not a
|
|
3638
|
+
* boolean counts as not set. Environment variable: `NSC__SWAGGER=true`.
|
|
3639
|
+
*
|
|
3640
|
+
* @default undefined (served only in `local`, `ci` and `e2e`)
|
|
3641
|
+
* @since 12.7.0
|
|
3642
|
+
*/
|
|
3643
|
+
swagger?: boolean;
|
|
3644
|
+
|
|
3624
3645
|
/**
|
|
3625
3646
|
* System setup configuration for initial admin creation.
|
|
3626
3647
|
*
|
|
@@ -4186,8 +4207,8 @@ export interface ITusConfig {
|
|
|
4186
4207
|
*
|
|
4187
4208
|
* Unset, they come from the API's own CORS configuration — `buildCorsConfig()`, the function REST,
|
|
4188
4209
|
* GraphQL and Better-Auth share (`appUrl`, `baseUrl`, `cors.allowedOrigins`, `cors.allowAll`).
|
|
4189
|
-
* Without credentialed CORS configured (
|
|
4190
|
-
*
|
|
4210
|
+
* Without credentialed CORS configured (no origin resolvable) the tus server keeps its own default,
|
|
4211
|
+
* `*`. Since 12.7.0 JWT mode (`cookies: false`) gets the origin list too.
|
|
4191
4212
|
*
|
|
4192
4213
|
* The wildcard is what broke browser uploads with cookie authentication and separate app/API
|
|
4193
4214
|
* origins before 11.42.1: a credentialed response with `Access-Control-Allow-Origin: *` is refused
|
|
@@ -161,7 +161,10 @@ ai: {
|
|
|
161
161
|
permissions.
|
|
162
162
|
- **User prompts ("Vorlagen"):** users author re-usable short prompts for themselves
|
|
163
163
|
(private) or their tenant (public) via `aiPrompts` (`/ai/prompts`, `useLtAiPrompts`).
|
|
164
|
-
Inserted into the chat input by a picker.
|
|
164
|
+
Inserted into the chat input by a picker. The list answers ENABLED prompts only — what the
|
|
165
|
+
picker offers; a management screen asks `GET /ai/prompts?includeDisabled=true` (GraphQL
|
|
166
|
+
`findAiPrompts(includeDisabled: true)`, 12.7.0), or a prompt saved with "enabled" off
|
|
167
|
+
disappears from it.
|
|
165
168
|
- **Placeholders:** `{{placeholder}}` tokens in both system slots AND user prompts are
|
|
166
169
|
resolved at run time by `CoreAiPlaceholderRegistry`. The current list is served via
|
|
167
170
|
`GET /ai/placeholders` (`useLtAiPlaceholders`) — your slot/prompt editors should render
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Body, Controller, Delete, Get, Inject, Optional, Param, Post, Put, Query, Res } from '@nestjs/common';
|
|
2
|
+
import { ApiQuery } from '@nestjs/swagger';
|
|
2
3
|
import type { Response } from 'express';
|
|
3
4
|
|
|
4
5
|
import { RESTServiceOptions } from '../../common/decorators/rest-service-options.decorator.js';
|
|
@@ -580,11 +581,25 @@ export class CoreAiController {
|
|
|
580
581
|
// User-facing user prompts ("Vorlagen") — own / tenant / global
|
|
581
582
|
// ===================================================================================================================
|
|
582
583
|
|
|
583
|
-
/**
|
|
584
|
+
/**
|
|
585
|
+
* List user prompts visible to the current user (own + tenant + global). Enabled ones only — what the chat offers;
|
|
586
|
+
* `?includeDisabled=true` lists disabled ones too, for the management screen (12.7.0).
|
|
587
|
+
*/
|
|
584
588
|
@Get('prompts')
|
|
585
589
|
@Roles(RoleEnum.S_USER)
|
|
586
|
-
|
|
587
|
-
|
|
590
|
+
@ApiQuery({
|
|
591
|
+
description: 'Also list disabled prompts (for managing them); default: enabled prompts only',
|
|
592
|
+
name: 'includeDisabled',
|
|
593
|
+
required: false,
|
|
594
|
+
type: Boolean,
|
|
595
|
+
})
|
|
596
|
+
async findPrompts(
|
|
597
|
+
@RESTServiceOptions() serviceOptions: ServiceOptions,
|
|
598
|
+
@Query('includeDisabled') includeDisabled?: string,
|
|
599
|
+
): Promise<CoreAiPrompt[]> {
|
|
600
|
+
return this.promptService.listVisible(serviceOptions, {
|
|
601
|
+
includeDisabled: includeDisabled === 'true' || includeDisabled === '1',
|
|
602
|
+
});
|
|
588
603
|
}
|
|
589
604
|
|
|
590
605
|
/** Create a user prompt for the current user / tenant (global requires admin). */
|
|
@@ -527,11 +527,22 @@ export class CoreAiResolver {
|
|
|
527
527
|
// User-facing user prompts ("Vorlagen") — own / tenant / global
|
|
528
528
|
// ===================================================================================================================
|
|
529
529
|
|
|
530
|
-
/**
|
|
530
|
+
/**
|
|
531
|
+
* List user prompts visible to the current user (own + tenant + global). Enabled ones only — what the chat offers;
|
|
532
|
+
* `includeDisabled: true` lists disabled ones too, for the management screen (12.7.0).
|
|
533
|
+
*/
|
|
531
534
|
@Query(() => [CoreAiPrompt], { description: 'List AI user prompts visible to the current user' })
|
|
532
535
|
@Roles(RoleEnum.S_USER)
|
|
533
|
-
async findAiPrompts(
|
|
534
|
-
|
|
536
|
+
async findAiPrompts(
|
|
537
|
+
@GraphQLServiceOptions() serviceOptions: ServiceOptions,
|
|
538
|
+
@Args('includeDisabled', {
|
|
539
|
+
description: 'Also list disabled prompts (for managing them); default: enabled prompts only',
|
|
540
|
+
nullable: true,
|
|
541
|
+
type: () => Boolean,
|
|
542
|
+
})
|
|
543
|
+
includeDisabled?: boolean,
|
|
544
|
+
): Promise<CoreAiPrompt[]> {
|
|
545
|
+
return this.promptService.listVisible(serviceOptions, { includeDisabled: includeDisabled === true });
|
|
535
546
|
}
|
|
536
547
|
|
|
537
548
|
/** Create a user prompt for the current user / tenant (global requires admin). */
|
|
@@ -123,8 +123,15 @@ export class CoreAiPromptService extends CrudService<CoreAiPrompt, CoreAiPromptC
|
|
|
123
123
|
/**
|
|
124
124
|
* List prompts visible to the current user: own + tenant prompts of the
|
|
125
125
|
* user's tenant. Ordered by `order` asc then `name`.
|
|
126
|
+
*
|
|
127
|
+
* Only enabled prompts by default — what the chat offers. `includeDisabled: true` (12.7.0) lists disabled ones too,
|
|
128
|
+
* for the management screen: without it a prompt saved with "enabled" switched off disappeared from the list and
|
|
129
|
+
* could no longer be edited or deleted. Visibility is the same either way.
|
|
126
130
|
*/
|
|
127
|
-
async listVisible(
|
|
131
|
+
async listVisible(
|
|
132
|
+
serviceOptions: ServiceOptions = {},
|
|
133
|
+
options: { includeDisabled?: boolean } = {},
|
|
134
|
+
): Promise<CoreAiPrompt[]> {
|
|
128
135
|
const user = serviceOptions?.currentUser;
|
|
129
136
|
if (!user?.id) {
|
|
130
137
|
return [];
|
|
@@ -135,10 +142,9 @@ export class CoreAiPromptService extends CrudService<CoreAiPrompt, CoreAiPromptC
|
|
|
135
142
|
or.push({ scope: 'tenant', tenantId: String(tenantId) });
|
|
136
143
|
}
|
|
137
144
|
try {
|
|
138
|
-
const
|
|
139
|
-
{ $or: or, enabled: { $ne: false } }
|
|
140
|
-
|
|
141
|
-
)) as CoreAiPrompt[];
|
|
145
|
+
const filter: Record<string, unknown> =
|
|
146
|
+
options.includeDisabled === true ? { $or: or } : { $or: or, enabled: { $ne: false } };
|
|
147
|
+
const rows = (await this.dataStore.find(filter, { sort: { order: 1, name: 1 } })) as CoreAiPrompt[];
|
|
142
148
|
return rows || [];
|
|
143
149
|
} catch (err) {
|
|
144
150
|
this.logger.warn(`Failed to list prompts: ${(err as Error).message}`);
|
|
@@ -161,6 +161,37 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
|
|
|
161
161
|
return normalized;
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
/**
|
|
165
|
+
* `POST /revoke-session` with `{ sessionId }` (12.7.0): `list-sessions` hands out session ids and no tokens, so a
|
|
166
|
+
* client names the session to end by its id. Better-Auth's route takes `{ token }` only; this looks the token up among
|
|
167
|
+
* the sessions of the signed-in user ({@link CoreBetterAuthService.sessionTokenOfUser}) and puts it into the body.
|
|
168
|
+
*
|
|
169
|
+
* An id that is unknown or belongs to another user becomes an empty token: Better-Auth then revokes nothing and
|
|
170
|
+
* answers as it does for a foreign token, so the answer says nothing about other users' sessions. A body that
|
|
171
|
+
* already carries a `token` is left as it is (revoking by token keeps working).
|
|
172
|
+
*/
|
|
173
|
+
protected async resolveRevokeSessionId(req: Request, relativePath: string): Promise<void> {
|
|
174
|
+
if (req.method !== 'POST' || normalizeIamRoutePath(relativePath) !== '/revoke-session') {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const body = req.body as Record<string, unknown> | undefined;
|
|
178
|
+
const sessionId = body?.sessionId;
|
|
179
|
+
if (!body || typeof sessionId !== 'string' || !sessionId || (typeof body.token === 'string' && body.token)) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const caller = req as unknown as {
|
|
183
|
+
betterAuthSession?: { user?: { id?: unknown } };
|
|
184
|
+
betterAuthUser?: { id?: unknown };
|
|
185
|
+
};
|
|
186
|
+
const userId = caller.betterAuthSession?.user?.id ?? caller.betterAuthUser?.id;
|
|
187
|
+
const token =
|
|
188
|
+
typeof userId === 'string' && userId
|
|
189
|
+
? await this.betterAuthService.sessionTokenOfUser(userId, sessionId)
|
|
190
|
+
: undefined;
|
|
191
|
+
const { sessionId: _sessionId, ...rest } = body;
|
|
192
|
+
req.body = { ...rest, token: token ?? '' };
|
|
193
|
+
}
|
|
194
|
+
|
|
164
195
|
/**
|
|
165
196
|
* Brings every other password a native route carries (see {@link PASSWORD_FIELD_PATHS}) to the shape the
|
|
166
197
|
* stored credential was written in. Matched like {@link normalizeResetPassword}: exact, after trimming a
|
|
@@ -365,6 +396,8 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
|
|
|
365
396
|
const resetPassword = this.normalizeResetPassword(req, relativePath);
|
|
366
397
|
// …and every password a non-reset native route carries (2FA, change-password, delete-user, …).
|
|
367
398
|
this.normalizeNativePasswords(req, relativePath);
|
|
399
|
+
// `list-sessions` hands out ids, no tokens: revoke-session takes the id (12.7.0)
|
|
400
|
+
await this.resolveRevokeSessionId(req, relativePath);
|
|
368
401
|
|
|
369
402
|
// Convert Express request to Web Standard Request with proper cookie signing
|
|
370
403
|
const webRequest = await toWebRequest(req, {
|
|
@@ -65,8 +65,11 @@ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieN
|
|
|
65
65
|
* - Token in body: the session token becomes {@link SessionTokenPresentation.resolveJwt}'s answer; `session.token`
|
|
66
66
|
* leaves the body as in sign-in (`mapSession()`). A response that created a session without a top-level token
|
|
67
67
|
* (passkey verify answers `{ session }`) gains one.
|
|
68
|
-
* -
|
|
69
|
-
* `
|
|
68
|
+
* - Session records (an object with a `token`, a `userId` and an `expiresAt`) lose their `token` in every mode, also
|
|
69
|
+
* inside an array: `list-sessions` answered every session of the user with its token (12.7.0). The client revokes a
|
|
70
|
+
* session by its `id` instead (`POST /revoke-session` with `{ sessionId }`).
|
|
71
|
+
* - Untouched: error responses, non-JSON bodies, a JWT (`/token` hands one out on purpose), and a top-level `token`
|
|
72
|
+
* that is not the session token (another plugin's value).
|
|
70
73
|
*
|
|
71
74
|
* Returns the response itself when nothing changes, otherwise a new one with the same status and headers.
|
|
72
75
|
*/
|
|
@@ -83,9 +86,20 @@ export async function presentSessionTokens(
|
|
|
83
86
|
} catch {
|
|
84
87
|
return response;
|
|
85
88
|
}
|
|
86
|
-
if (!body || typeof body !== 'object'
|
|
89
|
+
if (!body || typeof body !== 'object') {
|
|
87
90
|
return response;
|
|
88
91
|
}
|
|
92
|
+
if (Array.isArray(body)) {
|
|
93
|
+
return body.some(isSessionRecord)
|
|
94
|
+
? rebuildResponse(
|
|
95
|
+
response,
|
|
96
|
+
body.map((item) => (isSessionRecord(item) ? withoutToken(item) : item)),
|
|
97
|
+
)
|
|
98
|
+
: response;
|
|
99
|
+
}
|
|
100
|
+
if (isSessionRecord(body)) {
|
|
101
|
+
return rebuildResponse(response, withoutToken(body));
|
|
102
|
+
}
|
|
89
103
|
|
|
90
104
|
const record = body as Record<string, unknown>;
|
|
91
105
|
const session =
|
|
@@ -129,6 +143,29 @@ export async function presentSessionTokens(
|
|
|
129
143
|
}
|
|
130
144
|
}
|
|
131
145
|
|
|
146
|
+
return rebuildResponse(response, next);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A session as Better-Auth outputs it (`parseSessionOutput()`): its `token` is the bearer credential of that session,
|
|
151
|
+
* so it never belongs in a body — the `id` identifies the session to the client.
|
|
152
|
+
*/
|
|
153
|
+
function isSessionRecord(value: unknown): value is Record<string, unknown> {
|
|
154
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
const record = value as Record<string, unknown>;
|
|
158
|
+
return typeof record.token === 'string' && !!record.token && 'userId' in record && 'expiresAt' in record;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The record without its `token` */
|
|
162
|
+
function withoutToken(record: Record<string, unknown>): Record<string, unknown> {
|
|
163
|
+
const { token: _token, ...rest } = record;
|
|
164
|
+
return rest;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The same response with another JSON body: status and headers kept, every `Set-Cookie` re-appended */
|
|
168
|
+
function rebuildResponse(response: globalThis.Response, body: unknown): globalThis.Response {
|
|
132
169
|
const headers = new Headers();
|
|
133
170
|
response.headers.forEach((value, key) => {
|
|
134
171
|
if (key.toLowerCase() !== 'content-length' && key.toLowerCase() !== 'set-cookie') {
|
|
@@ -138,7 +175,7 @@ export async function presentSessionTokens(
|
|
|
138
175
|
for (const cookie of response.headers.getSetCookie?.() ?? []) {
|
|
139
176
|
headers.append('set-cookie', cookie);
|
|
140
177
|
}
|
|
141
|
-
return new Response(JSON.stringify(
|
|
178
|
+
return new Response(JSON.stringify(body), { headers, status: response.status, statusText: response.statusText });
|
|
142
179
|
}
|
|
143
180
|
|
|
144
181
|
/** Asks {@link SessionTokenPresentation.isSessionToken}; a lookup that fails cannot vouch for anything */
|
|
@@ -1071,6 +1071,33 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1071
1071
|
}
|
|
1072
1072
|
}
|
|
1073
1073
|
|
|
1074
|
+
/**
|
|
1075
|
+
* The token of the session `sessionId` — only when that session belongs to `userId` (12.7.0).
|
|
1076
|
+
*
|
|
1077
|
+
* `list-sessions` hands out session ids, no tokens, so a client revokes a session by its id; the API middleware asks
|
|
1078
|
+
* this to turn `POST /revoke-session { sessionId }` into the `{ token }` Better-Auth expects. Asked through
|
|
1079
|
+
* Better-Auth's own adapter (`internalAdapter.listSessions()`), so it reads wherever Better-Auth keeps its sessions.
|
|
1080
|
+
*
|
|
1081
|
+
* @returns the token, or `undefined` for an unknown id, a session of another user, or a failed lookup
|
|
1082
|
+
*/
|
|
1083
|
+
async sessionTokenOfUser(userId: string, sessionId: string): Promise<string | undefined> {
|
|
1084
|
+
if (!userId || !sessionId) {
|
|
1085
|
+
return undefined;
|
|
1086
|
+
}
|
|
1087
|
+
try {
|
|
1088
|
+
const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
|
|
1089
|
+
const sessions: unknown = await context?.internalAdapter?.listSessions?.(userId);
|
|
1090
|
+
const match = (Array.isArray(sessions) ? sessions : []).find(
|
|
1091
|
+
(session: { id?: unknown; userId?: unknown }) =>
|
|
1092
|
+
String(session?.id) === sessionId && String(session?.userId) === String(userId),
|
|
1093
|
+
);
|
|
1094
|
+
return typeof match?.token === 'string' && match.token ? match.token : undefined;
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
this.logger.debug(`sessionTokenOfUser error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
1097
|
+
return undefined;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1074
1101
|
/**
|
|
1075
1102
|
* Revokes a specific session (logout for that session)
|
|
1076
1103
|
*
|
|
@@ -119,7 +119,8 @@ authentication and separate app and API origins the request is credentialed, and
|
|
|
119
119
|
refuses `*` there — uploads failed in the browser although the server answered 201. The origins now
|
|
120
120
|
come from `buildCorsConfig()` (`appUrl`, `baseUrl`, `cors.allowedOrigins`, `cors.allowAll`), the same
|
|
121
121
|
decision REST, GraphQL and Better-Auth make; `tus.allowedOrigins` overrides. Without credentialed CORS
|
|
122
|
-
(
|
|
122
|
+
(no origin resolvable) the tus default `*` stays. Since 12.7.0 JWT mode (`cookies: false`) gets the origin list as
|
|
123
|
+
well.
|
|
123
124
|
|
|
124
125
|
The preflight (`OPTIONS`) is answered by Nest's CORS layer and was never affected — test an
|
|
125
126
|
**authenticated** request with an `Origin` header when checking this.
|
package/src/index.ts
CHANGED
|
@@ -57,6 +57,7 @@ export * from './core/common/helpers/redact-secrets.helper.js';
|
|
|
57
57
|
export * from './core/common/helpers/register-enum.helper.js';
|
|
58
58
|
export * from './core/common/helpers/scim.helper.js';
|
|
59
59
|
export * from './core/common/helpers/service.helper.js';
|
|
60
|
+
export * from './core/common/helpers/swagger-enabled.helper.js';
|
|
60
61
|
export * from './core/common/helpers/swagger.helper.js';
|
|
61
62
|
export * from './core/common/helpers/table.helper.js';
|
|
62
63
|
export * from './core/common/inputs/combined-filter.input.js';
|
package/src/main.ts
CHANGED
|
@@ -84,8 +84,9 @@ async function bootstrap() {
|
|
|
84
84
|
// Three cases:
|
|
85
85
|
// 1. CORS explicitly disabled (`cors: false` or `cors.enabled: false`) → skip `enableCors()`
|
|
86
86
|
// entirely. No CORS headers emitted. Same-origin requests still work.
|
|
87
|
-
// 2. Origins resolvable (appUrl/baseUrl/allowedOrigins or allowAll) → use the computed options
|
|
88
|
-
//
|
|
87
|
+
// 2. Origins resolvable (appUrl/baseUrl/allowedOrigins or allowAll) → use the computed options,
|
|
88
|
+
// with credentials — in JWT mode (`cookies: false`) too since 12.7.0.
|
|
89
|
+
// 3. Cookies disabled and no origin resolvable → permissive `enableCors()` without credentials.
|
|
89
90
|
if (isCorsDisabled(envConfig.cors)) {
|
|
90
91
|
// Case 1 — CORS explicitly disabled. Do nothing.
|
|
91
92
|
} else {
|