@lenne.tech/nest-server 12.9.4 → 12.10.1

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 (152) hide show
  1. package/.claude/rules/configurable-features.md +5 -1
  2. package/.claude/rules/package-management.md +38 -12
  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 +10 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
  22. package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
  23. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  24. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  26. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  27. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  28. package/dist/core/common/plugins/complexity.plugin.js +73 -9
  29. package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
  30. package/dist/core/common/services/request-context.service.d.ts +2 -0
  31. package/dist/core/common/services/request-context.service.js +3 -0
  32. package/dist/core/common/services/request-context.service.js.map +1 -1
  33. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  34. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  35. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  36. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  37. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  38. package/dist/core/modules/ai/core-ai.module.js +2 -0
  39. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  40. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  41. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  42. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  43. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  44. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  45. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  46. package/dist/core/modules/ai/index.d.ts +8 -0
  47. package/dist/core/modules/ai/index.js +8 -0
  48. package/dist/core/modules/ai/index.js.map +1 -1
  49. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  50. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  51. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  52. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  53. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  54. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  57. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  58. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  59. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  60. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  61. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  62. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  63. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  64. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  65. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  66. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  67. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  68. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  69. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  70. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  71. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  72. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  73. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  74. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  75. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  76. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  77. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  78. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  79. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  80. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  81. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  82. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  83. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  84. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  85. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  86. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  87. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  88. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  89. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  90. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  91. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  92. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  93. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  94. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  95. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  96. package/dist/core.module.js +2 -1
  97. package/dist/core.module.js.map +1 -1
  98. package/dist/index.d.ts +1 -0
  99. package/dist/index.js +1 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/types/graphql-upload.d.ts +34 -2
  102. package/docs/REQUEST-LIFECYCLE.md +59 -10
  103. package/migration-guides/12.10.0-to-12.10.1.md +182 -0
  104. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  105. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  106. package/package.json +46 -21
  107. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  108. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  109. package/src/core/common/helpers/context.helper.ts +14 -0
  110. package/src/core/common/helpers/decorator.helper.ts +5 -0
  111. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  112. package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
  113. package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
  114. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  115. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  116. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  117. package/src/core/common/plugins/complexity.plugin.ts +150 -9
  118. package/src/core/common/services/request-context.service.ts +11 -0
  119. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  120. package/src/core/modules/ai/README.md +101 -0
  121. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  122. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  123. package/src/core/modules/ai/core-ai.module.ts +3 -0
  124. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  125. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  126. package/src/core/modules/ai/index.ts +8 -0
  127. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  128. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  129. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  130. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  131. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  132. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  133. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  134. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  135. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  136. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  137. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  138. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  139. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  140. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  141. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  142. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  143. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  144. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  145. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  146. package/src/core/modules/better-auth/README.md +204 -0
  147. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  148. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  149. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  150. package/src/core.module.ts +5 -1
  151. package/src/index.ts +1 -0
  152. package/src/types/graphql-upload.d.ts +34 -2
@@ -987,6 +987,11 @@ export interface IBetterAuthSignUpChecksConfig {
987
987
  * - `SOCIAL_GOOGLE_CLIENT_ID`, `SOCIAL_GOOGLE_CLIENT_SECRET`
988
988
  * - `SOCIAL_GITHUB_CLIENT_ID`, `SOCIAL_GITHUB_CLIENT_SECRET`
989
989
  * - `SOCIAL_APPLE_CLIENT_ID`, `SOCIAL_APPLE_CLIENT_SECRET`
990
+ * - `SOCIAL_MICROSOFT_CLIENT_ID`, `SOCIAL_MICROSOFT_CLIENT_SECRET`, `SOCIAL_MICROSOFT_TENANT_ID`
991
+ *
992
+ * **Provider options (since 12.10.0):** every further key reaches the Better-Auth provider unchanged, so each
993
+ * provider's own options are set right here: Microsoft's `tenantId`, Google's `hd` and `accessType`, `scope`,
994
+ * `prompt`, `mapProfileToUser` and so on. Before 12.10.0 they were dropped without a word.
990
995
  *
991
996
  * @example
992
997
  * ```typescript
@@ -998,9 +1003,26 @@ export interface IBetterAuthSignUpChecksConfig {
998
1003
  *
999
1004
  * // Provider is explicitly disabled despite having credentials
1000
1005
  * github: { clientId: '...', clientSecret: '...', enabled: false }
1006
+ *
1007
+ * // Microsoft Entra ID: the organization's own tenant, identity only (no Graph scope, no refresh token)
1008
+ * microsoft: {
1009
+ * clientId: process.env.SOCIAL_MICROSOFT_CLIENT_ID || '',
1010
+ * clientSecret: process.env.SOCIAL_MICROSOFT_CLIENT_SECRET || '',
1011
+ * tenantId: process.env.SOCIAL_MICROSOFT_TENANT_ID,
1012
+ * disableDefaultScope: true,
1013
+ * scope: ['openid', 'profile', 'email'],
1014
+ * disableProfilePhoto: true,
1015
+ * },
1001
1016
  * ```
1002
1017
  */
1003
1018
  export interface IBetterAuthSocialProvider {
1019
+ /**
1020
+ * Any further option of the Better-Auth provider, handed on unchanged (since 12.10.0). The keys declared below keep
1021
+ * their meaning; `enabled` is the framework's own and is not handed on.
1022
+ * @see https://www.better-auth.com/docs/authentication/social-sign-in
1023
+ */
1024
+ [option: string]: unknown;
1025
+
1004
1026
  /**
1005
1027
  * OAuth client ID
1006
1028
  */
@@ -1011,6 +1033,13 @@ export interface IBetterAuthSocialProvider {
1011
1033
  */
1012
1034
  clientSecret: string;
1013
1035
 
1036
+ /**
1037
+ * Sends the provider's default scopes only when `false` or unset. `true` asks for exactly what `scope` lists, for
1038
+ * example `['openid', 'profile', 'email']` to keep a Microsoft sign-in free of `User.Read` and `offline_access`.
1039
+ * @default false
1040
+ */
1041
+ disableDefaultScope?: boolean;
1042
+
1014
1043
  /**
1015
1044
  * Whether a first sign-in through this provider may create an account.
1016
1045
  *
@@ -1029,6 +1058,32 @@ export interface IBetterAuthSocialProvider {
1029
1058
  * @default true (when credentials are configured)
1030
1059
  */
1031
1060
  enabled?: boolean;
1061
+
1062
+ /**
1063
+ * The `prompt` parameter for every authorization request of this provider (`'select_account'`, `'consent'`,
1064
+ * `'login'`, `'none'`). One request can set its own through `additionalParams` on `/sign-in/social`, which is how a
1065
+ * silent attempt (`{ prompt: 'none' }`) and an interactive sign-in share one provider.
1066
+ */
1067
+ prompt?: string;
1068
+
1069
+ /**
1070
+ * Scopes to request in addition to the provider's defaults, or instead of them with `disableDefaultScope: true`.
1071
+ *
1072
+ * A string is split on commas and whitespace (`'openid profile email'`, `'openid,profile,email'`), because
1073
+ * `NSC__BETTER_AUTH__SOCIAL_PROVIDERS__<PROVIDER>__SCOPE` arrives as a string: the `NSC__*` reader converts only
1074
+ * `true`, `false` and numbers (since 12.10.0). Any other value (the object indexed `…__SCOPE__0` variables build, the
1075
+ * `0` an empty `…__SCOPE=` becomes) is dropped with an error at boot, and the provider asks for its default scopes;
1076
+ * with `disableDefaultScope: true` it then asks for none, which the provider refuses.
1077
+ */
1078
+ scope?: string | string[];
1079
+
1080
+ /**
1081
+ * Microsoft Entra ID: the tenant to sign in through, by its directory id. Unset, Better-Auth uses `common`, which
1082
+ * admits accounts of every organization and personal Microsoft accounts. A verified domain works for the redirect
1083
+ * flow only: sign-in with an `idToken` compares the token's issuer with `<authority>/<tenantId>/v2.0`, and Microsoft
1084
+ * writes the id there.
1085
+ */
1086
+ tenantId?: string;
1032
1087
  }
1033
1088
 
1034
1089
  /**
@@ -1975,6 +2030,24 @@ export interface IAiRateLimit {
1975
2030
  * ```
1976
2031
  */
1977
2032
  export interface IAi {
2033
+ /**
2034
+ * Offer the application's `@nestjs/ai` agent functions (`@AgentFunction()` methods) as tools of the AI assistant and
2035
+ * its MCP server (12.10.0). Boolean shorthand, presence implies enabled: `true` / `{}` offers every agent function,
2036
+ * `include` only the named ones, `exclude` all but the named ones; `false` / `{ enabled: false }` / unset — off, and
2037
+ * `@nestjs/ai` is never loaded.
2038
+ *
2039
+ * Every gate of the AI module runs first (role filter, tool policies and grants, `authorize()`, confirmation, plan
2040
+ * mode, budgets); then the call runs through `@nestjs/ai`'s own pipeline (input validation, scopes, the application's
2041
+ * guards with the context type `'ai'`) with the run's HTTP request as the caller. Roles, `mutating`, `destructive`
2042
+ * and `authorize` come from `@AiAgentFunction()` on the method; roles default to the method's `@Roles()`, else
2043
+ * `S_USER`. An agent function that requires `scopes` is not offered; one named like a registered tool stops the boot.
2044
+ * Requires `@nestjs/ai` (optional peer, tested range `>=0.0.2 <0.0.3`) with `AiModule.forRoot()` imported — the boot
2045
+ * fails with the tested range named otherwise.
2046
+ *
2047
+ * @default undefined (off)
2048
+ */
2049
+ agentFunctions?: boolean | { enabled?: boolean; exclude?: string[]; include?: string[] };
2050
+
1978
2051
  /**
1979
2052
  * Optional SSRF allowlist for connection base URLs. When set (non-empty), the
1980
2053
  * provider only sends requests to these hosts (matched by `host` incl. port, or
@@ -4829,6 +4902,29 @@ interface IBetterAuthBase {
4829
4902
  */
4830
4903
  enabled?: boolean;
4831
4904
 
4905
+ /**
4906
+ * Where Better-Auth sends the browser when an OAuth flow fails and no error URL of the flow's own applies (since
4907
+ * 12.10.0): the callback could not read its state (expired after ten minutes, missing, tampered), or the flow was
4908
+ * started without `errorCallbackURL`. Better-Auth appends `?error=<code>` and, where the provider sent one,
4909
+ * `&error_description=…`. Its `GET <basePath>/error` page forwards there too. Handed to Better-Auth as
4910
+ * `onAPIError.errorURL`.
4911
+ *
4912
+ * - unset: `<appUrl>/auth/login`, with the app URL resolved like the other derived links (explicit `appUrl`, the
4913
+ * localhost default in `local` / `ci` / `e2e`, else derived from `baseUrl` unless `cors.deriveAppUrl: false`). No
4914
+ * app URL resolves: Better-Auth's own page on the API host, as before.
4915
+ * - an absolute `http(s)` URL: used as it is.
4916
+ * - a path starting with one `/`: resolved against the app URL; without one, Better-Auth's own page and a warning.
4917
+ * - `false`: Better-Auth's own page.
4918
+ * - anything else (another scheme, `//host`, a number from an empty `NSC__BETTER_AUTH__ERROR_URL`): refused with a
4919
+ * warning, Better-Auth's own page.
4920
+ *
4921
+ * `betterAuth.options.onAPIError.errorURL` wins over this. A login page shows a text of its own per `error` code and
4922
+ * never renders `error_description`: anyone can put text there through a link to `<basePath>/error`.
4923
+ *
4924
+ * @default '/auth/login' (resolved against the app URL)
4925
+ */
4926
+ errorUrl?: false | string;
4927
+
4832
4928
  /**
4833
4929
  * JWT plugin configuration for API clients.
4834
4930
  *
@@ -5062,6 +5158,8 @@ interface IBetterAuthBase {
5062
5158
  * github: { clientId: '...', clientSecret: '...' },
5063
5159
  * // This provider is explicitly disabled
5064
5160
  * discord: { clientId: '...', clientSecret: '...', enabled: false },
5161
+ * // Provider options reach Better-Auth unchanged (since 12.10.0)
5162
+ * microsoft: { clientId: '...', clientSecret: '...', tenantId: '...' },
5065
5163
  * }
5066
5164
  * ```
5067
5165
  */
@@ -34,6 +34,9 @@ export class RequestContextMiddleware implements NestMiddleware {
34
34
  return (req as any).isAdminBypass ?? false;
35
35
  },
36
36
  fromRequest: true,
37
+ get request() {
38
+ return req;
39
+ },
37
40
  };
38
41
  RequestContext.run(context, () => next());
39
42
  }
@@ -1,11 +1,127 @@
1
1
  import { Plugin } from '@nestjs/apollo';
2
2
  import { GraphQLSchemaHost } from '@nestjs/graphql';
3
3
  import type { ApolloServerPlugin, BaseContext, GraphQLRequestListener } from '@apollo/server';
4
- import { GraphQLError } from 'graphql';
5
- import { fieldExtensionsEstimator, getComplexity, simpleEstimator } from 'graphql-query-complexity';
4
+ import { getVariableValues, GraphQLError, Kind, TypeInfo, ValidationContext, visit, visitWithTypeInfo } from 'graphql';
5
+ import type {
6
+ ASTVisitor,
7
+ DefinitionNode,
8
+ DocumentNode,
9
+ FragmentDefinitionNode,
10
+ GraphQLSchema,
11
+ OperationDefinitionNode,
12
+ SelectionSetNode,
13
+ } from 'graphql';
14
+ import { createComplexityRule, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
6
15
 
7
16
  import { ConfigService } from '../services/config.service.js';
8
17
 
18
+ /**
19
+ * Most variable coercion errors the pre-check collects before it stops. It only needs to know WHETHER the variables
20
+ * coerce, and one error answers that. Every error graphql creates for a variable computes its line and column by
21
+ * scanning the query up to the variable's definition: with execution's cap of 50 the pre-check cost 550 ms for a
22
+ * 959 KiB multipart request whose definitions stood after 490,000 line breaks (12.10.1).
23
+ */
24
+ const VARIABLE_COERCION_MAX_ERRORS = 1;
25
+
26
+ /**
27
+ * Most visits × declared variables the complexity analysis may cost (12.10.1, SEC-4). graphql-query-complexity runs
28
+ * `Object.keys()` over the operation's variables at every field and every `@skip` / `@include` it visits — measured on
29
+ * Node 24 at 12–90 ns per variable and visit, so the limit is reached after at most about 23 ms. 38,000 declared
30
+ * variables and 4,900 visits blocked the event loop for 17 s before. With the default cost of 1 per field, a query
31
+ * `maxComplexity: 1000` accepts has at most 1,000 fields; with 30 variables that is at most 30,000.
32
+ */
33
+ const COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK = 250_000;
34
+
35
+ /** The visitor graphql-query-complexity builds (the class itself is not exported). */
36
+ type ComplexityVisitor = ReturnType<ReturnType<typeof createComplexityRule>>;
37
+
38
+ /** Fields and `@skip` / `@include` directives in the selection sets — each one a visit with the variables walked. */
39
+ function variableVisits(definitions: readonly (FragmentDefinitionNode | OperationDefinitionNode)[]): number {
40
+ let visits = 0;
41
+ const pending: SelectionSetNode[] = definitions.map((definition) => definition.selectionSet);
42
+ while (pending.length) {
43
+ const selectionSet = pending.pop()!;
44
+ for (const selection of selectionSet.selections) {
45
+ for (const directive of selection.directives ?? []) {
46
+ if (directive.name.value === 'include' || directive.name.value === 'skip') {
47
+ visits++;
48
+ }
49
+ }
50
+ if (selection.kind === Kind.FIELD) {
51
+ visits++;
52
+ }
53
+ if (selection.kind !== Kind.FRAGMENT_SPREAD && selection.selectionSet) {
54
+ pending.push(selection.selectionSet);
55
+ }
56
+ }
57
+ }
58
+ return visits;
59
+ }
60
+
61
+ /**
62
+ * The complexity graphql-query-complexity's `getComplexity()` computes, with each fragment evaluated once (12.10.1,
63
+ * SEC-4).
64
+ *
65
+ * The library evaluates a fragment again at EVERY spread, without caching, and at every visit coerces the field's
66
+ * literal arguments again. Its node cap (10,000 visits) bounds the visits, not their cost:
67
+ * `{...F ×3300} fragment F on Query { findUsers(filter: { … value: [0,0,…41,667 items] }) }` blocked the event loop
68
+ * for 2.2 s from a 100 KB JSON POST and for 22.5 s from a 990 KB multipart request — before any guard, with variables
69
+ * that coerce.
70
+ *
71
+ * A fragment's complexity depends on the fragment alone: its type is its type condition, and the variables and the
72
+ * estimators are the same for every spread. So the first spread evaluates it, every further spread reuses the result
73
+ * and adds the nodes the evaluation visited to the library's node count, so a query over 10,000 nodes is refused as
74
+ * before. The number this returns is the one `getComplexity()` returns; the work is that of the document, each
75
+ * fragment once. A field's `complexity` extension (read by `fieldExtensionsEstimator`) must therefore depend only on its
76
+ * arguments and `childComplexity` — as a function it runs once per fragment, not once per spread.
77
+ *
78
+ * The analysis stops at the first error it reports. The library catches the coercion error of every field's arguments
79
+ * and goes on, and `getComplexity()` throws the last one at the end — but every error with a node computes its line and
80
+ * column by scanning the query up to it. `query($x: String = "a") { a: getUser(id: $x) { id } b: … }` with
81
+ * `{"x": null}` is valid, passes the variable check and fails at every one of up to 9,999 fields: 1.4 s from a 98 KiB
82
+ * JSON POST, 86 s from a 993 KiB multipart request with the fields after 395,000 line breaks (12.10.1). The request is
83
+ * refused either way; now with the first error instead of the last.
84
+ *
85
+ * Built like `getComplexity()` (graphql-query-complexity 2.0.0, `QueryComplexity.js`), through the public
86
+ * `createComplexityRule()`; the cache wraps `nodeComplexity` of this one visitor, which the library calls through
87
+ * `this` for every fragment spread.
88
+ */
89
+ function computeComplexity(schema: GraphQLSchema, query: DocumentNode, variables: Record<string, unknown>): number {
90
+ const typeInfo = new TypeInfo(schema);
91
+ const context = new ValidationContext(schema, query, typeInfo, (error) => {
92
+ throw error;
93
+ });
94
+ const visitor: ComplexityVisitor = createComplexityRule({
95
+ estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
96
+ // The maximum is checked by the plugin; the visitor only computes.
97
+ maximumComplexity: Infinity,
98
+ variables,
99
+ })(context);
100
+
101
+ const evaluate = visitor.nodeComplexity.bind(visitor);
102
+ const fragments = new Map<string, { complexity: number; nodes: number }>();
103
+ visitor.nodeComplexity = (node, typeDef, activeFragments) => {
104
+ if (node.kind !== Kind.FRAGMENT_DEFINITION) {
105
+ return evaluate(node, typeDef, activeFragments);
106
+ }
107
+ const known = fragments.get(node.name.value);
108
+ if (known) {
109
+ visitor.evaluatedNodes += known.nodes;
110
+ if (visitor.evaluatedNodes >= visitor.maxQueryNodes) {
111
+ throw new GraphQLError('Query exceeds the maximum allowed number of nodes.');
112
+ }
113
+ return known.complexity;
114
+ }
115
+ const before = visitor.evaluatedNodes;
116
+ const complexity = evaluate(node, typeDef, activeFragments);
117
+ fragments.set(node.name.value, { complexity, nodes: visitor.evaluatedNodes - before });
118
+ return complexity;
119
+ };
120
+
121
+ visit(query, visitWithTypeInfo(typeInfo, visitor as unknown as ASTVisitor));
122
+ return visitor.complexity;
123
+ }
124
+
9
125
  @Plugin()
10
126
  export class ComplexityPlugin implements ApolloServerPlugin {
11
127
  constructor(
@@ -18,14 +134,39 @@ export class ComplexityPlugin implements ApolloServerPlugin {
18
134
  const { schema } = this.gqlSchemaHost;
19
135
 
20
136
  return {
21
- async didResolveOperation({ document, request }) {
22
- const complexity = getComplexity({
23
- estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
24
- operationName: request.operationName,
25
- query: document,
26
- schema,
27
- variables: request.variables,
137
+ async didResolveOperation({ document, operation, request }) {
138
+ // No operation resolved: several operations and no `operationName` naming one of them. Apollo still calls this
139
+ // hook, and graphql's `execute()` refuses the request afterwards, before it coerces a single variable.
140
+ // getComplexity() instead evaluated EVERY operation of such a document and coerced the variables for each
141
+ // (12.10.1, SEC-3): 860 operations sharing one 16,000-item variable blocked the event loop for 5.9 s from a
142
+ // 100 KB JSON POST, 1,720 operations for 25.5 s from 200 KB.
143
+ if (!operation) {
144
+ return;
145
+ }
146
+
147
+ // Invalid variables (12.10.1, SEC-2): getComplexity() coerces without an error cap, so a list of invalid items
148
+ // created one error per item — 1.5 s and 300 MB for 100 KB, 15 s and 2 GB for 1 MB. Execution refuses such
149
+ // variables itself, with graphql's cap of 50, before any resolver runs, so there is no complexity to compute.
150
+ const { errors } = getVariableValues(schema, operation.variableDefinitions ?? [], request.variables ?? {}, {
151
+ maxErrors: VARIABLE_COERCION_MAX_ERRORS,
28
152
  });
153
+ if (errors?.length) {
154
+ return;
155
+ }
156
+
157
+ // The resolved operation alone, with the fragments it may spread: the analysis evaluates exactly the operation
158
+ // execution runs, and coerces its variables once.
159
+ const fragments = document.definitions.filter(
160
+ (definition: DefinitionNode): definition is FragmentDefinitionNode =>
161
+ definition.kind === Kind.FRAGMENT_DEFINITION,
162
+ );
163
+ const variableCount = operation.variableDefinitions?.length ?? 0;
164
+ if (variableVisits([operation, ...fragments]) * variableCount > COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK) {
165
+ throw new GraphQLError('Query is too complex: too many fields for its number of variables');
166
+ }
167
+
168
+ const query: DocumentNode = { definitions: [operation, ...fragments], kind: Kind.DOCUMENT };
169
+ const complexity = computeComplexity(schema, query, request.variables ?? {});
29
170
  if (maxComplexity !== undefined && complexity > maxComplexity) {
30
171
  throw new GraphQLError(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
31
172
  }
@@ -35,6 +35,12 @@ export interface IRequestContext {
35
35
  * on inner calls — the outermost call and CheckSecurityInterceptor handle these.
36
36
  */
37
37
  processDepth?: number;
38
+ /**
39
+ * The HTTP request this context belongs to (12.10.0), set by `RequestContextMiddleware`; `undefined` on every other
40
+ * transport. Read by the AI module's agent-function bridge, which hands it to `@nestjs/ai` as the caller so the
41
+ * application's guards decide on the user exactly as over HTTP (nestjs-ai plan §3).
42
+ */
43
+ request?: unknown;
38
44
  }
39
45
 
40
46
  /**
@@ -53,6 +59,11 @@ export class RequestContext {
53
59
  return this.storage.getStore();
54
60
  }
55
61
 
62
+ /** The HTTP request of the current context, when it came from one (see {@link IRequestContext.request}). */
63
+ static getRequest(): unknown {
64
+ return this.storage.getStore()?.request;
65
+ }
66
+
56
67
  static getCurrentUser(): IRequestContext['currentUser'] | undefined {
57
68
  return this.storage.getStore()?.currentUser;
58
69
  }
@@ -276,6 +276,22 @@ the client's registered URI, so an unprotected Deny lets a cross-site POST send
276
276
  An error before your method runs (a malformed request) is answered with 400 by the framework and never
277
277
  redirected.
278
278
 
279
+ ### NestJS AI / AI SDK (optional, 12.10.0)
280
+
281
+ Only when the project wants one of the integrations (README → "NestJS AI and the AI SDK"):
282
+
283
+ - [ ] Install exactly what the integration needs, in the tested range: `ai` (`>=7.0.0 <8`) for
284
+ `registerAiSdkModel()`; additionally `@nestjs/ai` (`>=0.0.2 <0.0.3`) and `@nestjs/resilience`
285
+ (`>=0.0.3 <0.0.4`) for `providerType: 'nestjs-ai'` and `ai.agentFunctions`, with `AiModule.forRoot({ models })`
286
+ imported. Outside the range the boot (or the first call) fails with `AiSdkPackageError` naming it.
287
+ - [ ] `registerAiSdkModel()`: hand the provider the `fetch` from the builder context — otherwise
288
+ `ai.allowedBaseUrlHosts` does not cover it.
289
+ - [ ] `ai.agentFunctions`: put `@Roles()` or `@AiAgentFunction({ roles })` on every agent function that is not for
290
+ every signed-in user, and `mutating` / `destructive` on those that change data. **WHY:** the bridge offers an
291
+ agent function to every user its roles allow, and confirmation applies only to flagged tools.
292
+ - [ ] Vendor mode: the core names `ai`, `@nestjs/ai` and `@nestjs/resilience` in literal `import()` calls, so the
293
+ project declares them (the lt CLI adds them when vendoring).
294
+
279
295
  ## Verification Checklist
280
296
 
281
297
  - [ ] Build succeeds (`pnpm run build`)
@@ -180,6 +180,76 @@ calling and executes tools itself through `CrudService` with the caller's permis
180
180
  the child runs in a temp dir so no `CLAUDE.md`/settings leak into the context. See
181
181
  `ClaudeCliProvider` for the full security model and the optional `ai.claudeCli` config.
182
182
 
183
+ ## NestJS AI and the AI SDK (12.10.0)
184
+
185
+ Three opt-in integrations with `@nestjs/ai` / the AI SDK (`ai`). All three packages — `ai`, `@nestjs/ai`,
186
+ `@nestjs/resilience` — are **optional peers**: a project that installs none of them loads nothing new. Each is loaded
187
+ lazily on first use and checked against the range this release was tested with (`AI_SDK_TESTED_RANGES`:
188
+ `ai >=7.0.0 <8`, `@nestjs/ai >=0.0.2 <0.0.3`, `@nestjs/resilience >=0.0.3 <0.0.4`) and for the members the framework
189
+ calls; outside it the call (or the boot, for `ai.agentFunctions` and `registerAiSdkModel()`) fails with
190
+ `AiSdkPackageError` naming the range — never a quiet misbehaviour of a 0.x release.
191
+
192
+ **A model registered in `@nestjs/ai`** — a connection with `providerType: 'nestjs-ai'` and `model` = the name in
193
+ `AiModule.forRoot({ models })` (`baseUrl` is informative only, e.g. `nestjs-ai:default`). The call runs through the AI
194
+ SDK with `@nestjs/resilience` retries (3 attempts on what the provider marks retryable) and the connection's timeout.
195
+ Why not `AiService.generateText()`: it offers only `@AgentFunction()` methods as tools and runs them itself, and the
196
+ method that returns tool calls unrun (`callModel()`) is `@internal` — the module's own gates must decide every call.
197
+
198
+ **An AI SDK provider for database-managed connections** (encrypted keys, per tenant):
199
+
200
+ ```typescript
201
+ import { createAnthropic } from '@ai-sdk/anthropic';
202
+
203
+ // Add it to ServerModule.imports — CoreAiModule is global and exports LlmProviderFactory. Never import
204
+ // CoreModule.forRoot() here: that would start the whole framework a second time.
205
+ @Module({})
206
+ export class AiProvidersModule implements OnModuleInit {
207
+ constructor(private readonly factory: LlmProviderFactory) {}
208
+ async onModuleInit() {
209
+ await this.factory.registerAiSdkModel('anthropic', (connection, { fetch }) =>
210
+ createAnthropic({ apiKey: connection.apiKey, fetch })(connection.model),
211
+ );
212
+ }
213
+ }
214
+ ```
215
+
216
+ Pass the `fetch` you are given: it refuses hosts outside `ai.allowedBaseUrlHosts`, so the egress allowlist covers the
217
+ provider's requests. Native tools reach the model **without `execute`**: the AI SDK returns the tool calls, and the
218
+ module runs them through its gates (role filter, policies and grants, `authorize()`, confirmation, plan mode, budgets).
219
+ An attachment URL the model cannot read itself is downloaded through `outboundFetch()` (private addresses refused;
220
+ streamed, 20 MB each, 50 MB and 10 downloads per call), never by the AI SDK's own fetch. Usage feeds budgets and audit.
221
+
222
+ Tool results — chat and `/ai/mcp` alike — pass `sanitizeToolResultForModel()`: `securityCheck(user)` on every model
223
+ instance at any depth (also inside `{ success, data }`), then every secret field leaves the result, Mongoose documents
224
+ included.
225
+
226
+ **`@AgentFunction()` methods as tools** — `ai.agentFunctions: true` (or `{ include, exclude }`) offers the application's
227
+ agent functions to the chat and to `/ai/mcp`. The module's gates run first; `execute()` then calls `@nestjs/ai`'s own
228
+ pipeline (`AiTools.call()`: input validation, scopes, the application's guards with context type `'ai'`) with the run's
229
+ HTTP request as the caller, so the method's `@Roles()` is decided on the user exactly as over HTTP. The framework's extras
230
+ go on the method:
231
+
232
+ ```typescript
233
+ @AgentFunction({ name: 'cancel_booking', description: 'Cancel a booking', inputSchema: z.object({ id: z.string() }) })
234
+ @AiAgentFunction({ destructive: true, authorize: (args) => args.id !== 'locked' })
235
+ @Roles(RoleEnum.S_USER)
236
+ cancel({ id }: { id: string }) { ... }
237
+ ```
238
+
239
+ Roles default to the method's `@Roles()`, else `S_USER` (never open). An agent function that requires `scopes` is not
240
+ offered — the assistant calls without scopes. A name that is already a registered tool stops the boot.
241
+
242
+ **Standard Schema parameters** — `IAiTool.parameters` may be a Zod 4.2+ / ArkType / Valibot (`toStandardJsonSchema()`)
243
+ schema. The registry stores its JSON Schema and validates the arguments before `authorize()` and `execute()`; invalid
244
+ arguments are reported back to the model as a failed call.
245
+
246
+ **Your own `@nestjs/mcp` endpoint with this module's OAuth server** — `CoreAiMcpOAuthService.createMcpTokenVerifier()`
247
+ (see "OAuth 2.1" below).
248
+
249
+ **Global enhancers on `'ai'` / `'mcp'` calls** — in any project that installs `@nestjs/ai` or `@nestjs/mcp`, the
250
+ framework's guards decide on the request the call runs in, never on the tool arguments; a request-less caller is
251
+ anonymous; results are filtered for the request's user. See `docs/REQUEST-LIFECYCLE.md` → "Agent function and MCP calls".
252
+
183
253
  ## Egress allowlist (`ai.allowedBaseUrlHosts`)
184
254
 
185
255
  A connection's `baseUrl` decides where the server sends outbound HTTP. It is admin-set, so the
@@ -1034,6 +1104,37 @@ token, retried, and never asked the user to sign in again. A refusal in your own
1034
1104
  needs the same: take the class from `this.loadOAuthErrors()` (e.g. `AccessDeniedError` when the user
1035
1105
  declines), never a plain `Error`.
1036
1106
 
1107
+ ### Your own `@nestjs/mcp` endpoint (12.10.0)
1108
+
1109
+ `@nestjs/mcp` is a resource server only. This module's authorization server can be its identity provider:
1110
+
1111
+ ```typescript
1112
+ McpModule.forRootAsync({
1113
+ inject: [CoreAiMcpOAuthService],
1114
+ useFactory: (oauth: CoreAiMcpOAuthService) => ({
1115
+ name: 'my-api',
1116
+ version: '1.0.0',
1117
+ auth: {
1118
+ authorizationServers: ['https://api.example.com'],
1119
+ resource: 'https://api.example.com/mcp',
1120
+ verifier: oauth.createMcpTokenVerifier({ resource: 'https://api.example.com/mcp' }),
1121
+ },
1122
+ }),
1123
+ });
1124
+ ```
1125
+
1126
+ The verifier accepts a token when its signature and expiry hold, its audience is `resource`, and its user exists and
1127
+ may use MCP (`ai.mcp.roles` / `mayUseMcp()`, on every request); the user reaches the tool's guards as `request.user`.
1128
+
1129
+ **Audience binding (RFC 8707, 12.10.0).** Creating the verifier registers `resource` with the authorization server. A
1130
+ client names the endpoint as `resource` at `/authorize` and `/token` (the MCP authorization spec requires it); the code,
1131
+ the refresh token and the access token are bound to it, and a token is accepted only where it was issued for: `/ai/mcp`
1132
+ refuses a token for the project endpoint and the verifier one for `/ai/mcp`. A `resource` this server does not serve is
1133
+ `invalid_target`. A client that names none gets a token for `/ai/mcp`. Tokens and refresh tokens from before 12.10.0
1134
+ carry no audience and stay valid at `/ai/mcp` only; a refresh binds them to `/ai/mcp`. `/ai/mcp` stays on
1135
+ `@modelcontextprotocol/sdk` 1.x: the v2 SDK ships no authorization-server router, and `@nestjs/mcp` serves every request
1136
+ statelessly (no sessions, no server-initiated elicitation for 2025 clients) — see the migration guide 12.9.x → 12.10.x.
1137
+
1037
1138
  ## Tests
1038
1139
 
1039
1140
  - `tests/unit/ai.spec.ts` — crypto, registry role filtering, orchestrator loop,
@@ -14,6 +14,7 @@ import { getMountedMcpOAuth } from './helpers/ai-mcp-oauth.registry.js';
14
14
  import { CoreAiMcpOAuthService } from './services/core-ai-mcp-oauth.service.js';
15
15
  import { CoreAiMcpService } from './services/core-ai-mcp.service.js';
16
16
  import { AiToolUser } from './tools/ai-tool.registry.js';
17
+ import { toVerifiedAiUser } from './helpers/ai-verified-user.helper.js';
17
18
 
18
19
  /**
19
20
  * MCP Streamable-HTTP endpoint at `/ai/mcp`.
@@ -279,8 +280,12 @@ export class CoreAiMcpController implements OnModuleDestroy {
279
280
  // OAuth 2.1 access token (when ai.mcp.oauth is enabled).
280
281
  if (bearer && this.oauthEnabled()) {
281
282
  const payload = this.oauthService.verifyAccessToken(bearer);
282
- if (payload?.sub) {
283
- return this.oauthService.loadUser(payload.sub);
283
+ // RFC 8707: only a token issued for /ai/mcp — or one from before 12.10.0, which carries no audience
284
+ if (payload?.sub && this.oauthService.acceptsAudienceAtMcp(payload)) {
285
+ // Shaped like a user the authentication middleware sets, so the role guards on an agent function and a model's
286
+ // securityCheck() work with it (12.10.0, see toVerifiedAiUser())
287
+ const user = await this.oauthService.loadUser(payload.sub);
288
+ return user ? toVerifiedAiUser(user) : null;
284
289
  }
285
290
  }
286
291
 
@@ -110,3 +110,7 @@ export const AI_MCP_OAUTH_CODE_TTL_SECONDS = 600;
110
110
  // ---- module options ----
111
111
  /** Whether `CoreAiModule.forRoot()` registered the MCP endpoint (`ai.mcp`) — what `GET /ai/status` answers. */
112
112
  export const AI_MCP_ENABLED = 'AI_MCP_ENABLED';
113
+
114
+ // ---- agent functions (nestjs-ai plan §3) ----
115
+ /** Metadata key of `@AiAgentFunction()` — the framework's extras on a `@nestjs/ai` agent function method. */
116
+ export const AI_AGENT_FUNCTION_METADATA = 'lt:ai:agent-function';
@@ -36,6 +36,7 @@ import { AiToolGrantSchema, CoreAiToolGrant } from './models/core-ai-tool-grant.
36
36
  import { AiToolPolicySchema, CoreAiToolPolicy } from './models/core-ai-tool-policy.model.js';
37
37
  import { AiUserSettingSchema, CoreAiUserSetting } from './models/core-ai-user-setting.model.js';
38
38
  import { LlmProviderFactory } from './providers/llm-provider.factory.js';
39
+ import { CoreAiAgentFunctionBridge } from './services/core-ai-agent-function.bridge.js';
39
40
  import { AiCryptoService } from './services/ai-crypto.service.js';
40
41
  import {
41
42
  AI_BUDGET_LIMIT_CLASS,
@@ -275,6 +276,8 @@ export class CoreAiModule {
275
276
  AskUserQuestionAiTool,
276
277
  SearchToolsAiTool,
277
278
  LlmProviderFactory,
279
+ // Inert unless `ai.agentFunctions` is set (nestjs-ai plan §3)
280
+ CoreAiAgentFunctionBridge,
278
281
  { provide: AI_MCP_ENABLED, useValue: options.mcpEnabled === true },
279
282
  { provide: AI_BUDGET_LIMIT_CLASS, useValue: CoreAiBudgetLimit },
280
283
  { provide: AI_CONNECTION_CLASS, useValue: CoreAiConnection },
@@ -0,0 +1,44 @@
1
+ import { AI_AGENT_FUNCTION_METADATA } from '../core-ai.constants.js';
2
+ import type { AiToolAuthorization, AiToolContext } from '../interfaces/ai-tool.interface.js';
3
+
4
+ /**
5
+ * The framework's extras for a `@nestjs/ai` agent function that the AI module offers as a tool
6
+ * (`ai.agentFunctions`, nestjs-ai plan §3). Everything `@nestjs/ai` does not know: who may see the tool, whether it
7
+ * changes data, and a data-level check before it runs.
8
+ */
9
+ export interface IAiAgentFunctionOptions {
10
+ /**
11
+ * Data-level check before every execution, with the arguments that will run — exactly `IAiTool.authorize()`. Called
12
+ * with `this` bound to the provider instance. Fail closed: a throw refuses.
13
+ */
14
+ authorize?: (
15
+ args: Record<string, any>,
16
+ context: AiToolContext,
17
+ ) => AiToolAuthorization | boolean | Promise<AiToolAuthorization | boolean>;
18
+ /** Always asks the user before running (`IAiTool.destructive`). */
19
+ destructive?: boolean;
20
+ /** Changes data (`IAiTool.mutating`): the confirmation policy applies. */
21
+ mutating?: boolean;
22
+ /**
23
+ * Roles that may see and call the tool. Default: the method's `@Roles()` (merged with the class's), else `S_USER`.
24
+ * The method's `@Roles()` is ALSO enforced by the application's guards when `@nestjs/ai` runs it.
25
+ */
26
+ roles?: string[];
27
+ }
28
+
29
+ /**
30
+ * Stacks the framework's tool extras on a `@nestjs/ai` `@AgentFunction()` method:
31
+ *
32
+ * ```typescript
33
+ * @AgentFunction({ name: 'cancel_order', description: 'Cancel an order', inputSchema: z.object({ id: z.string() }) })
34
+ * @AiAgentFunction({ destructive: true })
35
+ * @Roles(RoleEnum.S_USER)
36
+ * cancel({ id }: { id: string }) { ... }
37
+ * ```
38
+ */
39
+ export function AiAgentFunction(options: IAiAgentFunctionOptions = {}): MethodDecorator {
40
+ return (_target, _key, descriptor: PropertyDescriptor) => {
41
+ Reflect.defineMetadata(AI_AGENT_FUNCTION_METADATA, { ...options }, descriptor.value);
42
+ return descriptor;
43
+ };
44
+ }
@@ -0,0 +1,47 @@
1
+ import { RoleEnum } from '../../../common/enums/role.enum.js';
2
+
3
+ /** A user the AI module authenticated itself (an MCP OAuth access token), as the guards and models expect one. */
4
+ export interface AiVerifiedUser {
5
+ [key: string]: any;
6
+ _authenticatedViaBetterAuth: true;
7
+ hasRole(roles: string | string[]): boolean;
8
+ id: string;
9
+ roles: string[];
10
+ }
11
+
12
+ /**
13
+ * The user an MCP OAuth access token belongs to, shaped like a user the authentication middleware sets (12.10.0).
14
+ *
15
+ * `loadUser()` answers a plain `{ id, roles }`. On `/ai/mcp` that object became `request.user`, and two things expected
16
+ * more of it: `RolesGuard` (three-argument `CoreModule.forRoot()`) decides on an existing user only when it carries
17
+ * `_authenticatedViaBetterAuth` — otherwise it asks Passport, which knows no MCP token, and answers 401 — and a model's
18
+ * `securityCheck(user)` calls `user.hasRole()`. Both now run on an MCP OAuth user: the guards when a tool is an
19
+ * `@AgentFunction()` (`ai.agentFunctions`) or a `@nestjs/mcp` tool, `securityCheck()` when an MCP tool result is
20
+ * sanitised. `hasRole()` follows `CoreBetterAuthUserMapper`: `S_EVERYONE` / `S_USER` true, `S_NO_ONE` false,
21
+ * `S_VERIFIED` false (the token says nothing about verification — fail closed), else the user's own roles.
22
+ *
23
+ * A user that already carries both is returned as it is.
24
+ */
25
+ export function toVerifiedAiUser<T extends { [key: string]: any; id: string; roles?: string[] }>(
26
+ user: T,
27
+ ): AiVerifiedUser & T {
28
+ if (user._authenticatedViaBetterAuth === true && typeof user.hasRole === 'function') {
29
+ return user as AiVerifiedUser & T;
30
+ }
31
+ const roles = Array.isArray(user.roles) ? [...user.roles] : [];
32
+ return {
33
+ ...user,
34
+ _authenticatedViaBetterAuth: true,
35
+ hasRole: (check: string | string[]) => {
36
+ const required = Array.isArray(check) ? check : [check];
37
+ if (required.includes(RoleEnum.S_EVERYONE) || required.includes(RoleEnum.S_USER)) {
38
+ return true;
39
+ }
40
+ if (required.includes(RoleEnum.S_NO_ONE) || required.includes(RoleEnum.S_VERIFIED)) {
41
+ return false;
42
+ }
43
+ return required.some((role) => roles.includes(role));
44
+ },
45
+ roles,
46
+ };
47
+ }