@lenne.tech/nest-server 12.9.4 → 12.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/.claude/rules/configurable-features.md +4 -0
  2. package/.claude/rules/package-management.md +29 -5
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +8 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  22. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  23. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  24. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  25. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  26. package/dist/core/common/services/request-context.service.d.ts +2 -0
  27. package/dist/core/common/services/request-context.service.js +3 -0
  28. package/dist/core/common/services/request-context.service.js.map +1 -1
  29. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  30. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  31. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  32. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  33. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  34. package/dist/core/modules/ai/core-ai.module.js +2 -0
  35. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  36. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  37. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  38. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  39. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  40. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  41. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  42. package/dist/core/modules/ai/index.d.ts +8 -0
  43. package/dist/core/modules/ai/index.js +8 -0
  44. package/dist/core/modules/ai/index.js.map +1 -1
  45. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  46. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  47. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  48. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  49. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  50. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  51. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  52. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  53. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  54. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  57. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  58. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  59. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  60. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  61. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  62. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  63. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  64. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  65. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  66. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  67. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  68. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  69. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  70. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  71. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  72. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  73. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  74. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  75. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  76. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  77. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  78. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  79. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  80. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  81. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  82. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  83. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  84. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  85. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  86. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  87. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  88. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  89. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  90. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  91. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  92. package/dist/core.module.js +2 -1
  93. package/dist/core.module.js.map +1 -1
  94. package/dist/index.d.ts +1 -0
  95. package/dist/index.js +1 -0
  96. package/dist/index.js.map +1 -1
  97. package/dist/types/graphql-upload.d.ts +34 -2
  98. package/docs/REQUEST-LIFECYCLE.md +46 -9
  99. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  100. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  101. package/package.json +46 -21
  102. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  103. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  104. package/src/core/common/helpers/context.helper.ts +14 -0
  105. package/src/core/common/helpers/decorator.helper.ts +5 -0
  106. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  107. package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
  108. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  109. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  110. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  111. package/src/core/common/services/request-context.service.ts +11 -0
  112. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  113. package/src/core/modules/ai/README.md +101 -0
  114. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  115. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  116. package/src/core/modules/ai/core-ai.module.ts +3 -0
  117. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  118. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  119. package/src/core/modules/ai/index.ts +8 -0
  120. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  121. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  122. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  123. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  124. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  125. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  126. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  127. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  128. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  129. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  130. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  131. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  132. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  133. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  134. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  135. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  136. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  137. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  138. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  139. package/src/core/modules/better-auth/README.md +204 -0
  140. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  141. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  142. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  143. package/src/core.module.ts +5 -1
  144. package/src/index.ts +1 -0
  145. package/src/types/graphql-upload.d.ts +34 -2
@@ -1,6 +1,5 @@
1
1
  import { BadGatewayException, Logger, ServiceUnavailableException } from '@nestjs/common';
2
2
 
3
- import { ConfigService } from '../../../common/services/config.service.js';
4
3
  import { ErrorCode } from '../../error-code/index.js';
5
4
  import {
6
5
  ILlmProvider,
@@ -12,6 +11,7 @@ import {
12
11
  LlmUsage,
13
12
  } from '../interfaces/llm-provider.interface.js';
14
13
  import { ResolvedAiConnection } from '../interfaces/resolved-ai-connection.interface.js';
14
+ import { aiEgressHostCandidates, normaliseAiEgressHost, resolveAiEgressAllowlist } from './ai-egress.helper.js';
15
15
 
16
16
  /**
17
17
  * Provider for OpenAI-compatible chat-completions endpoints.
@@ -302,11 +302,7 @@ export class OpenAiCompatibleProvider implements ILlmProvider {
302
302
  // omits the default port, so a conscientious `llm.example.com:443` entry would
303
303
  // otherwise never match `https://llm.example.com/` — a lockout whose only symptom is
304
304
  // a WARN and "the AI stopped working". Nothing here widens the set of reachable hosts.
305
- const defaultPort = parsed.protocol === 'https:' ? '443' : parsed.protocol === 'http:' ? '80' : '';
306
- const candidates = [parsed.host, parsed.hostname];
307
- if (defaultPort && parsed.host === parsed.hostname) {
308
- candidates.push(`${parsed.hostname}:${defaultPort}`);
309
- }
305
+ const candidates = aiEgressHostCandidates(parsed);
310
306
  if (!candidates.map((candidate) => this.normaliseHostEntry(candidate)).some((c) => allowedHosts.includes(c))) {
311
307
  this.logger.warn(
312
308
  `AI connection "${this.connection.name}" host "${parsed.host}" is not in ai.allowedBaseUrlHosts`,
@@ -385,19 +381,8 @@ export class OpenAiCompatibleProvider implements ILlmProvider {
385
381
  * decision, a malformed value is an accident nobody is told about.
386
382
  */
387
383
  protected resolveAllowedBaseUrlHosts(): string[] {
388
- const configured = ConfigService.get<unknown>('ai.allowedBaseUrlHosts');
389
- if (configured === undefined || configured === null) {
390
- return [];
391
- }
392
- const entries = typeof configured === 'string' ? configured.split(',') : configured;
393
- if (!Array.isArray(entries)) {
394
- this.logger.error(
395
- `ai.allowedBaseUrlHosts is a ${typeof configured} and carries no hostnames — the SSRF egress ` +
396
- 'allowlist is NOT active. Use an array or a comma-separated string.',
397
- );
398
- return [];
399
- }
400
- return entries.map((host) => this.normaliseHostEntry(String(host))).filter(Boolean);
384
+ // One implementation for every AI egress path (the AI SDK transport uses it too) — see ai-egress.helper
385
+ return resolveAiEgressAllowlist(this.logger);
401
386
  }
402
387
 
403
388
  /**
@@ -409,10 +394,7 @@ export class OpenAiCompatibleProvider implements ILlmProvider {
409
394
  * produced a confusing refusal — never protection.
410
395
  */
411
396
  protected normaliseHostEntry(value: string): string {
412
- return value
413
- .trim()
414
- .toLowerCase()
415
- .replace(/\.(?=$|:)/, '');
397
+ return normaliseAiEgressHost(value);
416
398
  }
417
399
 
418
400
  /**
@@ -0,0 +1,170 @@
1
+ import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+
4
+ import { RoleEnum } from '../../../common/enums/role.enum.js';
5
+ import { ConfigService } from '../../../common/services/config.service.js';
6
+ import { RequestContext } from '../../../common/services/request-context.service.js';
7
+ import { mergeRolesMetadata } from '../../tenant/core-tenant.helpers.js';
8
+ import { AI_AGENT_FUNCTION_METADATA } from '../core-ai.constants.js';
9
+ import type { IAiAgentFunctionOptions } from '../decorators/ai-agent-function.decorator.js';
10
+ import type { AiToolContext, IAiTool } from '../interfaces/ai-tool.interface.js';
11
+ import { AiSdkPackageError, loadNestjsAi } from '../providers/ai-sdk.packages.js';
12
+ import { AiToolRegistry } from '../tools/ai-tool.registry.js';
13
+
14
+ /** `ai.agentFunctions` once resolved: which agent functions to offer. */
15
+ export interface ResolvedAiAgentFunctionsConfig {
16
+ exclude: string[];
17
+ include?: string[];
18
+ }
19
+
20
+ /**
21
+ * `ai.agentFunctions` (boolean shorthand, presence implies enabled): `undefined` = off.
22
+ */
23
+ export function resolveAiAgentFunctionsConfig(value: unknown): ResolvedAiAgentFunctionsConfig | undefined {
24
+ if (value === undefined || value === null || value === false) {
25
+ return undefined;
26
+ }
27
+ if (value === true) {
28
+ return { exclude: [] };
29
+ }
30
+ if (typeof value !== 'object' || (value as { enabled?: unknown }).enabled === false) {
31
+ return undefined;
32
+ }
33
+ const { exclude, include } = value as { exclude?: unknown; include?: unknown };
34
+ const names = (list: unknown) =>
35
+ Array.isArray(list) ? list.filter((name): name is string => typeof name === 'string') : undefined;
36
+ return { exclude: names(exclude) ?? [], ...(names(include) && { include: names(include) }) };
37
+ }
38
+
39
+ /** What the bridge reads of a `@nestjs/ai` `AiToolEntry` (structural — the package's own type stays its own). */
40
+ interface AgentFunctionEntry {
41
+ description?: string;
42
+ host: Function;
43
+ inputSchema: { jsonSchema: PromiseLike<Record<string, any>> | Record<string, any> };
44
+ name: string;
45
+ scopes?: string[];
46
+ where: string;
47
+ }
48
+
49
+ interface AiToolsLike {
50
+ call(name: string, input: unknown, caller?: { request?: unknown }): Promise<unknown>;
51
+ readonly tools: ReadonlyMap<string, AgentFunctionEntry>;
52
+ }
53
+
54
+ /**
55
+ * Offers the application's `@nestjs/ai` agent functions (`@AgentFunction()` methods) as tools of the AI assistant and
56
+ * its MCP server (12.10.0, nestjs-ai plan §3). Opt-in through `ai.agentFunctions`; inert otherwise — `@nestjs/ai` is
57
+ * not even loaded.
58
+ *
59
+ * ORDER OF GATES. Every gate of the framework runs first, in `CoreAiService` / `CoreAiMcpService`: the role filter
60
+ * (`roles`), tool policies and grants, `authorize()`, confirmation (`mutating` / `destructive`), plan mode, budgets.
61
+ * Only then `execute()` hands the call to `@nestjs/ai`'s own pipeline — its input validation, `scopes` and the
62
+ * application's enhancers (our guards included, with the context type `'ai'`) — with the HTTP request of the run as the
63
+ * caller, so the method's `@Roles()` is decided on the user exactly as over HTTP. A run without a request (none today)
64
+ * would be anonymous to those guards.
65
+ *
66
+ * FAIL CLOSED. An agent function that needs `scopes` is not offered (the framework has no scopes for a chat user, and
67
+ * offering it would only produce refusals); one whose name is already a registered tool stops the boot.
68
+ */
69
+ @Injectable()
70
+ export class CoreAiAgentFunctionBridge implements OnApplicationBootstrap {
71
+ protected readonly logger = new Logger(CoreAiAgentFunctionBridge.name);
72
+
73
+ constructor(
74
+ protected readonly registry: AiToolRegistry,
75
+ protected readonly moduleRef: ModuleRef,
76
+ ) {}
77
+
78
+ async onApplicationBootstrap(): Promise<void> {
79
+ const ai = ConfigService.configFastButReadOnly?.ai;
80
+ const config = resolveAiAgentFunctionsConfig(ai && typeof ai === 'object' ? ai.agentFunctions : undefined);
81
+ if (!config) {
82
+ return;
83
+ }
84
+ const nestjsAi = await loadNestjsAi('ai.agentFunctions');
85
+ let aiTools: AiToolsLike | undefined;
86
+ try {
87
+ aiTools = this.moduleRef.get(nestjsAi.AiTools, { strict: false });
88
+ } catch {
89
+ aiTools = undefined;
90
+ }
91
+ if (!aiTools) {
92
+ throw new AiSdkPackageError(
93
+ 'ai.agentFunctions is set, but the application imports no AiModule.forRoot() of @nestjs/ai, so there are no ' +
94
+ 'agent functions to offer.',
95
+ );
96
+ }
97
+ const offered: string[] = [];
98
+ for (const entry of aiTools.tools.values()) {
99
+ if (config.include && !config.include.includes(entry.name)) {
100
+ continue;
101
+ }
102
+ if (config.exclude.includes(entry.name)) {
103
+ continue;
104
+ }
105
+ const tool = await this.toTool(entry, aiTools);
106
+ if (tool) {
107
+ this.registry.register(tool);
108
+ offered.push(tool.name);
109
+ }
110
+ }
111
+ this.logger.log(`Agent functions offered as AI tools: ${offered.length ? offered.join(', ') : 'none'}`);
112
+ }
113
+
114
+ /**
115
+ * One agent function as an {@link IAiTool}; `undefined` when it cannot be offered safely. Overridable — an override
116
+ * that widens what is offered owns that decision.
117
+ */
118
+ protected async toTool(entry: AgentFunctionEntry, aiTools: AiToolsLike): Promise<IAiTool | undefined> {
119
+ if (this.registry.get(entry.name)) {
120
+ throw new AiSdkPackageError(
121
+ `The agent function "${entry.name}" (${entry.where}) has the name of a registered AI tool. Give it another ` +
122
+ '{ name }, or leave it out with ai.agentFunctions.exclude.',
123
+ );
124
+ }
125
+ if (entry.scopes?.length) {
126
+ this.logger.warn(
127
+ `Agent function "${entry.name}" (${entry.where}) requires the scopes ${entry.scopes.join(', ')}; the AI ` +
128
+ 'assistant calls with none, so it is not offered.',
129
+ );
130
+ return undefined;
131
+ }
132
+ const methodName = entry.where.slice(entry.where.lastIndexOf('.') + 1);
133
+ const method = (entry.host as { prototype?: Record<string, unknown> }).prototype?.[methodName];
134
+ if (typeof method !== 'function') {
135
+ this.logger.error(`Agent function "${entry.name}": ${entry.where} is no method of its provider; not offered.`);
136
+ return undefined;
137
+ }
138
+ const extras: IAiAgentFunctionOptions = Reflect.getMetadata(AI_AGENT_FUNCTION_METADATA, method) ?? {};
139
+ const methodRoles = mergeRolesMetadata([
140
+ Reflect.getMetadata('roles', method) as string[] | undefined,
141
+ Reflect.getMetadata('roles', entry.host) as string[] | undefined,
142
+ ]).filter(Boolean);
143
+ const roles = extras.roles?.length ? [...extras.roles] : methodRoles.length ? methodRoles : [RoleEnum.S_USER];
144
+ const parameters = await entry.inputSchema.jsonSchema;
145
+ const authorize = extras.authorize;
146
+ const instance = authorize ? this.moduleRef.get(entry.host as any, { strict: false }) : undefined;
147
+ const name = entry.name;
148
+
149
+ return {
150
+ ...(authorize && {
151
+ authorize: async (args: Record<string, any>, context: AiToolContext) => authorize.call(instance, args, context),
152
+ }),
153
+ description: entry.description ?? `Agent function ${name}`,
154
+ destructive: extras.destructive === true,
155
+ execute: async (args: Record<string, any>) => {
156
+ const request = RequestContext.getRequest();
157
+ try {
158
+ return await aiTools.call(name, args ?? {}, request ? { request } : {});
159
+ } catch (error) {
160
+ // AiToolError: the message is what @nestjs/ai lets a model read (an HttpException's, else a generic one)
161
+ throw new Error((error as Error)?.message || `Agent function "${name}" failed`, { cause: error });
162
+ }
163
+ },
164
+ mutating: extras.mutating === true || extras.destructive === true,
165
+ name,
166
+ parameters: parameters && typeof parameters === 'object' ? parameters : { properties: {}, type: 'object' },
167
+ roles,
168
+ };
169
+ }
170
+ }
@@ -6,6 +6,8 @@ import type { Connection } from 'mongoose';
6
6
 
7
7
  import { looksLikeSystemRole } from '../../../common/enums/role.enum.js';
8
8
  import { isLocalEnv, resolveAppUrlFromConfig } from '../../../common/helpers/cookies.helper.js';
9
+ import { MCP_VERIFIED_USER } from '../../../common/helpers/execution-context-request.helper.js';
10
+ import { toVerifiedAiUser } from '../helpers/ai-verified-user.helper.js';
9
11
  import type { DataStore } from '../../../common/persistence/data-store.interface.js';
10
12
  import { getModelStore } from '../../../common/persistence/persistence-runtime.registry.js';
11
13
  import { ConfigService } from '../../../common/services/config.service.js';
@@ -93,7 +95,25 @@ export interface AiMcpOAuthClient {
93
95
  /**
94
96
  * Decoded MCP access-token payload.
95
97
  */
98
+ /**
99
+ * What {@link CoreAiMcpOAuthService.createMcpTokenVerifier} returns for an accepted token: the SDK's `AuthInfo` shape
100
+ * (declared here — the core imports neither MCP package), `resource` set so `@nestjs/mcp` accepts the audience.
101
+ */
102
+ export interface IMcpVerifiedAuthInfo {
103
+ clientId: string;
104
+ expiresAt: number;
105
+ extra: Record<PropertyKey, unknown>;
106
+ resource: string;
107
+ scopes: string[];
108
+ token: string;
109
+ }
110
+
96
111
  export interface AiMcpAccessTokenPayload {
112
+ /**
113
+ * The resource (RFC 8707 audience) the token was issued for (12.10.0). A token without one was issued before
114
+ * 12.10.0 and is accepted at `/ai/mcp` only (`acceptsAudience()`).
115
+ */
116
+ aud?: string;
97
117
  cid: string;
98
118
  exp: number;
99
119
  sub: string;
@@ -118,7 +138,7 @@ export interface IAiMcpOAuthConsentBinding {
118
138
  * Set by the provider's `authorize` (outside the overridable {@link CoreAiMcpOAuthService.authorizeConsent}),
119
139
  * read by {@link assertCodeIssuanceAllowed}.
120
140
  */
121
- const authorizeRequest = new AsyncLocalStorage<{ method: string }>();
141
+ const authorizeRequest = new AsyncLocalStorage<{ method: string; resource?: string }>();
122
142
 
123
143
  /**
124
144
  * Refuses to issue an authorization code while answering a GET to `/authorize`.
@@ -131,6 +151,23 @@ const authorizeRequest = new AsyncLocalStorage<{ method: string }>();
131
151
  * `/authorize` handler (e.g. by a consent route of the project's own) is not affected; that route
132
152
  * carries the same obligation.
133
153
  */
154
+ /**
155
+ * A resource indicator (RFC 8707) as this server compares it: an absolute URL without fragment, as `URL.href` spells
156
+ * it. `undefined` for anything that is no absolute URL.
157
+ */
158
+ export function normalizeMcpResource(value: unknown): string | undefined {
159
+ if (value === undefined || value === null || value === '') {
160
+ return undefined;
161
+ }
162
+ try {
163
+ const url = new URL(value instanceof URL ? value.href : String(value));
164
+ url.hash = '';
165
+ return url.href;
166
+ } catch {
167
+ return undefined;
168
+ }
169
+ }
170
+
134
171
  function assertCodeIssuanceAllowed(): void {
135
172
  const request = authorizeRequest.getStore();
136
173
  if (request && request.method !== 'POST') {
@@ -301,8 +338,9 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
301
338
  /**
302
339
  * Sign an access token for a user + client with a TTL (seconds).
303
340
  */
304
- signAccessToken(userId: string, clientId: string, ttlSeconds = 3600): string {
341
+ signAccessToken(userId: string, clientId: string, ttlSeconds = 3600, resource?: string): string {
305
342
  const payload: AiMcpAccessTokenPayload = {
343
+ ...(resource ? { aud: resource } : {}),
306
344
  cid: clientId,
307
345
  exp: Math.floor(Date.now() / 1000) + ttlSeconds,
308
346
  sub: userId,
@@ -338,6 +376,126 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
338
376
  }
339
377
  }
340
378
 
379
+ /**
380
+ * A token verifier for `@nestjs/mcp` (12.10.0, nestjs-ai plan §4): makes this authorization server the identity
381
+ * provider of a project's own `McpModule` endpoint, next to `/ai/mcp`.
382
+ *
383
+ * ```typescript
384
+ * McpModule.forRootAsync({
385
+ * inject: [CoreAiMcpOAuthService],
386
+ * useFactory: (oauth: CoreAiMcpOAuthService) => ({
387
+ * name: 'my-api', version: '1.0.0',
388
+ * auth: {
389
+ * authorizationServers: ['https://api.example.com'],
390
+ * resource: 'https://api.example.com/mcp',
391
+ * verifier: oauth.createMcpTokenVerifier({ resource: 'https://api.example.com/mcp' }),
392
+ * },
393
+ * }),
394
+ * })
395
+ * ```
396
+ *
397
+ * A token is accepted only when its signature and expiry hold, its user still exists and may use MCP
398
+ * (`ai.mcp.roles` / {@link mayUseMcp}, decided on every request as on `/ai/mcp`). The user then reaches the tool's
399
+ * guards as `request.user` — through a key only this verifier sets (`MCP_VERIFIED_USER`), so a claim another
400
+ * verifier copies into `extra` never names the caller. Refusals answer `null` (401).
401
+ *
402
+ * AUDIENCE (RFC 8707): the resource is registered with this authorization server, so a client that names it as
403
+ * `resource` at `/authorize` / `/token` gets a token bound to it — and this verifier accepts only such tokens. A
404
+ * token issued for `/ai/mcp`, or one issued before 12.10.0 (no audience), is refused here.
405
+ *
406
+ * @throws when `ai.mcp.oauth` is off (no token can be valid) or `resource` is no absolute URL — at boot, not per call.
407
+ */
408
+ createMcpTokenVerifier(options: { resource: string }): {
409
+ verifyAccessToken(token: string): Promise<IMcpVerifiedAuthInfo | null>;
410
+ } {
411
+ if (!this.oauthEnabled()) {
412
+ throw new Error('createMcpTokenVerifier() needs ai.mcp.oauth: true — without it this server issues no tokens.');
413
+ }
414
+ if (typeof options?.resource !== 'string' || !URL.canParse(options.resource)) {
415
+ throw new Error(
416
+ `createMcpTokenVerifier(): resource must be the absolute URL of the MCP endpoint, got ${options?.resource}`,
417
+ );
418
+ }
419
+ const resource = normalizeMcpResource(options.resource);
420
+ // Tokens for this resource are issued from now on (RFC 8707 `resource` at /authorize and /token)
421
+ this.registeredResources.add(resource);
422
+ return {
423
+ verifyAccessToken: async (token: string) => {
424
+ const payload = this.verifyAccessToken(token);
425
+ // The token's audience must be THIS resource; one issued before 12.10.0 (no audience) is valid at /ai/mcp only
426
+ if (!payload?.sub || !this.acceptsAudience(payload, resource)) {
427
+ return null;
428
+ }
429
+ const user = await this.loadUser(payload.sub);
430
+ if (!user || !(await this.checkMcpAccess(user))) {
431
+ return null;
432
+ }
433
+ const verifiedUser = toVerifiedAiUser(user);
434
+ return {
435
+ clientId: payload.cid,
436
+ expiresAt: payload.exp,
437
+ extra: { userId: payload.sub, [MCP_VERIFIED_USER]: verifiedUser },
438
+ resource,
439
+ scopes: [],
440
+ token,
441
+ };
442
+ },
443
+ };
444
+ }
445
+
446
+ /** Resources registered by {@link createMcpTokenVerifier}, besides `/ai/mcp` (normalised). */
447
+ protected readonly registeredResources = new Set<string>();
448
+
449
+ /** The `/ai/mcp` resource: the one the mounted OAuth endpoints describe; `undefined` while nothing is mounted. */
450
+ mcpResource(): string | undefined {
451
+ return normalizeMcpResource(getMountedMcpOAuth()?.resourceUrl);
452
+ }
453
+
454
+ /**
455
+ * The resource a grant is issued for (RFC 8707): the requested one when this server serves it, `/ai/mcp`'s when the
456
+ * client names none (every client before 2025-06-18 of the MCP spec). An unknown resource is refused with
457
+ * `invalid_target` — a token for an endpoint this server does not protect is a token for somebody else.
458
+ */
459
+ async resolveRequestedResource(requested: unknown): Promise<string | undefined> {
460
+ if (requested === undefined || requested === null || requested === '') {
461
+ return this.mcpResource();
462
+ }
463
+ const resource = normalizeMcpResource(requested);
464
+ if (resource && (resource === this.mcpResource() || this.registeredResources.has(resource))) {
465
+ return resource;
466
+ }
467
+ const { InvalidTargetError } = await this.loadOAuthErrors();
468
+ throw new InvalidTargetError('The requested resource is not served by this authorization server');
469
+ }
470
+
471
+ /**
472
+ * Whether an access token may be used at `/ai/mcp` (12.10.0): one issued for it, or one from before 12.10.0 (no
473
+ * audience). A token bound to another resource — a project's `@nestjs/mcp` endpoint — is refused here.
474
+ */
475
+ acceptsAudienceAtMcp(payload: AiMcpAccessTokenPayload): boolean {
476
+ // A token from before 12.10.0 (no audience) stays valid here, and only here
477
+ if (!payload.aud) {
478
+ return true;
479
+ }
480
+ const mcp = this.mcpResource();
481
+ return !!mcp && normalizeMcpResource(payload.aud) === mcp;
482
+ }
483
+
484
+ /**
485
+ * Whether an access token may be used at `resource` (12.10.0): its audience must be that resource. A token without
486
+ * one was issued before 12.10.0 and is accepted at `/ai/mcp` only ({@link acceptsAudienceAtMcp}), never elsewhere.
487
+ */
488
+ acceptsAudience(payload: AiMcpAccessTokenPayload, resource: string | undefined): boolean {
489
+ const target = normalizeMcpResource(resource);
490
+ if (!target) {
491
+ return false;
492
+ }
493
+ if (!payload.aud) {
494
+ return target === this.mcpResource();
495
+ }
496
+ return normalizeMcpResource(payload.aud) === target;
497
+ }
498
+
341
499
  /**
342
500
  * Verify a PKCE code verifier against a stored S256 challenge.
343
501
  */
@@ -415,14 +573,17 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
415
573
  */
416
574
  async saveAuthorizationCode(
417
575
  code: string,
418
- data: { clientId: string; codeChallenge: string; userId: string },
576
+ data: { clientId: string; codeChallenge: string; resource?: string; userId: string },
419
577
  ): Promise<void> {
420
578
  assertCodeIssuanceAllowed();
579
+ // The resource /authorize resolved (RFC 8707) — also for an overridden authorizeConsent() that does not pass it
580
+ const resource = data.resource ?? authorizeRequest.getStore()?.resource;
421
581
  const record = {
422
582
  clientId: data.clientId,
423
583
  code,
424
584
  codeChallenge: data.codeChallenge,
425
585
  createdAt: new Date(),
586
+ ...(resource ? { resource } : {}),
426
587
  userId: data.userId,
427
588
  };
428
589
  const sql = this.sqlStore(AI_MCP_OAUTH_CODE_MODEL);
@@ -439,7 +600,7 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
439
600
  */
440
601
  async getAuthorizationCode(
441
602
  code: string,
442
- ): Promise<{ clientId: string; codeChallenge: string; userId: string } | null> {
603
+ ): Promise<{ clientId: string; codeChallenge: string; resource?: string; userId: string } | null> {
443
604
  const sql = this.sqlStore(AI_MCP_OAUTH_CODE_MODEL);
444
605
  const doc = sql ? await sql.findOne({ code }) : await this.db().collection(this.codesCollection).findOne({ code });
445
606
  return this.liveCode(doc);
@@ -455,7 +616,7 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
455
616
  async consumeAuthorizationCode(
456
617
  code: string,
457
618
  clientId?: string,
458
- ): Promise<{ clientId: string; codeChallenge: string; userId: string } | null> {
619
+ ): Promise<{ clientId: string; codeChallenge: string; resource?: string; userId: string } | null> {
459
620
  const filter = clientId === undefined ? { code } : { clientId, code };
460
621
  const sql = this.sqlStore(AI_MCP_OAUTH_CODE_MODEL);
461
622
  // Deleted whatever its age: an expired code is refused AND gone, so it can never be presented again
@@ -471,7 +632,7 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
471
632
  * MongoDB's TTL index removes an expired code only eventually (its monitor runs about once a minute, later under
472
633
  * load), and a SQL table has no TTL at all — the sweeper only keeps the table small.
473
634
  */
474
- protected liveCode(doc: any): { clientId: string; codeChallenge: string; userId: string } | null {
635
+ protected liveCode(doc: any): { clientId: string; codeChallenge: string; resource?: string; userId: string } | null {
475
636
  if (!doc) {
476
637
  return null;
477
638
  }
@@ -479,15 +640,20 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
479
640
  if (!(Date.now() - createdAt <= AI_MCP_OAUTH_CODE_TTL_SECONDS * 1000)) {
480
641
  return null;
481
642
  }
482
- return { clientId: doc.clientId, codeChallenge: doc.codeChallenge, userId: doc.userId };
643
+ return {
644
+ clientId: doc.clientId,
645
+ codeChallenge: doc.codeChallenge,
646
+ ...(doc.resource ? { resource: doc.resource } : {}),
647
+ userId: doc.userId,
648
+ };
483
649
  }
484
650
 
485
651
  /**
486
652
  * Issue a refresh token for a user + client.
487
653
  */
488
- async issueRefreshToken(userId: string, clientId: string): Promise<string> {
654
+ async issueRefreshToken(userId: string, clientId: string, resource?: string): Promise<string> {
489
655
  const token = this.generateId();
490
- const record = { clientId, createdAt: new Date(), token, userId };
656
+ const record = { clientId, createdAt: new Date(), ...(resource ? { resource } : {}), token, userId };
491
657
  const sql = this.sqlStore(AI_MCP_OAUTH_REFRESH_TOKEN_MODEL);
492
658
  if (sql) {
493
659
  await sql.insert(record);
@@ -510,11 +676,26 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
510
676
  async rotateRefreshToken(
511
677
  token: string,
512
678
  clientId: string,
513
- ): Promise<{ clientId: string; newToken: string; userId: string } | null> {
679
+ requestedResource?: string,
680
+ ): Promise<{ clientId: string; newToken: string; resource?: string; userId: string } | null> {
514
681
  if (!token || !clientId) {
515
682
  return null;
516
683
  }
517
684
  const sql = this.sqlStore(AI_MCP_OAUTH_REFRESH_TOKEN_MODEL);
685
+ // RFC 8707: a refresh token issues tokens for the resource its grant was bound to — a token from before 12.10.0
686
+ // (none) for /ai/mcp only. Checked BEFORE the rotation, so a request for another resource costs the client nothing.
687
+ const current: any = sql
688
+ ? await sql.findOne({ clientId, token })
689
+ : await this.db().collection(this.refreshCollection).findOne({ clientId, token });
690
+ if (!current) {
691
+ return null;
692
+ }
693
+ const resource = normalizeMcpResource(current.resource) ?? this.mcpResource();
694
+ const requested = normalizeMcpResource(requestedResource);
695
+ if (requested && requested !== resource) {
696
+ const { InvalidTargetError } = await this.loadOAuthErrors();
697
+ throw new InvalidTargetError('This refresh token was not issued for the requested resource');
698
+ }
518
699
  const doc = sql
519
700
  ? await sql.deleteOne({ clientId, token })
520
701
  : await this.db().collection(this.refreshCollection).findOneAndDelete({ clientId, token });
@@ -522,8 +703,8 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
522
703
  if (!value) {
523
704
  return null;
524
705
  }
525
- const newToken = await this.issueRefreshToken(value.userId, value.clientId);
526
- return { clientId: value.clientId, newToken, userId: value.userId };
706
+ const newToken = await this.issueRefreshToken(value.userId, value.clientId, resource);
707
+ return { clientId: value.clientId, newToken, ...(resource ? { resource } : {}), userId: value.userId };
527
708
  }
528
709
 
529
710
  /**
@@ -596,7 +777,21 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
596
777
  // Lets saveAuthorizationCode() refuse a code issued on GET — here, not in authorizeConsent(),
597
778
  // so an override cannot drop it.
598
779
  const method = String(res?.req?.method ?? '').toUpperCase();
599
- return authorizeRequest.run({ method }, () => this.authorizeConsent(client, params, res));
780
+ // RFC 8707: the resource the code (and every token from it) is bound to. An unknown one is answered HERE with
781
+ // 400 — thrown, the SDK would send it to the client's self-registered redirect URI before any sign-in, and
782
+ // /authorize would be the open redirect 12.3.0 closed (RFC 9700 §4.11.2)
783
+ let resource: string | undefined;
784
+ try {
785
+ resource = await this.resolveRequestedResource(params?.resource);
786
+ } catch (error) {
787
+ const body =
788
+ typeof (error as { toResponseObject?: unknown })?.toResponseObject === 'function'
789
+ ? (error as { toResponseObject(): Record<string, unknown> }).toResponseObject()
790
+ : { error: 'invalid_target', error_description: (error as Error)?.message };
791
+ res.status(400).json(body);
792
+ return;
793
+ }
794
+ return authorizeRequest.run({ method, resource }, () => this.authorizeConsent(client, params, res));
600
795
  },
601
796
  challengeForAuthorizationCode: async (_client: any, authorizationCode: string) => {
602
797
  const stored = await this.getAuthorizationCode(authorizationCode);
@@ -606,7 +801,20 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
606
801
  getClient: (clientId: string) => this.getClient(clientId),
607
802
  registerClient: (client: AiMcpOAuthClient) => this.registerClient(client),
608
803
  },
609
- exchangeAuthorizationCode: async (client: any, authorizationCode: string) => {
804
+ exchangeAuthorizationCode: async (
805
+ client: any,
806
+ authorizationCode: string,
807
+ _codeVerifier?: string,
808
+ _redirectUri?: string,
809
+ requestedResource?: URL,
810
+ ) => {
811
+ // A resource named here must be one this server serves, and the one the code was bound to (RFC 8707)
812
+ const requested = requestedResource ? await this.resolveRequestedResource(requestedResource) : undefined;
813
+ const peeked = requested ? await this.getAuthorizationCode(authorizationCode) : null;
814
+ if (requested && peeked && (normalizeMcpResource(peeked.resource) ?? this.mcpResource()) !== requested) {
815
+ const { InvalidTargetError } = await this.loadOAuthErrors();
816
+ throw new InvalidTargetError('The authorization code was not issued for the requested resource');
817
+ }
610
818
  const stored = await this.consumeAuthorizationCode(authorizationCode, String(client?.client_id ?? ''));
611
819
  if (!stored || stored.clientId !== client?.client_id) {
612
820
  const { InvalidGrantError } = await this.loadOAuthErrors();
@@ -619,14 +827,16 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
619
827
  const { InvalidGrantError } = await this.loadOAuthErrors();
620
828
  throw new InvalidGrantError('This account may not use MCP');
621
829
  }
830
+ // A code from before 12.10.0 carries no resource: it is bound to /ai/mcp from here on
831
+ const resource = normalizeMcpResource(stored.resource) ?? requested ?? this.mcpResource();
622
832
  return {
623
- access_token: this.signAccessToken(stored.userId, stored.clientId, accessTtlSeconds),
833
+ access_token: this.signAccessToken(stored.userId, stored.clientId, accessTtlSeconds, resource),
624
834
  expires_in: accessTtlSeconds,
625
- refresh_token: await this.issueRefreshToken(stored.userId, stored.clientId),
835
+ refresh_token: await this.issueRefreshToken(stored.userId, stored.clientId, resource),
626
836
  token_type: 'Bearer',
627
837
  };
628
838
  },
629
- exchangeRefreshToken: async (client: any, refreshToken: string) => {
839
+ exchangeRefreshToken: async (client: any, refreshToken: string, _scopes?: string[], requestedResource?: URL) => {
630
840
  // Bind the rotating refresh token to the calling client (OAuth 2.1
631
841
  // §4.13.2 / §7.4). Without this check, a different client could present
632
842
  // a stolen refresh token and obtain an access token for the original
@@ -637,7 +847,10 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
637
847
  const { InvalidClientError } = await this.loadOAuthErrors();
638
848
  throw new InvalidClientError('Unknown client');
639
849
  }
640
- const rotated = await this.rotateRefreshToken(refreshToken, callerClientId);
850
+ if (requestedResource) {
851
+ await this.resolveRequestedResource(requestedResource);
852
+ }
853
+ const rotated = await this.rotateRefreshToken(refreshToken, callerClientId, requestedResource?.href);
641
854
  if (!rotated) {
642
855
  // invalid_grant is the one answer on which an MCP client discards its stored tokens and asks
643
856
  // the user to sign in again — see loadOAuthErrors().
@@ -652,7 +865,7 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
652
865
  throw new InvalidGrantError('This account may not use MCP');
653
866
  }
654
867
  return {
655
- access_token: this.signAccessToken(rotated.userId, rotated.clientId, accessTtlSeconds),
868
+ access_token: this.signAccessToken(rotated.userId, rotated.clientId, accessTtlSeconds, rotated.resource),
656
869
  expires_in: accessTtlSeconds,
657
870
  refresh_token: rotated.newToken,
658
871
  token_type: 'Bearer',
@@ -665,7 +878,14 @@ export class CoreAiMcpOAuthService implements OnModuleInit {
665
878
  throw new InvalidTokenError('Invalid or expired access token');
666
879
  }
667
880
  // `expiresAt` is part of the SDK's AuthInfo contract: its bearer middleware refuses a token without one.
668
- return { clientId: payload.cid, expiresAt: payload.exp, extra: { userId: payload.sub }, scopes: [], token };
881
+ return {
882
+ clientId: payload.cid,
883
+ expiresAt: payload.exp,
884
+ extra: { userId: payload.sub },
885
+ ...(payload.aud ? { resource: new URL(payload.aud) } : {}),
886
+ scopes: [],
887
+ token,
888
+ };
669
889
  },
670
890
  };
671
891
  }
@@ -12,6 +12,7 @@ import { AiToolRegistry, AiToolUser } from '../tools/ai-tool.registry.js';
12
12
  import type { AiToolPolicyDecision } from './core-ai-tool-policy.service.js';
13
13
  import { CoreAiToolPolicyService } from './core-ai-tool-policy.service.js';
14
14
  import { CoreAiUserSettingService } from './core-ai-user-setting.service.js';
15
+ import { sanitizeToolResultForModel } from '../tools/ai-tool-result.helper.js';
15
16
 
16
17
  /**
17
18
  * MCP tool descriptor (name + description + JSON-schema input + behaviour hints).
@@ -148,7 +149,8 @@ export class CoreAiMcpService {
148
149
 
149
150
  try {
150
151
  const result = await tool.execute(callArgs, tool.authorize ? { ...context, authorization } : context);
151
- return { content: [{ text: JSON.stringify(result), type: 'text' }] };
152
+ // The same filtering the chat loop applies: securityCheck() and no secret field reaches the client (12.10.0)
153
+ return { content: [{ text: JSON.stringify(sanitizeToolResultForModel(result, user)), type: 'text' }] };
152
154
  } catch (err) {
153
155
  this.logger.warn(`MCP tool "${name}" failed: ${(err as Error).message}`);
154
156
  return this.errorResult((err as Error).message);