@lenne.tech/nest-server 12.8.4 → 12.8.6

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 (30) hide show
  1. package/.claude/rules/configurable-features.md +2 -1
  2. package/.claude/rules/testing.md +3 -3
  3. package/FRAMEWORK-API.md +1 -1
  4. package/dist/core/common/filters/http-exception-log.filter.js +4 -3
  5. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  6. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  7. package/dist/core/modules/ai/core-ai-mcp.controller.d.ts +1 -0
  8. package/dist/core/modules/ai/core-ai-mcp.controller.js +11 -0
  9. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  10. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.d.ts +33 -0
  11. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js +74 -9
  12. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js.map +1 -1
  13. package/dist/core/modules/ai/index.d.ts +2 -2
  14. package/dist/core/modules/ai/index.js +1 -1
  15. package/dist/core/modules/ai/index.js.map +1 -1
  16. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +17 -1
  17. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +124 -8
  18. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  19. package/docs/REQUEST-LIFECYCLE.md +1 -1
  20. package/migration-guides/12.8.4-to-12.8.5.md +39 -0
  21. package/migration-guides/12.8.5-to-12.8.6.md +144 -0
  22. package/package.json +1 -1
  23. package/src/core/common/filters/http-exception-log.filter.ts +7 -3
  24. package/src/core/common/interfaces/server-options.interface.ts +18 -0
  25. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +8 -0
  26. package/src/core/modules/ai/README.md +66 -0
  27. package/src/core/modules/ai/core-ai-mcp.controller.ts +17 -0
  28. package/src/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.ts +150 -11
  29. package/src/core/modules/ai/index.ts +5 -1
  30. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +222 -8
@@ -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
  *
@@ -7,6 +7,10 @@
7
7
  * Better-Auth's own endpoints on the same origin, then a reload of the very same `/authorize`
8
8
  * request. Other methods (passkey, social login) through the app's login page.
9
9
  *
10
+ * Plus a notice page in the same document ({@link renderMcpOAuthConsentNoticePage}): the refusal for a user
11
+ * `CoreAiMcpOAuthService.mayUseMcp()` refuses (`ai.mcp.roles`), and whatever else a project answers on the consent
12
+ * route instead of the form.
13
+ *
10
14
  * Everything that reaches the page from outside is escaped: the client's name comes from dynamic
11
15
  * registration, i.e. from whoever registered the client. Nothing here decides whether a code is
12
16
  * issued — that is `CoreAiMcpOAuthService` (CSRF token, user, client, PKCE challenge).
@@ -101,6 +105,30 @@ const TEXTS = {
101
105
  },
102
106
  } satisfies Record<McpOAuthConsentLocale, Record<string, string>>;
103
107
 
108
+ /** What the consent route shows a user `CoreAiMcpOAuthService.mayUseMcp()` refuses. */
109
+ const REFUSAL_TEXTS = {
110
+ de: {
111
+ message: [
112
+ 'Dieses Konto darf keine MCP-Clients verbinden.',
113
+ 'Melde dich mit einem anderen Konto an oder wende dich an die Administration.',
114
+ ],
115
+ title: 'Kein Zugriff über MCP',
116
+ },
117
+ en: {
118
+ message: [
119
+ 'This account may not connect MCP clients.',
120
+ 'Sign in with another account or contact your administrator.',
121
+ ],
122
+ title: 'No MCP access',
123
+ },
124
+ } satisfies Record<McpOAuthConsentLocale, { message: string[]; title: string }>;
125
+
126
+ /** Title and message of the built-in refusal notice in one locale. */
127
+ export function mcpOAuthConsentRefusalTexts(locale: McpOAuthConsentLocale): { message: string[]; title: string } {
128
+ const texts = REFUSAL_TEXTS[locale] ?? REFUSAL_TEXTS.en;
129
+ return { message: [...texts.message], title: texts.title };
130
+ }
131
+
104
132
  /** The locale for an `Accept-Language` header: German when the first preference is German, else English. */
105
133
  export function mcpOAuthConsentLocale(acceptLanguage: unknown): McpOAuthConsentLocale {
106
134
  const first = typeof acceptLanguage === 'string' ? acceptLanguage.split(',')[0].trim().toLowerCase() : '';
@@ -149,7 +177,7 @@ export function renderMcpOAuthConsentPage(
149
177
  view: IMcpOAuthConsentView,
150
178
  options: IMcpOAuthConsentPageOptions = {},
151
179
  ): string {
152
- const t: Texts = { ...TEXTS[view.locale], ...options.texts?.[view.locale] };
180
+ const t = pageTexts(view.locale, options);
153
181
  const clientName = view.client.name?.trim() || t.unnamedClient;
154
182
  // One pass: a client name is chosen by whoever registered the client, so a name containing
155
183
  // `{app}` must not be expanded by a second replace.
@@ -160,6 +188,106 @@ export function renderMcpOAuthConsentPage(
160
188
  );
161
189
 
162
190
  const body = view.user ? consentView(view, t, fill) : signInView(view, t, fill);
191
+ return pageDocument(view, t.title, body, pageScript(view), options);
192
+ }
193
+
194
+ /**
195
+ * What the consent route answers instead of the consent form: the refusal of `CoreAiMcpOAuthService.consentRefusal()`
196
+ * for a user `mayUseMcp()` refuses, or a notice a project decides in its own `authorizeConsent()` before calling
197
+ * `super`. Passed to `CoreAiMcpOAuthService.sendConsentNotice()`, which sets the status, a fresh nonce and the page's
198
+ * security headers. Fill it from code or configuration, never from user or tenant input; every value is rendered as
199
+ * plain text. Who may use MCP at all is `ai.mcp.roles` / `mayUseMcp()` — a notice alone stops a new grant only.
200
+ */
201
+ export interface IMcpOAuthConsentNotice {
202
+ /** A link below the message, e.g. to the app: an absolute `http(s)` URL or a path on this origin; anything else is dropped */
203
+ link?: { href: string; label: string };
204
+ /** Locale of the built-in labels and of `<html lang>`; default from the request's `Accept-Language` */
205
+ locale?: McpOAuthConsentLocale;
206
+ /** Plain text; an array renders one paragraph per entry */
207
+ message: string | string[];
208
+ /** HTTP status between 400 and 599; default 403 */
209
+ status?: number;
210
+ /** Offer "use another account" when a user is signed in (default `true`) */
211
+ switchAccount?: boolean;
212
+ title: string;
213
+ }
214
+
215
+ /** What the notice page shows. Built by `CoreAiMcpOAuthService`, rendered by {@link renderMcpOAuthConsentNoticePage}. */
216
+ export interface IMcpOAuthConsentNoticeView {
217
+ /** Host the user knows the application by (the app's host, else the API's) */
218
+ appHost: string;
219
+ /** Better-Auth base path; with a signed-in user it offers "use another account". Absent: no such offer */
220
+ authBasePath?: string;
221
+ link?: { href: string; label: string };
222
+ locale: McpOAuthConsentLocale;
223
+ /** One paragraph per entry */
224
+ message: string[];
225
+ /** CSP nonce of this response */
226
+ nonce: string;
227
+ title: string;
228
+ /** The signed-in user, if any */
229
+ user?: { email?: string; name?: string };
230
+ }
231
+
232
+ /**
233
+ * Renders the notice page: title, message, the signed-in account with "use another account", an optional link. No
234
+ * form and nothing that issues a code — the MCP client keeps waiting until the user signs in with another account
235
+ * or closes the window. Same document, styles and escaping as the consent page; `options` work as there.
236
+ */
237
+ export function renderMcpOAuthConsentNoticePage(
238
+ view: IMcpOAuthConsentNoticeView,
239
+ options: IMcpOAuthConsentPageOptions = {},
240
+ ): string {
241
+ const t = pageTexts(view.locale, options);
242
+ const account = accountLine(view.user, view.authBasePath, t);
243
+ const href = consentNoticeLinkHref(view.link?.href);
244
+ const link = href
245
+ ? `<div class="other"><a href="${escapeHtml(href)}">${escapeHtml(view.link?.label || href)}</a></div>`
246
+ : '';
247
+ const body = `<h1>${escapeHtml(view.title)}</h1>
248
+ ${account}
249
+ ${view.message.map((paragraph) => `<p>${escapeHtml(paragraph)}</p>`).join('\n')}
250
+ ${link}`;
251
+ // Only the "use another account" half of the guard script has anything to do here: there is no Allow button
252
+ const script = account.includes('id="lt-mcp-switch"')
253
+ ? `<script nonce="${escapeHtml(view.nonce)}">${MCP_OAUTH_CONSENT_GUARD_SCRIPT}</script>`
254
+ : '';
255
+ return pageDocument(view, view.title, body, script, options);
256
+ }
257
+
258
+ /**
259
+ * The link target of a notice, or `undefined`: an absolute `http(s)` URL, or a path on this origin. A protocol-relative
260
+ * `//host` and its backslash spelling `/\host` (which browsers read the same way) are not paths, and a value with a
261
+ * control character is refused outright.
262
+ */
263
+ export function consentNoticeLinkHref(href: unknown): string | undefined {
264
+ if (typeof href !== 'string') {
265
+ return undefined;
266
+ }
267
+ const value = href.trim();
268
+ // Browsers drop tabs and line breaks from a URL, so `/\t/host` would become the protocol-relative `//host`
269
+ if ([...value].some((char) => char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f)) {
270
+ return undefined;
271
+ }
272
+ if (value.startsWith('/')) {
273
+ return /^\/[/\\]/.test(value) ? undefined : value;
274
+ }
275
+ try {
276
+ const url = new URL(value);
277
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined;
278
+ } catch {
279
+ return undefined;
280
+ }
281
+ }
282
+
283
+ /** The HTML document both pages share. */
284
+ function pageDocument(
285
+ view: { appHost: string; locale: McpOAuthConsentLocale; nonce: string },
286
+ title: string,
287
+ body: string,
288
+ script: string,
289
+ options: IMcpOAuthConsentPageOptions,
290
+ ): string {
163
291
  return `<!doctype html>
164
292
  <html lang="${view.locale}">
165
293
  <head>
@@ -167,14 +295,14 @@ export function renderMcpOAuthConsentPage(
167
295
  <meta name="viewport" content="width=device-width, initial-scale=1">
168
296
  <meta name="robots" content="noindex">
169
297
  <link rel="icon" href="data:,">
170
- <title>${escapeHtml(t.title)} – ${escapeHtml(view.appHost)}</title>
298
+ <title>${escapeHtml(title)} – ${escapeHtml(view.appHost)}</title>
171
299
  <style nonce="${escapeHtml(view.nonce)}">${STYLES}${confinedStyles(options.styles)}</style>
172
300
  </head>
173
301
  <body>
174
302
  <main class="card">
175
303
  ${body}
176
304
  </main>
177
- ${pageScript(view)}
305
+ ${script}
178
306
  </body>
179
307
  </html>
180
308
  `;
@@ -182,6 +310,24 @@ ${pageScript(view)}
182
310
 
183
311
  type Texts = McpOAuthConsentTexts;
184
312
 
313
+ /** The texts of one locale: the built-in ones, with the project's replacements merged over them. */
314
+ function pageTexts(locale: McpOAuthConsentLocale, options: IMcpOAuthConsentPageOptions): Texts {
315
+ return { ...TEXTS[locale], ...options.texts?.[locale] };
316
+ }
317
+
318
+ /** "Signed in as …" with "use another account" (when Better-Auth is active); empty without a user. */
319
+ function accountLine(user: { email?: string; name?: string } | undefined, authBasePath: string | undefined, t: Texts) {
320
+ const who = user?.email || user?.name;
321
+ if (!who) {
322
+ return '';
323
+ }
324
+ return `<p class="account">${escapeHtml(t.signedInAs).replace('{user}', () => `<strong>${escapeHtml(who)}</strong>`)}${
325
+ authBasePath
326
+ ? `<a href="" id="lt-mcp-switch" class="switch" data-sign-out="${escapeHtml(`${authBasePath}/sign-out`)}">${escapeHtml(t.switchAccount)}</a>`
327
+ : ''
328
+ }</p>`;
329
+ }
330
+
185
331
  /**
186
332
  * Project CSS that cannot end the `<style>` element: a `</style>` in it would continue as markup — an injected
187
333
  * form, for one, since the page sets no `form-action`. `<` has no meaning in CSS outside strings and comments, and
@@ -195,19 +341,12 @@ function consentView(view: IMcpOAuthConsentView, t: Texts, fill: (text: string)
195
341
  const target = view.redirect.loopback
196
342
  ? `${escapeHtml(t.loopback)} (${escapeHtml(view.redirect.host)})`
197
343
  : escapeHtml(view.redirect.host);
198
- const who = view.user?.email || view.user?.name;
199
344
  const hidden = Object.entries(view.oauthParams)
200
345
  .map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`)
201
346
  .join('\n');
202
347
  // The account comes first and is not muted: a session planted by login CSRF must be noticed
203
348
  // before Allow, not after.
204
- const account = who
205
- ? `<p class="account">${escapeHtml(t.signedInAs).replace('{user}', () => `<strong>${escapeHtml(who)}</strong>`)}${
206
- view.authBasePath
207
- ? `<a href="" id="lt-mcp-switch" class="switch" data-sign-out="${escapeHtml(`${view.authBasePath}/sign-out`)}">${escapeHtml(t.switchAccount)}</a>`
208
- : ''
209
- }</p>`
210
- : '';
349
+ const account = accountLine(view.user, view.authBasePath, t);
211
350
  // Allow starts disabled: only the guard script enables it, so a page without the script can never
212
351
  // be clicked into an approval (see MCP_OAUTH_CONSENT_GUARD_SCRIPT).
213
352
  return `<h1>${escapeHtml(t.title)}</h1>
@@ -2,14 +2,18 @@
2
2
  export * from './core-ai-mcp-oauth.initializer.js';
3
3
  export * from './core-ai-mcp.controller.js';
4
4
  export * from './helpers/ai-mcp-oauth.helper.js';
5
- // Named on purpose: the page's scripts and security headers stay internal, so a project cannot pin them
5
+ // Named on purpose: the page's scripts and security headers stay internal, so a project cannot pin them. A project's
6
+ // own notice on the consent route goes through CoreAiMcpOAuthService.sendConsentNotice(), which applies them
6
7
  export {
7
8
  MCP_OAUTH_CONSENT_DECISION_FIELD,
8
9
  MCP_OAUTH_CONSENT_TOKEN_FIELD,
9
10
  mcpOAuthConsentLocale,
11
+ renderMcpOAuthConsentNoticePage,
10
12
  renderMcpOAuthConsentPage,
11
13
  } from './helpers/ai-mcp-oauth-consent.helper.js';
12
14
  export type {
15
+ IMcpOAuthConsentNotice,
16
+ IMcpOAuthConsentNoticeView,
13
17
  IMcpOAuthConsentPageOptions,
14
18
  IMcpOAuthConsentView,
15
19
  McpOAuthConsentLocale,