@lenne.tech/nest-server 12.8.5 → 12.8.7

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.
Files changed (35) hide show
  1. package/.claude/rules/architecture.md +1 -0
  2. package/.claude/rules/configurable-features.md +2 -1
  3. package/.claude/rules/testing.md +3 -3
  4. package/CLAUDE.md +4 -0
  5. package/FRAMEWORK-API.md +1 -1
  6. package/bin/check-unified-field-types.js +615 -0
  7. package/dist/core/common/decorators/unified-field.decorator.js +36 -1
  8. package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
  9. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  10. package/dist/core/modules/ai/core-ai-mcp.controller.d.ts +1 -0
  11. package/dist/core/modules/ai/core-ai-mcp.controller.js +11 -0
  12. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  13. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.d.ts +33 -0
  14. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js +74 -9
  15. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js.map +1 -1
  16. package/dist/core/modules/ai/index.d.ts +2 -2
  17. package/dist/core/modules/ai/index.js +1 -1
  18. package/dist/core/modules/ai/index.js.map +1 -1
  19. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +17 -1
  20. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +124 -8
  21. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  22. package/docs/REQUEST-LIFECYCLE.md +9 -1
  23. package/migration-guides/11.43.x-to-12.0.x.md +22 -2
  24. package/migration-guides/12.0.x-to-12.1.x.md +6 -0
  25. package/migration-guides/12.8.5-to-12.8.6.md +144 -0
  26. package/migration-guides/12.8.6-to-12.8.7.md +112 -0
  27. package/package.json +20 -18
  28. package/src/core/common/decorators/unified-field.decorator.ts +63 -1
  29. package/src/core/common/interfaces/server-options.interface.ts +18 -0
  30. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +8 -0
  31. package/src/core/modules/ai/README.md +66 -0
  32. package/src/core/modules/ai/core-ai-mcp.controller.ts +17 -0
  33. package/src/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.ts +150 -11
  34. package/src/core/modules/ai/index.ts +5 -1
  35. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +222 -8
@@ -0,0 +1,112 @@
1
+ # Migration Guide: 12.8.6 → 12.8.7
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None. The deployed behaviour does not change |
8
+ | **New Features** | `@UnifiedField` warns at start for a field whose type the SWC dev start and the tsc build read differently; the package bin `nest-check-unified-field-types` finds those fields and with `--fix` writes the declared type (§1, §2) |
9
+ | **Bugfixes** | Under the SWC dev start an enum field took the enum object as its type — `@UnifiedField({ enum: Status, mongoose: true })` crashed the schema build; it is now read as `String` / `Number` like in the tsc build (§1). Documentation: §14 of the 12.0 guide no longer claims the TypeScript loader matches the tsc build for decorator metadata. The 12.1 guide names the pnpm 10 deploy effect of the `typeorm` devDependency |
10
+ | **Migration Effort** | Recommended: run `nest-check-unified-field-types --fix` once and add it to `check` / `check:fix` (§2). A later minor release refuses such fields at boot |
11
+
12
+ ## Quick Migration
13
+
14
+ ```bash
15
+ pnpm add @lenne.tech/nest-server@12.8.7
16
+ pnpm run update # nest-server-starter based projects
17
+ pnpm exec nest-check-unified-field-types --fix # npm mode; vendor mode: §2
18
+ pnpm run format
19
+ pnpm run build
20
+ pnpm test
21
+ ```
22
+
23
+ ## 1. The dev start and the build can read a field's type differently
24
+
25
+ Without `type`, `@UnifiedField` takes a field's type from the `design:type` metadata the compiler writes. The tsc
26
+ build writes it with the type checker. The TypeScript loader of the dev start (`ts-compiler.js`, SWC) writes it per
27
+ file, without type information:
28
+
29
+ | Field | SWC (dev start) | tsc (build, `strict: false`) |
30
+ |---|---|---|
31
+ | `max?: null \| number`, `count?: number \| undefined` | `Object` | `Number` |
32
+ | `kind?: Kind` (a type alias, local or imported) | `Object` | `String` / `Number` |
33
+ | `status?: Status` (an enum) | the enum object — read as `String` / `Number` since 12.8.7 | `String` / `Number` |
34
+ | `status?: Status \| null` | `Object` | `String` / `Number` |
35
+ | `flag?: boolean \| null` | `Object` | `Boolean` |
36
+ | `state?: 'ok' \| 'error'` (written in place), `number`, `string`, `boolean`, `Date`, a class imported as a value | same as tsc | |
37
+ | `meta?: Record<string, unknown>`, an interface, `string \| number` | `Object` | `Object` |
38
+
39
+ `Object` makes `@UnifiedField` validate the field as a nested object. In the dev API `max: 5` is refused, Swagger
40
+ documents the field as `type: object` and the generated app client types it `{ [key: string]: unknown }` — while the
41
+ deployed build accepts `max: 5`. Projects in strict mode (`strictNullChecks`) get `Object` for `null | number` from
42
+ tsc too, so there the deployed API refuses it as well.
43
+
44
+ **What is new:**
45
+
46
+ - `@UnifiedField` reads the enum object SWC writes for an enum field as `String` / `Number`, like the tsc build. Until
47
+ 12.8.6 it became the field's type: the Mongoose path type of `@UnifiedField({ enum: Status, mongoose: true })`, which
48
+ `SchemaFactory` refused — the dev start crashed while the build booted.
49
+ - `@UnifiedField` warns once per field at start when the type comes only from metadata that says `Object` and neither
50
+ `type`, `isAny` nor `enum` is set:
51
+ `[@UnifiedField] "InputRequestCreateInput.max" has no explicit type, and the compiler metadata says only "Object". …`
52
+ - The package bin `nest-check-unified-field-types` (file `bin/check-unified-field-types.js`) uses the project's
53
+ TypeScript type checker to find every such field. With `--fix` it writes the type the field declares —
54
+ `type: () => Number`, `String`, `Boolean`, `Date` or the class, referenced the way the file imports it. Without
55
+ `strictNullChecks` that is the type the tsc build already uses, so the deployed behaviour stays as it is and the dev
56
+ start matches it. **With `strictNullChecks`** the tsc build writes `Object` for a union with `null` / `undefined`
57
+ too: the check marks such a field `[changes the deployed build]`, because the written type changes how the deployed
58
+ API validates it (as the declared type instead of as an object) — review those fields. Fields without a runtime class (an interface, a `Record`, a mixed union, `any`, a class imported
59
+ only as a type) are reported with what to declare: `type: () => Object` for a free-form object, `isAny: true` for
60
+ any value, or a class for a nested structure.
61
+
62
+ ```typescript
63
+ // Before: the dev start reads Object, the build reads Number
64
+ @UnifiedField({ description: 'Upper limit', isOptional: true })
65
+ max?: null | number;
66
+
67
+ // After `nest-check-unified-field-types --fix`
68
+ @UnifiedField({ description: 'Upper limit', isOptional: true, type: () => Number })
69
+ max?: null | number;
70
+ ```
71
+
72
+ ## 2. Running the check
73
+
74
+ | Mode | Command |
75
+ |---|---|
76
+ | npm mode | `nest-check-unified-field-types` (package bin, e.g. `pnpm exec nest-check-unified-field-types --fix`) |
77
+ | vendor mode | `node ./bin/check-unified-field-types.js` once the lt CLI copies the file next to `bin/migrate.js`; until then a one-off `npx -p @lenne.tech/nest-server@12.8.7 nest-check-unified-field-types --fix` in the API project |
78
+
79
+ Options: `--fix` writes the types, `--project <tsconfig>` (default `tsconfig.json`), `--include <dir>` (default `src`,
80
+ repeatable). Exit code 1 when fields remain (with `--fix`: the ones it cannot fix), 2 on a usage error. Spec and test
81
+ files are skipped.
82
+
83
+ nest-server-starter adds it as `check:unified-field-types` to `check` (fails on a finding) and with `--fix` to
84
+ `check:fix`, before `format`, so `lt fullstack update` brings it to every starter-based project. A project of its own:
85
+
86
+ ```jsonc
87
+ "check:unified-field-types": "nest-check-unified-field-types",
88
+ // in "check": … && pnpm run check:unified-field-types && …
89
+ // in "check:fix": … && pnpm run check:unified-field-types -- --fix && pnpm run format && …
90
+ ```
91
+
92
+ ## 3. Outlook
93
+
94
+ A later minor release turns the warning of §1 into an error at boot, as `@UnifiedField` already refuses an array field
95
+ without `type`. A project that runs `check:unified-field-types` in its `check` is ready for it.
96
+
97
+ ## Troubleshooting
98
+
99
+ | Symptom | Cause | Fix |
100
+ |---|---|---|
101
+ | `[@UnifiedField] "X.y" has no explicit type …` at start | §1 | `nest-check-unified-field-types --fix` (vendor mode: `node ./bin/check-unified-field-types.js --fix`), or declare `type` / `isAny` / `enum` by hand |
102
+ | The dev API refuses `max: 5` with "must be an object", the deployed API accepts it | §1 | as above |
103
+ | The check reports `(a type-only import)` | the class is imported with `import type` | import it as a value, then `type: () => X` |
104
+ | A fixed field is marked `[changes the deployed build]` | `strictNullChecks`: the build validated it as an object until now | review it; the written type is the one the field declares |
105
+ | `tsconfig not found` (exit code 2) | the check runs outside the API project | run it in the API project, or pass `--project` |
106
+
107
+ ## References
108
+
109
+ - `bin/check-unified-field-types.js`
110
+ - `src/core/common/decorators/unified-field.decorator.ts` — `warnIfAmbiguousMetadataType()`
111
+ - `tests/unit/check-unified-field-types.spec.ts`, `tests/unit/unified-field-ambiguous-type.spec.ts`
112
+ - `migration-guides/11.43.x-to-12.0.x.md` §14 — decorator metadata of the TypeScript loader
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.8.5",
3
+ "version": "12.8.7",
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": [
@@ -34,14 +34,15 @@
34
34
  "check": "node scripts/check.mjs",
35
35
  "check:consumer": "node scripts/check-consumer.mjs",
36
36
  "check:esm": "node scripts/check-esm-core.mjs",
37
- "check:fix": "pnpm install && pnpm run spectaql:sync && pnpm audit --fix && pnpm run check:overrides && pnpm peers check && pnpm run format && pnpm run lint:fix && pnpm run typecheck:tests && pnpm run typecheck:vendor && pnpm run check:vendor-lint && pnpm run check:esm && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && pnpm run check:without-mongodb && pnpm run check:server-start",
37
+ "check:fix": "pnpm install && pnpm run spectaql:sync && pnpm audit --fix && pnpm run check:overrides && pnpm peers check && pnpm run check:unified-field-types -- --fix && pnpm run format && pnpm run lint:fix && pnpm run typecheck:tests && pnpm run typecheck:vendor && pnpm run check:vendor-lint && pnpm run check:esm && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && pnpm run check:without-mongodb && pnpm run check:server-start",
38
38
  "check:manifest": "node scripts/check-package-manifest.mjs",
39
39
  "check:mutations": "node scripts/check-mutations.mjs",
40
- "check:naf": "pnpm install && pnpm run spectaql:sync && pnpm run check:overrides && pnpm peers check && pnpm run format && pnpm run lint:fix && pnpm run typecheck:tests && pnpm run typecheck:vendor && pnpm run check:vendor-lint && pnpm run check:esm && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && pnpm run check:without-mongodb && pnpm run check:server-start",
40
+ "check:naf": "pnpm install && pnpm run spectaql:sync && pnpm run check:overrides && pnpm peers check && pnpm run check:unified-field-types -- --fix && pnpm run format && pnpm run lint:fix && pnpm run typecheck:tests && pnpm run typecheck:vendor && pnpm run check:vendor-lint && pnpm run check:esm && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && pnpm run check:without-mongodb && pnpm run check:server-start",
41
41
  "check:overrides": "node scripts/check-overrides.mjs",
42
- "check:raw": "pnpm install --frozen-lockfile && pnpm run spectaql:sync && pnpm audit && pnpm run check:overrides && pnpm peers check && pnpm run format:check && pnpm run lint && pnpm run typecheck:tests && pnpm run typecheck:vendor && pnpm run check:vendor-lint && pnpm run check:esm && pnpm run check:swc-tdz && pnpm test && pnpm run build && pnpm run check:manifest && pnpm run check:without-mongodb && pnpm run check:server-start",
42
+ "check:raw": "pnpm install --frozen-lockfile && pnpm run spectaql:sync && pnpm audit && pnpm run check:overrides && pnpm peers check && pnpm run format:check && pnpm run lint && pnpm run typecheck:tests && pnpm run typecheck:vendor && pnpm run check:vendor-lint && pnpm run check:esm && pnpm run check:swc-tdz && pnpm run check:unified-field-types && pnpm test && pnpm run build && pnpm run check:manifest && pnpm run check:without-mongodb && pnpm run check:server-start",
43
43
  "check:server-start": "cross-env NODE_ENV=local node scripts/check-server-start.mjs --entry=dist/main.js --port-env=NSC__PORT --ready=\"Server starte[dt] at\" --path=/",
44
44
  "check:swc-tdz": "nest build -b swc -p tsconfig.swc-tdz.json && node scripts/check-swc-tdz.mjs",
45
+ "check:unified-field-types": "node bin/check-unified-field-types.js",
45
46
  "check:vendor-lint": "node scripts/check-vendor-lint.mjs",
46
47
  "check:without-mongodb": "node scripts/check-without-mongodb.mjs --dist",
47
48
  "check:without-mongodb:package": "node scripts/check-without-mongodb.mjs --package",
@@ -106,12 +107,12 @@
106
107
  "@getbrevo/brevo": "6.2.0",
107
108
  "@modelcontextprotocol/sdk": "1.32.2",
108
109
  "@nestjs/apollo": "14.2.0",
109
- "@nestjs/common": "12.4.0",
110
- "@nestjs/core": "12.4.0",
110
+ "@nestjs/common": "12.4.2",
111
+ "@nestjs/core": "12.4.2",
111
112
  "@nestjs/graphql": "14.2.0",
112
113
  "@nestjs/jwt": "12.0.4",
113
114
  "@nestjs/passport": "12.0.1",
114
- "@nestjs/platform-express": "12.4.0",
115
+ "@nestjs/platform-express": "12.4.2",
115
116
  "@nestjs/schedule": "12.0.3",
116
117
  "@nestjs/swagger": "12.1.1",
117
118
  "@nestjs/terminus": "12.1.0",
@@ -124,7 +125,7 @@
124
125
  "compression": "1.8.2",
125
126
  "cookie-parser": "1.4.7",
126
127
  "cron": "4.4.0",
127
- "dotenv": "18.0.9",
128
+ "dotenv": "18.0.10",
128
129
  "ejs": "7.0.2",
129
130
  "express": "5.3.0",
130
131
  "graphql": "16.14.2",
@@ -132,7 +133,7 @@
132
133
  "graphql-subscriptions": "3.0.0",
133
134
  "graphql-upload": "17.1.0",
134
135
  "graphql-ws": "6.4.1",
135
- "jose": "6.2.15",
136
+ "jose": "6.2.17",
136
137
  "js-sha256": "1.0.0",
137
138
  "json-to-graphql-query": "2.3.0",
138
139
  "lodash": "4.18.1",
@@ -227,16 +228,16 @@
227
228
  }
228
229
  },
229
230
  "devDependencies": {
230
- "@aws-sdk/client-s3": "3.1164.0",
231
- "@aws-sdk/lib-storage": "3.1164.0",
232
- "@aws-sdk/s3-request-presigner": "3.1164.0",
231
+ "@aws-sdk/client-s3": "3.1165.0",
232
+ "@aws-sdk/lib-storage": "3.1165.0",
233
+ "@aws-sdk/s3-request-presigner": "3.1165.0",
233
234
  "@better-auth/core": "1.7.18",
234
235
  "@better-auth/passkey": "1.7.18",
235
236
  "@compodoc/compodoc": "2.0.0",
236
237
  "@nestjs/cli": "12.0.12",
237
238
  "@nestjs/mongoose": "12.0.1",
238
239
  "@nestjs/schematics": "12.0.13",
239
- "@nestjs/testing": "12.4.0",
240
+ "@nestjs/testing": "12.4.2",
240
241
  "@swc/cli": "0.8.2",
241
242
  "@swc/core": "1.16.22",
242
243
  "@tus/s3-store": "2.1.0",
@@ -257,12 +258,12 @@
257
258
  "ioredis": "6.0.0",
258
259
  "kysely": "0.29.8",
259
260
  "mongodb": "7.8.0",
260
- "mongoose": "9.12.0",
261
+ "mongoose": "9.12.1",
261
262
  "mysql2": "3.24.6",
262
263
  "nodemon": "3.1.14",
263
264
  "otpauth": "9.6.0",
264
- "oxfmt": "0.77.0",
265
- "oxlint": "1.92.0",
265
+ "oxfmt": "0.78.0",
266
+ "oxlint": "1.93.0",
266
267
  "oxlint-tsgolint": "7.0.2006",
267
268
  "pg": "8.23.1",
268
269
  "playwright-core": "1.65.0",
@@ -273,14 +274,15 @@
273
274
  "typeorm": "1.1.2",
274
275
  "typescript": "6.0.3",
275
276
  "unplugin-swc": "2.0.0",
276
- "vite": "8.3.6",
277
+ "vite": "8.3.7",
277
278
  "vitest": "5.1.0"
278
279
  },
279
280
  "main": "dist/index.js",
280
281
  "types": "dist/index.d.ts",
281
282
  "bin": {
282
283
  "nest-migrate": "./bin/migrate.js",
283
- "migrate": "./bin/migrate.js"
284
+ "migrate": "./bin/migrate.js",
285
+ "nest-check-unified-field-types": "./bin/check-unified-field-types.js"
284
286
  },
285
287
  "files": [
286
288
  "dist/**/*",
@@ -270,6 +270,64 @@ function warnIfLikelyMisconfiguredEnumOptions(value: unknown, propertyHint: stri
270
270
  }
271
271
  }
272
272
 
273
+ /**
274
+ * `design:type` as the tsc build writes it. For a field typed with an enum, tsc writes `String` (string enum) or
275
+ * `Number` (numeric enum); the SWC loader of the dev start writes the enum OBJECT. Read as is, that object became the
276
+ * Mongoose path type (`SchemaFactory` refused it: "'active' is not a valid type") and a nested-object validation target.
277
+ * tsc never writes a plain object here, so only the dev start is affected; a heterogeneous enum stays as it is.
278
+ */
279
+ function designTypeOf(metadataType: unknown): unknown {
280
+ if (typeof metadataType !== 'object' || metadataType === null || Array.isArray(metadataType)) {
281
+ return metadataType;
282
+ }
283
+ const values = Object.values(metadataType);
284
+ if (values.length === 0) {
285
+ return metadataType;
286
+ }
287
+ const numbers = values.filter((value) => typeof value === 'number');
288
+ const strings = values.filter((value) => typeof value === 'string') as string[];
289
+ if (numbers.length === 0 && strings.length === values.length) {
290
+ return String;
291
+ }
292
+ // A numeric enum carries its reverse mapping: every string value is the name of a numeric member
293
+ if (
294
+ numbers.length > 0 &&
295
+ strings.every((name) => typeof (metadataType as Record<string, unknown>)[name] === 'number')
296
+ ) {
297
+ return Number;
298
+ }
299
+ return metadataType;
300
+ }
301
+
302
+ /** Fields already warned about by {@link warnIfAmbiguousMetadataType}: one line per field, not per decoration. */
303
+ const ambiguousTypeWarned = new Set<string>();
304
+
305
+ /**
306
+ * Warn when a field without `type` / `isAny` / `enum` takes its type from compiler metadata that is only `Object`. The
307
+ * SWC loader of the dev start writes `design:type` syntactically, file by file: a union with `null` / `undefined` (also
308
+ * with an enum), a type alias or an interface become `Object` there, where the tsc build writes `Number`, `String` or
309
+ * the class — a plain enum is read like tsc does, see {@link designTypeOf}. The dev API then validates the field as a
310
+ * nested object while the deployed one does not — `max: 5` refused in development, accepted in production.
311
+ *
312
+ * The package bin `nest-check-unified-field-types --fix` (`check:unified-field-types` in nest-server-starter
313
+ * projects; vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes the declared type into every such
314
+ * field; a later release refuses them at boot.
315
+ */
316
+ function warnIfAmbiguousMetadataType(metadataType: unknown, propertyHint: string): void {
317
+ const ambiguous = metadataType === Object || (typeof metadataType === 'object' && metadataType !== null);
318
+ if (!ambiguous || ambiguousTypeWarned.has(propertyHint)) return;
319
+ ambiguousTypeWarned.add(propertyHint);
320
+ // eslint-disable-next-line no-console
321
+ console.warn(
322
+ `[@UnifiedField] "${propertyHint}" has no explicit type, and the compiler metadata says only "Object". The SWC ` +
323
+ 'dev start and the tsc build can disagree here (a union with null/undefined, a type alias, an interface), so ' +
324
+ 'the dev API may validate it as a nested object. Declare it: type: () => Number / String / Boolean / ' +
325
+ 'Date / <Class>, type: () => Object for a free-form object, or isAny: true. `nest-check-unified-field-types ' +
326
+ '--fix` (vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes the declared type; a later ' +
327
+ 'release refuses such a field at boot.',
328
+ );
329
+ }
330
+
273
331
  export function UnifiedField(opts: UnifiedFieldOptions = {}): PropertyDecorator {
274
332
  // Normalize the shortcut form `enum: MyEnum` into the long form
275
333
  // `enum: { enum: MyEnum }` so the rest of the decorator can assume a uniform
@@ -353,7 +411,7 @@ export function UnifiedField(opts: UnifiedFieldOptions = {}): PropertyDecorator
353
411
  Reflect.defineMetadata(UNIFIED_FIELD_KEYS, [...existingKeys, key], target);
354
412
  }
355
413
 
356
- const metadataType = Reflect.getMetadata('design:type', target, propertyKey);
414
+ const metadataType = designTypeOf(Reflect.getMetadata('design:type', target, propertyKey));
357
415
  const userType = opts.type;
358
416
  const isArrayField = opts.isArray === true || metadataType === Array;
359
417
 
@@ -362,6 +420,10 @@ export function UnifiedField(opts: UnifiedFieldOptions = {}): PropertyDecorator
362
420
  throw new Error(`Array field '${String(propertyKey)}' of '${String(target)}' must have an explicit type`);
363
421
  }
364
422
 
423
+ if (!userType && !opts.isAny && !normalizedEnum) {
424
+ warnIfAmbiguousMetadataType(metadataType, `${target.constructor?.name || '?'}.${key}`);
425
+ }
426
+
365
427
  const resolvedTypeFn = (): any => {
366
428
  if (userType) {
367
429
  if (userType instanceof GraphQLScalarType) {
@@ -2251,6 +2251,24 @@ export interface IAi {
2251
2251
  */
2252
2252
  oauthLoginUrl?: string;
2253
2253
  oauthSecret?: string;
2254
+ /**
2255
+ * Which accounts may use MCP at all (12.8.6+): only a user whose own `roles` hold one of these. Checked on
2256
+ * every request to `/ai/mcp`, whichever credential authenticated it (the user's session token or JWT as
2257
+ * bearer, an MCP OAuth access token), on the consent route (a refused user gets the notice page with 403
2258
+ * instead of the consent form) and when an authorization code or a refresh token is exchanged
2259
+ * (`invalid_grant`). A revoked role therefore takes effect with the next request, also for open sessions
2260
+ * and grants issued earlier.
2261
+ *
2262
+ * An array of role names, or a comma-separated string (`NSC__AI__MCP__ROLES=admin,support`). Unset: every
2263
+ * signed-in user may use MCP, as before 12.8.6. A value that names no role (`[]`, `''`, an empty entry,
2264
+ * a non-string) or a system role (`s_…`) fails the boot — a misconfiguration must never read as "everyone".
2265
+ * The roles are compared with the user's own (global) roles, never a tenant membership role; list every
2266
+ * role that may use MCP, `admin` included if administrators should. For any other rule override
2267
+ * `mayUseMcp()` in the `CoreAiMcpOAuthService` subclass registered via
2268
+ * `CoreModule.forRoot(env, { ai: { mcpOAuthService } })`.
2269
+ * @default undefined (every signed-in user)
2270
+ */
2271
+ roles?: string | string[];
2254
2272
  /**
2255
2273
  * Serve `/ai/mcp` without sessions: every POST builds its own server and transport for the
2256
2274
  * authenticated user and ends with the response, no `mcp-session-id` is issued, and GET /
@@ -249,6 +249,14 @@ CSS without copying markup, scripts or headers; fill both from code or configura
249
249
  `authorizeConsent(client, params, res)` (replace), registered via
250
250
  `CoreModule.forRoot(envConfig, { ai: { mcpOAuthService: McpOAuthService } })`.
251
251
 
252
+ **Optional — only some accounts may use MCP (12.8.6+):** `ai: { mcp: { roles: ['admin'] } }` (or
253
+ `NSC__AI__MCP__ROLES=admin`). The framework checks it on every `/ai/mcp` request (session, JWT and OAuth token alike),
254
+ on the consent route (refusal notice, 403) and on `/token` — do not build this into an `authorizeConsent()` override:
255
+ `/ai/mcp` takes the user's own session or JWT as bearer, which never passes `/authorize`. For a rule roles cannot
256
+ express, override `mayUseMcp(user, req)` in the `CoreAiMcpOAuthService` subclass; the refusal's wording comes from
257
+ `consentRefusal(req)`, its look from `renderConsentNoticePage(view)`. A project that refused accounts in its own
258
+ `authorizeConsent()` moves that rule into `ai.mcp.roles` or `mayUseMcp()` (README, "Who may use MCP").
259
+
252
260
  **Optional — no sticky sessions:** `ai: { mcp: { stateless: true } }` serves `/ai/mcp` without sessions, so any
253
261
  replica answers any request. Without a session the server cannot ask the user (no MCP elicitation): tools that
254
262
  need confirmation are refused there unless the user or `ai.mcp.confirmation` switched the question off.
@@ -945,6 +945,72 @@ protected override renderConsentPage(view: IMcpOAuthConsentView): string {
945
945
  }
946
946
  ```
947
947
 
948
+ **Who may use MCP (12.8.6+).** `ai.mcp.roles` limits MCP to accounts holding one of the listed roles — an array, or a
949
+ comma-separated string (`NSC__AI__MCP__ROLES=admin,support`). Unset, every signed-in user may use MCP, as before.
950
+
951
+ ```typescript
952
+ ai: { mcp: { oauth: true, roles: ['admin'] } }
953
+ ```
954
+
955
+ The framework checks the rule wherever a credential arrives, so it cannot be walked around:
956
+
957
+ | Where | Credential | A refused user gets |
958
+ | ---------------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------- |
959
+ | every request to `/ai/mcp` (POST, GET, DELETE) | the user's session token or JWT as bearer, an MCP OAuth access token | 403 — an open session ends with its next request |
960
+ | the consent route `/authorize` | the signed-in session | the refusal notice (403) instead of the consent form |
961
+ | `/token` | an authorization code, a refresh token | `invalid_grant`; the refresh token the rotation issued is revoked |
962
+
963
+ The roles are compared with the user's own (global) roles, never a tenant membership role — list every role that may
964
+ use MCP, `admin` included if administrators should. A value that names no role (`[]`, `''`, an empty entry, a
965
+ non-string) or a system role (`s_…`) fails the boot: a misconfigured access rule must never read as "everyone may".
966
+
967
+ **Any other rule** (a flag in the database, a tenant rule): override `mayUseMcp(user, req)` in the
968
+ `CoreAiMcpOAuthService` subclass registered via `CoreModule.forRoot(env, { ai: { mcpOAuthService } })`. The framework
969
+ calls it at every point in the table above — `user` carries `id` and `roles` (on `/token` the roles `loadUser()`
970
+ reads), and it runs per MCP request, so keep it fast. Only an explicit `true` admits; a throw refuses and is logged.
971
+
972
+ ```typescript
973
+ @Injectable()
974
+ export class McpOAuthService extends CoreAiMcpOAuthService {
975
+ constructor(
976
+ @InjectConnection() connection: Connection,
977
+ private readonly mcpAccounts: McpAccountService,
978
+ ) {
979
+ super(connection);
980
+ }
981
+
982
+ // A rule roles cannot express, e.g. a switch the project keeps per account
983
+ override async mayUseMcp(user: { id: string; roles?: string[] }): Promise<boolean> {
984
+ return this.mcpAccounts.isEnabled(user.id);
985
+ }
986
+ }
987
+ ```
988
+
989
+ **The refusal notice.** Its wording comes from `consentRefusal(req)` (German or English by `Accept-Language`),
990
+ its look from `renderConsentNoticePage(view)` — override them to change it:
991
+
992
+ ```typescript
993
+ protected override consentRefusal(req: any): IMcpOAuthConsentNotice {
994
+ return { locale: 'de', message: 'Nur Administratoren dürfen MCP-Clients verbinden.', title: 'Zugriff nicht möglich' };
995
+ }
996
+
997
+ protected override renderConsentNoticePage(view: IMcpOAuthConsentNoticeView): string {
998
+ return renderMcpOAuthConsentNoticePage(view, { styles: ':root{--primary:#0b5}' });
999
+ }
1000
+ ```
1001
+
1002
+ **A notice of your own on the consent route** — for any other case where a project answers `/authorize` itself:
1003
+ `this.sendConsentNotice(res, { title, message })` from an overridden `authorizeConsent()`. The framework sets the
1004
+ status (default 403, any 400–599), a fresh nonce and the consent page's security headers (CSP with nonce,
1005
+ `frame-ancestors 'none'`, `X-Frame-Options: DENY`, `no-store`), so the page keeps receiving their fixes. It shows title
1006
+ and message as plain text (an array renders one paragraph per entry), the signed-in account with "use another
1007
+ account" (`switchAccount: false` leaves it out) and optionally a link (`link: { href, label }`, an absolute `http(s)`
1008
+ URL or a path; anything else is dropped with a warning). It issues nothing: no code, no redirect. `locale` fixes the
1009
+ language of the built-in labels; default from `Accept-Language`. The security headers themselves are not exported
1010
+ (`mcpOAuthConsentHeaders()` stays internal): a project that copied them into its own response would stop receiving
1011
+ their fixes. Such a notice refuses a new grant only — who may use MCP at all belongs in `ai.mcp.roles` /
1012
+ `mayUseMcp()`, which `/ai/mcp` and `/token` check too.
1013
+
948
1014
  **Your own page.** Override `renderConsentPage(view)` in a subclass to restyle it beyond that (keep every
949
1015
  value escaped), or `authorizeConsent(client, params, res)` for a consent UI of your own — same shape: no session
950
1016
  → sign in, GET → show which client, POST with a CSRF token → `saveAuthorizationCode()` and redirect;
@@ -130,6 +130,10 @@ export class CoreAiMcpController implements OnModuleDestroy {
130
130
  this.unauthorized(res);
131
131
  return;
132
132
  }
133
+ if (!(await this.oauthService.checkMcpAccess(user, req))) {
134
+ this.forbidden(res);
135
+ return;
136
+ }
133
137
 
134
138
  if (this.statelessEnabled()) {
135
139
  await this.handleStatelessPost(req, res, user);
@@ -401,6 +405,10 @@ export class CoreAiMcpController implements OnModuleDestroy {
401
405
  this.unauthorized(res);
402
406
  return;
403
407
  }
408
+ if (!(await this.oauthService.checkMcpAccess(user, req))) {
409
+ this.forbidden(res);
410
+ return;
411
+ }
404
412
  // Without sessions there is no stream to open and nothing to end (MCP spec: 405 for GET then).
405
413
  if (this.statelessEnabled()) {
406
414
  res.status(405).set('Allow', 'POST').json({ error: 'Method not allowed: this MCP server is stateless' });
@@ -592,6 +600,15 @@ export class CoreAiMcpController implements OnModuleDestroy {
592
600
  .json({ error: 'Unauthorized: a valid Bearer token is required' });
593
601
  }
594
602
 
603
+ /**
604
+ * 403 for an authenticated user who may not use MCP (`CoreAiMcpOAuthService.mayUseMcp()`, `ai.mcp.roles`) — checked on
605
+ * every request, whichever credential authenticated it, so a withdrawn right ends an open session with its next
606
+ * request. No `WWW-Authenticate`: signing in again with the same account changes nothing.
607
+ */
608
+ private forbidden(res: Response): void {
609
+ res.status(403).json({ error: 'Forbidden: this account may not use MCP' });
610
+ }
611
+
595
612
  /**
596
613
  * Make room for a new session of `ownerId`, evicting WITHIN the offending user's own set.
597
614
  *