@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.
- package/.claude/rules/architecture.md +1 -0
- package/.claude/rules/configurable-features.md +2 -1
- package/.claude/rules/testing.md +3 -3
- package/CLAUDE.md +4 -0
- package/FRAMEWORK-API.md +1 -1
- package/bin/check-unified-field-types.js +615 -0
- package/dist/core/common/decorators/unified-field.decorator.js +36 -1
- package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/modules/ai/core-ai-mcp.controller.d.ts +1 -0
- package/dist/core/modules/ai/core-ai-mcp.controller.js +11 -0
- package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
- package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.d.ts +33 -0
- package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js +74 -9
- package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js.map +1 -1
- package/dist/core/modules/ai/index.d.ts +2 -2
- package/dist/core/modules/ai/index.js +1 -1
- package/dist/core/modules/ai/index.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +17 -1
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +124 -8
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +9 -1
- package/migration-guides/11.43.x-to-12.0.x.md +22 -2
- package/migration-guides/12.0.x-to-12.1.x.md +6 -0
- package/migration-guides/12.8.5-to-12.8.6.md +144 -0
- package/migration-guides/12.8.6-to-12.8.7.md +112 -0
- package/package.json +20 -18
- package/src/core/common/decorators/unified-field.decorator.ts +63 -1
- package/src/core/common/interfaces/server-options.interface.ts +18 -0
- package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +8 -0
- package/src/core/modules/ai/README.md +66 -0
- package/src/core/modules/ai/core-ai-mcp.controller.ts +17 -0
- package/src/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.ts +150 -11
- package/src/core/modules/ai/index.ts +5 -1
- package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +222 -8
|
@@ -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
|
|
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(
|
|
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
|
-
${
|
|
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 =
|
|
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,
|
|
@@ -4,6 +4,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
4
4
|
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
5
5
|
import type { Connection } from 'mongoose';
|
|
6
6
|
|
|
7
|
+
import { looksLikeSystemRole } from '../../../common/enums/role.enum.js';
|
|
7
8
|
import { isLocalEnv, resolveAppUrlFromConfig } from '../../../common/helpers/cookies.helper.js';
|
|
8
9
|
import type { DataStore } from '../../../common/persistence/data-store.interface.js';
|
|
9
10
|
import { getModelStore } from '../../../common/persistence/persistence-runtime.registry.js';
|
|
@@ -18,11 +19,16 @@ import {
|
|
|
18
19
|
AI_MCP_OAUTH_REFRESH_TOKEN_MODEL,
|
|
19
20
|
} from '../core-ai.constants.js';
|
|
20
21
|
import {
|
|
22
|
+
consentNoticeLinkHref,
|
|
23
|
+
type IMcpOAuthConsentNotice,
|
|
24
|
+
type IMcpOAuthConsentNoticeView,
|
|
21
25
|
IMcpOAuthConsentView,
|
|
22
26
|
MCP_OAUTH_CONSENT_DECISION_FIELD,
|
|
23
27
|
MCP_OAUTH_CONSENT_TOKEN_FIELD,
|
|
24
28
|
mcpOAuthConsentHeaders,
|
|
25
29
|
mcpOAuthConsentLocale,
|
|
30
|
+
mcpOAuthConsentRefusalTexts,
|
|
31
|
+
renderMcpOAuthConsentNoticePage,
|
|
26
32
|
renderMcpOAuthConsentPage,
|
|
27
33
|
} from '../helpers/ai-mcp-oauth-consent.helper.js';
|
|
28
34
|
import { getMountedMcpOAuth } from '../helpers/ai-mcp-oauth.registry.js';
|
|
@@ -189,6 +195,9 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
189
195
|
*/
|
|
190
196
|
onModuleInit(): void {
|
|
191
197
|
this.assertProductionSafe();
|
|
198
|
+
// A value of ai.mcp.roles that names no role fails the boot here rather than refusing (or, worse, admitting) at
|
|
199
|
+
// the first request — mayUseMcp() reads it again per request and refuses then, for a subclass that skips this.
|
|
200
|
+
this.mcpAccessRoles();
|
|
192
201
|
}
|
|
193
202
|
|
|
194
203
|
/** Throw when OAuth is enabled but no secret is configured outside local / ci / e2e. */
|
|
@@ -225,6 +234,50 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
225
234
|
return this.authorizeConsent === CoreAiMcpOAuthService.prototype.authorizeConsent;
|
|
226
235
|
}
|
|
227
236
|
|
|
237
|
+
/**
|
|
238
|
+
* Whether `user` may use MCP at all. The framework asks on every request to `/ai/mcp` — whichever credential
|
|
239
|
+
* authenticated it: the user's session token or JWT as bearer, or an MCP OAuth access token —, on the consent route
|
|
240
|
+
* before the consent form, and when an authorization code or a refresh token is exchanged. A refusal answers
|
|
241
|
+
* `/ai/mcp` with 403, the consent route with the notice page of {@link consentRefusal} (403), and the token endpoint
|
|
242
|
+
* with `invalid_grant`; a revoked right therefore takes effect with the next request, for open sessions and grants
|
|
243
|
+
* issued earlier too.
|
|
244
|
+
*
|
|
245
|
+
* Default: `ai.mcp.roles` — unset, every signed-in user may (as before 12.8.6); set, only a user whose own `roles`
|
|
246
|
+
* hold one of them. Override it for any other rule (a flag in the database, a tenant rule) in the subclass
|
|
247
|
+
* registered via `CoreModule.forRoot(env, { ai: { mcpOAuthService } })`, and keep it fast: it runs per MCP request.
|
|
248
|
+
* Only an explicit `true` admits; a throw refuses (see {@link checkMcpAccess}). `user.roles` are the user's own
|
|
249
|
+
* global roles — on the token endpoint those {@link loadUser} reads —, never a tenant membership role.
|
|
250
|
+
*/
|
|
251
|
+
async mayUseMcp(user: { id: string; roles?: string[] }, _req?: any): Promise<boolean> {
|
|
252
|
+
const allowed = this.mcpAccessRoles();
|
|
253
|
+
if (!allowed) {
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
const held = Array.isArray(user?.roles) ? user.roles : [];
|
|
257
|
+
return held.some((role) => typeof role === 'string' && allowed.includes(role));
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* {@link mayUseMcp}, fail-closed: `true` only for a user with an id and an explicit `true`; a throw is logged and
|
|
262
|
+
* refuses. What the framework calls — override {@link mayUseMcp}, not this.
|
|
263
|
+
*/
|
|
264
|
+
async checkMcpAccess(user: { id: string; roles?: string[] } | null | undefined, req?: any): Promise<boolean> {
|
|
265
|
+
if (!user?.id) {
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
return (await this.mayUseMcp(user, req)) === true;
|
|
270
|
+
} catch (err) {
|
|
271
|
+
this.logger.error(`MCP access check failed for user ${user.id}, refusing: ${(err as Error)?.message ?? err}`);
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** The roles `ai.mcp.roles` names, or `undefined` when it is unset. Throws on a value that names no role. */
|
|
277
|
+
protected mcpAccessRoles(): string[] | undefined {
|
|
278
|
+
return resolveMcpAccessRoles(ConfigService.get<unknown>('ai.mcp'));
|
|
279
|
+
}
|
|
280
|
+
|
|
228
281
|
/** Whether the OAuth 2.1 layer is enabled via `ai.mcp.oauth`. */
|
|
229
282
|
protected oauthEnabled(): boolean {
|
|
230
283
|
const mcp = ConfigService.get<{ oauth?: boolean }>('ai.mcp');
|
|
@@ -473,6 +526,26 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
473
526
|
return { clientId: value.clientId, newToken, userId: value.userId };
|
|
474
527
|
}
|
|
475
528
|
|
|
529
|
+
/**
|
|
530
|
+
* Whether the user of a grant (authorization code or refresh token) may use MCP — {@link checkMcpAccess} with the
|
|
531
|
+
* roles {@link loadUser} reads. A user it cannot load is checked with no roles: without `ai.mcp.roles` that admits as
|
|
532
|
+
* before (`/ai/mcp` then answers 401 for the token), with it the grant is refused.
|
|
533
|
+
*/
|
|
534
|
+
protected async grantMayUseMcp(userId: string): Promise<boolean> {
|
|
535
|
+
const user = (await this.loadUser(userId)) ?? { id: userId, roles: [] };
|
|
536
|
+
return this.checkMcpAccess(user);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Delete a refresh token, e.g. the one a rotation issued for a user who may no longer use MCP. */
|
|
540
|
+
protected async revokeRefreshToken(token: string): Promise<void> {
|
|
541
|
+
const sql = this.sqlStore(AI_MCP_OAUTH_REFRESH_TOKEN_MODEL);
|
|
542
|
+
if (sql) {
|
|
543
|
+
await sql.deleteOne({ token });
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
await this.db().collection(this.refreshCollection).deleteOne({ token });
|
|
547
|
+
}
|
|
548
|
+
|
|
476
549
|
/**
|
|
477
550
|
* Load the minimal user shape ({ id, roles }) for a verified OAuth subject from
|
|
478
551
|
* the `users` collection (read-only). Enough for tool role-filtering + ownership.
|
|
@@ -541,6 +614,11 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
541
614
|
'Authorization code is invalid, expired, already used or issued to another client',
|
|
542
615
|
);
|
|
543
616
|
}
|
|
617
|
+
// The right may have been withdrawn between the consent and this exchange
|
|
618
|
+
if (!(await this.grantMayUseMcp(stored.userId))) {
|
|
619
|
+
const { InvalidGrantError } = await this.loadOAuthErrors();
|
|
620
|
+
throw new InvalidGrantError('This account may not use MCP');
|
|
621
|
+
}
|
|
544
622
|
return {
|
|
545
623
|
access_token: this.signAccessToken(stored.userId, stored.clientId, accessTtlSeconds),
|
|
546
624
|
expires_in: accessTtlSeconds,
|
|
@@ -566,6 +644,13 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
566
644
|
const { InvalidGrantError } = await this.loadOAuthErrors();
|
|
567
645
|
throw new InvalidGrantError('Refresh token is invalid, already used or issued to another client');
|
|
568
646
|
}
|
|
647
|
+
// A grant issued before the right was withdrawn must not refresh forever: refuse, and revoke the token the
|
|
648
|
+
// rotation just issued, so the client is left with nothing to present again
|
|
649
|
+
if (!(await this.grantMayUseMcp(rotated.userId))) {
|
|
650
|
+
await this.revokeRefreshToken(rotated.newToken);
|
|
651
|
+
const { InvalidGrantError } = await this.loadOAuthErrors();
|
|
652
|
+
throw new InvalidGrantError('This account may not use MCP');
|
|
653
|
+
}
|
|
569
654
|
return {
|
|
570
655
|
access_token: this.signAccessToken(rotated.userId, rotated.clientId, accessTtlSeconds),
|
|
571
656
|
expires_in: accessTtlSeconds,
|
|
@@ -615,6 +700,10 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
615
700
|
protected async authorizeConsent(client: any, params: any, res: any): Promise<void> {
|
|
616
701
|
const req = res?.req;
|
|
617
702
|
const user = await this.consentUser(req);
|
|
703
|
+
// Before the form and before any decision: a user who may not use MCP gets neither a form nor a code
|
|
704
|
+
if (user && !(await this.checkMcpAccess(user, req))) {
|
|
705
|
+
return this.sendConsentNotice(res, this.consentRefusal(req));
|
|
706
|
+
}
|
|
618
707
|
const decision = req?.method === 'POST' ? req.body?.[MCP_OAUTH_CONSENT_DECISION_FIELD] : undefined;
|
|
619
708
|
|
|
620
709
|
let notice: IMcpOAuthConsentView['notice'];
|
|
@@ -659,9 +748,7 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
659
748
|
|
|
660
749
|
const view = this.buildConsentView(req, client, params, user, notice);
|
|
661
750
|
res.status(200);
|
|
662
|
-
|
|
663
|
-
res.setHeader(name, value);
|
|
664
|
-
}
|
|
751
|
+
setConsentPageHeaders(res, view.nonce);
|
|
665
752
|
res.send(this.renderConsentPage(view));
|
|
666
753
|
}
|
|
667
754
|
|
|
@@ -670,6 +757,83 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
670
757
|
return renderMcpOAuthConsentPage(view);
|
|
671
758
|
}
|
|
672
759
|
|
|
760
|
+
/**
|
|
761
|
+
* Answers the consent route with a notice page instead of the consent form — for a decision a project makes in its own
|
|
762
|
+
* {@link authorizeConsent} before calling `super`, e.g. while it takes no new MCP connections:
|
|
763
|
+
*
|
|
764
|
+
* ```typescript
|
|
765
|
+
* protected override async authorizeConsent(client: any, params: any, res: any): Promise<void> {
|
|
766
|
+
* if (await this.maintenance.isActive()) {
|
|
767
|
+
* return this.sendConsentNotice(res, { message: 'Please try again in an hour.', status: 503, title: 'Maintenance' });
|
|
768
|
+
* }
|
|
769
|
+
* return super.authorizeConsent(client, params, res);
|
|
770
|
+
* }
|
|
771
|
+
* ```
|
|
772
|
+
*
|
|
773
|
+
* The framework sets the status (default 403), a fresh nonce and the consent page's security headers (CSP,
|
|
774
|
+
* `frame-ancestors 'none'`, `X-Frame-Options`, `no-store`), so they keep receiving its fixes; the project supplies
|
|
775
|
+
* plain text. The page shows the signed-in account with "use another account" and issues nothing: no code, no
|
|
776
|
+
* redirect — the MCP client keeps waiting until the user signs in with another account or closes the window.
|
|
777
|
+
* Restyle it through {@link renderConsentNoticePage}.
|
|
778
|
+
*
|
|
779
|
+
* Not for deciding who may use MCP: a refusal here stops a new OAuth grant only, while `/ai/mcp` also accepts the
|
|
780
|
+
* user's own session token or JWT as bearer, which never passes `/authorize`. That rule is `ai.mcp.roles` or an
|
|
781
|
+
* overridden {@link mayUseMcp}, which the framework checks on `/ai/mcp`, here and on `/token` alike (and answers here
|
|
782
|
+
* with this page, worded by {@link consentRefusal}).
|
|
783
|
+
*/
|
|
784
|
+
protected async sendConsentNotice(res: any, notice: IMcpOAuthConsentNotice): Promise<void> {
|
|
785
|
+
const req = res?.req;
|
|
786
|
+
const user = await this.consentUser(req);
|
|
787
|
+
const requested = notice.status;
|
|
788
|
+
const status =
|
|
789
|
+
typeof requested === 'number' && Number.isInteger(requested) && requested >= 400 && requested <= 599
|
|
790
|
+
? requested
|
|
791
|
+
: 403;
|
|
792
|
+
if (requested !== undefined && status !== requested) {
|
|
793
|
+
this.logger.warn(`MCP OAuth consent notice: status ${requested} is not between 400 and 599, sending 403.`);
|
|
794
|
+
}
|
|
795
|
+
if (notice.link && !consentNoticeLinkHref(notice.link.href)) {
|
|
796
|
+
this.logger.warn(
|
|
797
|
+
'MCP OAuth consent notice: the link is neither an absolute http(s) URL nor a path on this origin, left out.',
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
const view: IMcpOAuthConsentNoticeView = {
|
|
801
|
+
appHost: this.consentAppHost(),
|
|
802
|
+
authBasePath: notice.switchAccount === false ? undefined : this.consentAuthBasePath(),
|
|
803
|
+
link: notice.link,
|
|
804
|
+
locale:
|
|
805
|
+
notice.locale === 'de' || notice.locale === 'en'
|
|
806
|
+
? notice.locale
|
|
807
|
+
: mcpOAuthConsentLocale(req?.headers?.['accept-language']),
|
|
808
|
+
message: (Array.isArray(notice.message) ? notice.message : [notice.message]).map((paragraph) =>
|
|
809
|
+
String(paragraph ?? ''),
|
|
810
|
+
),
|
|
811
|
+
nonce: randomBytes(16).toString('base64'),
|
|
812
|
+
title: String(notice.title ?? ''),
|
|
813
|
+
user: user ? { email: user.email, name: user.name } : undefined,
|
|
814
|
+
};
|
|
815
|
+
res.status(status);
|
|
816
|
+
setConsentPageHeaders(res, view.nonce);
|
|
817
|
+
res.send(this.renderConsentNoticePage(view));
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Renders the notice page of {@link sendConsentNotice}. Override to change its wording or look via
|
|
822
|
+
* `renderMcpOAuthConsentNoticePage(view, { texts, styles })`; keep every dynamic value escaped.
|
|
823
|
+
*/
|
|
824
|
+
protected renderConsentNoticePage(view: IMcpOAuthConsentNoticeView): string {
|
|
825
|
+
return renderMcpOAuthConsentNoticePage(view);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* The notice the consent route answers a signed-in user {@link mayUseMcp} refuses with (403). Override to change its
|
|
830
|
+
* wording; its look changes through {@link renderConsentNoticePage}.
|
|
831
|
+
*/
|
|
832
|
+
protected consentRefusal(req: any): IMcpOAuthConsentNotice {
|
|
833
|
+
const locale = mcpOAuthConsentLocale(req?.headers?.['accept-language']);
|
|
834
|
+
return { ...mcpOAuthConsentRefusalTexts(locale), locale, status: 403 };
|
|
835
|
+
}
|
|
836
|
+
|
|
673
837
|
/**
|
|
674
838
|
* The user the consent is given for: whoever the Better-Auth middleware put on the request — or,
|
|
675
839
|
* where it did not run, the session the request carries. Nest registers that middleware below a
|
|
@@ -677,9 +841,18 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
677
841
|
* sees `/authorize`; the session is then resolved the way the middleware resolves it (bearer, then
|
|
678
842
|
* session cookie). Never an API token — those carry their own, narrower rights.
|
|
679
843
|
*/
|
|
680
|
-
protected async consentUser(
|
|
844
|
+
protected async consentUser(
|
|
845
|
+
req: any,
|
|
846
|
+
): Promise<{ email?: string; id: string; name?: string; roles?: string[] } | undefined> {
|
|
681
847
|
const toConsentUser = (user: any) =>
|
|
682
|
-
user?.id && !getApiTokenContext(user)
|
|
848
|
+
user?.id && !getApiTokenContext(user)
|
|
849
|
+
? {
|
|
850
|
+
email: user.email,
|
|
851
|
+
id: String(user.id),
|
|
852
|
+
name: user.name,
|
|
853
|
+
roles: Array.isArray(user.roles) ? user.roles : undefined,
|
|
854
|
+
}
|
|
855
|
+
: undefined;
|
|
683
856
|
if (req?.user?.id) {
|
|
684
857
|
return toConsentUser(req.user);
|
|
685
858
|
}
|
|
@@ -722,9 +895,7 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
722
895
|
}
|
|
723
896
|
return {
|
|
724
897
|
appHost: this.consentAppHost(),
|
|
725
|
-
authBasePath:
|
|
726
|
-
? getMountedMcpOAuth()?.authBasePath || ConfigService.get<string>('betterAuth.basePath') || '/iam'
|
|
727
|
-
: undefined,
|
|
898
|
+
authBasePath: this.consentAuthBasePath(),
|
|
728
899
|
client: { id: String(client.client_id), name: client.client_name },
|
|
729
900
|
csrfToken: user
|
|
730
901
|
? this.signConsentToken({
|
|
@@ -744,6 +915,13 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
744
915
|
};
|
|
745
916
|
}
|
|
746
917
|
|
|
918
|
+
/** Better-Auth's base path for the consent pages' sign-in and sign-out; `undefined` when Better-Auth is not active. */
|
|
919
|
+
protected consentAuthBasePath(): string | undefined {
|
|
920
|
+
return getBetterAuthTokenService()
|
|
921
|
+
? getMountedMcpOAuth()?.authBasePath || ConfigService.get<string>('betterAuth.basePath') || '/iam'
|
|
922
|
+
: undefined;
|
|
923
|
+
}
|
|
924
|
+
|
|
747
925
|
/** The host users know the application by: the app's, else the server's. */
|
|
748
926
|
protected consentAppHost(): string {
|
|
749
927
|
for (const url of [resolveAppUrlFromConfig(ConfigService), getMountedMcpOAuth()?.baseUrl]) {
|
|
@@ -924,3 +1102,39 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
|
|
|
924
1102
|
return store && !store.capabilities.mongoosePopulate ? store : undefined;
|
|
925
1103
|
}
|
|
926
1104
|
}
|
|
1105
|
+
|
|
1106
|
+
/** Sets the consent pages' security headers on a response — the one place both pages get them from. */
|
|
1107
|
+
function setConsentPageHeaders(res: any, nonce: string): void {
|
|
1108
|
+
for (const [name, value] of Object.entries(mcpOAuthConsentHeaders(nonce))) {
|
|
1109
|
+
res.setHeader(name, value);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* `ai.mcp.roles`, resolved: `undefined` when unset, else the role names (an array, or a comma-separated string as an
|
|
1115
|
+
* `NSC__AI__MCP__ROLES` variable delivers it). Throws on a value that names no role or a system role: a
|
|
1116
|
+
* misconfiguration of an access rule must stop the boot, never read as "everyone may".
|
|
1117
|
+
*/
|
|
1118
|
+
function resolveMcpAccessRoles(mcp: unknown): string[] | undefined {
|
|
1119
|
+
const value = mcp && typeof mcp === 'object' ? (mcp as { roles?: unknown }).roles : undefined;
|
|
1120
|
+
if (value === undefined || value === null) {
|
|
1121
|
+
return undefined;
|
|
1122
|
+
}
|
|
1123
|
+
const entries: unknown[] | undefined =
|
|
1124
|
+
typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : undefined;
|
|
1125
|
+
const roles = entries?.map((role) => (typeof role === 'string' ? role.trim() : ''));
|
|
1126
|
+
if (!roles?.length || roles.some((role) => !role)) {
|
|
1127
|
+
throw new Error(
|
|
1128
|
+
'ai.mcp.roles must name at least one role (an array of role names, or a comma-separated string) and no ' +
|
|
1129
|
+
'empty entry. Remove it to let every signed-in user use MCP.',
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
1132
|
+
const systemRoles = roles.filter((role) => looksLikeSystemRole(role));
|
|
1133
|
+
if (systemRoles.length) {
|
|
1134
|
+
throw new Error(
|
|
1135
|
+
`ai.mcp.roles names system roles (${systemRoles.join(', ')}), which no user holds. List real roles, remove ` +
|
|
1136
|
+
'ai.mcp.roles to let every signed-in user use MCP, or override mayUseMcp() for any other rule.',
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
return roles;
|
|
1140
|
+
}
|