@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
@@ -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
- for (const [name, value] of Object.entries(mcpOAuthConsentHeaders(view.nonce))) {
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(req: any): Promise<{ email?: string; id: string; name?: string } | undefined> {
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) ? { email: user.email, id: String(user.id), name: user.name } : undefined;
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: getBetterAuthTokenService()
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
+ }