@lenne.tech/nest-server 12.9.3 → 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.
- package/.claude/rules/configurable-features.md +4 -0
- package/.claude/rules/package-management.md +35 -6
- package/.claude/rules/role-system.md +12 -0
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +10 -1
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/decorators/rest-user.decorator.js +4 -0
- package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +3 -0
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/context.helper.js +9 -0
- package/dist/core/common/helpers/context.helper.js.map +1 -1
- package/dist/core/common/helpers/decorator.helper.js +4 -0
- package/dist/core/common/helpers/decorator.helper.js.map +1 -1
- package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +8 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
- package/dist/core/common/middleware/request-context.middleware.js +3 -0
- package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
- package/dist/core/common/services/request-context.service.d.ts +2 -0
- package/dist/core/common/services/request-context.service.js +3 -0
- package/dist/core/common/services/request-context.service.js.map +1 -1
- package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
- package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
- package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
- package/dist/core/modules/ai/core-ai.constants.js +1 -0
- package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
- package/dist/core/modules/ai/core-ai.module.js +2 -0
- package/dist/core/modules/ai/core-ai.module.js.map +1 -1
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
- package/dist/core/modules/ai/index.d.ts +8 -0
- package/dist/core/modules/ai/index.js +8 -0
- package/dist/core/modules/ai/index.js.map +1 -1
- package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
- package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
- package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
- package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
- package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
- package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
- package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai.service.js +2 -7
- package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
- package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
- package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
- package/dist/core/modules/auth/guards/auth.guard.js +10 -2
- package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/roles.guard.js +11 -1
- package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +78 -0
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/file/core-file.controller.js +8 -0
- package/dist/core/modules/file/core-file.controller.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +2 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types/graphql-upload.d.ts +34 -2
- package/docs/REQUEST-LIFECYCLE.md +46 -9
- package/docs/security-overrides.md +44 -10
- package/migration-guides/12.9.3-to-12.9.4.md +137 -0
- package/migration-guides/12.9.x-to-12.10.x.md +271 -0
- package/package.json +62 -37
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +8 -0
- package/src/core/common/helpers/context.helper.ts +14 -0
- package/src/core/common/helpers/decorator.helper.ts +5 -0
- package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/common/interfaces/server-options.interface.ts +98 -0
- package/src/core/common/middleware/request-context.middleware.ts +3 -0
- package/src/core/common/services/request-context.service.ts +11 -0
- package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
- package/src/core/modules/ai/README.md +101 -0
- package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
- package/src/core/modules/ai/core-ai.constants.ts +4 -0
- package/src/core/modules/ai/core-ai.module.ts +3 -0
- package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
- package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
- package/src/core/modules/ai/index.ts +8 -0
- package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
- package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
- package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
- package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
- package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
- package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
- package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
- package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
- package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
- package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
- package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
- package/src/core/modules/ai/services/core-ai.service.ts +5 -7
- package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
- package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
- package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
- package/src/core/modules/auth/guards/auth.guard.ts +19 -2
- package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
- package/src/core/modules/auth/guards/roles.guard.ts +23 -1
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
- package/src/core/modules/better-auth/README.md +204 -0
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/better-auth/better-auth.config.ts +138 -1
- package/src/core/modules/file/README.md +1 -0
- package/src/core/modules/file/core-file.controller.ts +17 -0
- package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
- package/src/core.module.ts +5 -1
- package/src/index.ts +1 -0
- 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
|
*/
|
|
@@ -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
|
-
|
|
283
|
-
|
|
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
|
+
}
|
|
@@ -20,6 +20,7 @@ export type {
|
|
|
20
20
|
McpOAuthConsentTexts,
|
|
21
21
|
} from './helpers/ai-mcp-oauth-consent.helper.js';
|
|
22
22
|
export * from './helpers/ai-tool-authorization.helper.js';
|
|
23
|
+
export * from './helpers/ai-verified-user.helper.js';
|
|
23
24
|
export * from './core-ai.controller.js';
|
|
24
25
|
export * from './core-ai.module.js';
|
|
25
26
|
export * from './core-ai.resolver.js';
|
|
@@ -66,10 +67,15 @@ export * from './models/core-ai-user-setting.model.js';
|
|
|
66
67
|
export * from './models/core-ai-response.model.js';
|
|
67
68
|
export * from './models/core-ai-usage-info.model.js';
|
|
68
69
|
export * from './models/core-ai-usage.model.js';
|
|
70
|
+
export * from './decorators/ai-agent-function.decorator.js';
|
|
71
|
+
export * from './providers/ai-egress.helper.js';
|
|
72
|
+
export * from './providers/ai-sdk.packages.js';
|
|
73
|
+
export * from './providers/ai-sdk.provider.js';
|
|
69
74
|
export * from './providers/claude-cli.provider.js';
|
|
70
75
|
export * from './providers/llm-provider.factory.js';
|
|
71
76
|
export * from './providers/openai-compatible.provider.js';
|
|
72
77
|
export * from './services/ai-crypto.service.js';
|
|
78
|
+
export * from './services/core-ai-agent-function.bridge.js';
|
|
73
79
|
export * from './services/core-ai-budget.service.js';
|
|
74
80
|
export * from './services/core-ai-connection-preference.service.js';
|
|
75
81
|
export * from './services/core-ai-connection-resolver.service.js';
|
|
@@ -89,6 +95,8 @@ export * from './services/core-ai-mode.service.js';
|
|
|
89
95
|
export * from './services/core-ai-tool-policy.service.js';
|
|
90
96
|
export * from './services/core-ai-user-setting.service.js';
|
|
91
97
|
export * from './services/core-ai.service.js';
|
|
98
|
+
export * from './tools/ai-tool-result.helper.js';
|
|
99
|
+
export * from './tools/ai-tool-schema.helper.js';
|
|
92
100
|
export * from './tools/ai-tool.base.js';
|
|
93
101
|
export * from './tools/ai-tool.registry.js';
|
|
94
102
|
export * from './tools/ask-user-question.tool.js';
|
|
@@ -129,7 +129,11 @@ export interface IAiTool {
|
|
|
129
129
|
/** Unique tool name (snake_case recommended, stable across versions). */
|
|
130
130
|
readonly name: string;
|
|
131
131
|
|
|
132
|
-
/**
|
|
132
|
+
/**
|
|
133
|
+
* The tool's input arguments: a JSON Schema object, or (12.10.0) a Standard Schema with JSON Schema — Zod 4.2+,
|
|
134
|
+
* ArkType, Valibot via `toStandardJsonSchema()`. `AiToolRegistry.register()` stores a Standard Schema as its JSON
|
|
135
|
+
* Schema and validates the arguments before `authorize()` and `execute()` (`withStandardSchemaParameters()`).
|
|
136
|
+
*/
|
|
133
137
|
readonly parameters: Record<string, any>;
|
|
134
138
|
|
|
135
139
|
/**
|
|
@@ -145,6 +145,12 @@ export interface LlmCompletionOptions {
|
|
|
145
145
|
|
|
146
146
|
/** Per-request timeout in milliseconds. */
|
|
147
147
|
timeoutMs?: number;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Cancels the call (12.10.0). Honoured by the AI SDK transport (`AiSdkProvider`); a provider that ignores it still
|
|
151
|
+
* ends at `timeoutMs`.
|
|
152
|
+
*/
|
|
153
|
+
abortSignal?: AbortSignal;
|
|
148
154
|
}
|
|
149
155
|
|
|
150
156
|
/**
|
|
@@ -29,6 +29,8 @@ export const AiMcpOAuthCodeSchema = createSchema(
|
|
|
29
29
|
codeChallenge: { type: String },
|
|
30
30
|
// The TTL: MongoDB gets its index from the service, a SQL table its sweep (`CorePersistenceLifecycle`)
|
|
31
31
|
createdAt: { expires: AI_MCP_OAUTH_CODE_TTL_SECONDS, type: Date },
|
|
32
|
+
// RFC 8707 resource the code is bound to (12.10.0); absent on a code from before
|
|
33
|
+
resource: { type: String },
|
|
32
34
|
userId: { type: String },
|
|
33
35
|
},
|
|
34
36
|
{ autoIndex: false, collection: 'aiMcpOAuthCodes', versionKey: false },
|
|
@@ -39,6 +41,8 @@ export const AiMcpOAuthRefreshTokenSchema = createSchema(
|
|
|
39
41
|
{
|
|
40
42
|
clientId: { type: String },
|
|
41
43
|
createdAt: { type: Date },
|
|
44
|
+
// RFC 8707 resource the grant is bound to (12.10.0); absent on a token from before — then /ai/mcp only
|
|
45
|
+
resource: { type: String },
|
|
42
46
|
token: { index: { unique: true }, type: String },
|
|
43
47
|
userId: { type: String },
|
|
44
48
|
},
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Logger, ServiceUnavailableException } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
import { ConfigService } from '../../../common/services/config.service.js';
|
|
4
|
+
import { ErrorCode } from '../../error-code/error-codes.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The AI egress allowlist (`ai.allowedBaseUrlHosts`) as functions, for every outbound path the AI module constructs —
|
|
8
|
+
* the OpenAI-compatible provider and the AI SDK transport alike (nestjs-ai plan §2). One implementation, so a model
|
|
9
|
+
* provider a project builds with the AI SDK (`createAnthropic({ fetch })`) is held to exactly the rule the built-in
|
|
10
|
+
* provider is.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const logger = new Logger('AiEgress');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Lowercase, trim, and drop a fully-qualifying trailing dot — applied to BOTH the allowlist entry and the URL, so
|
|
17
|
+
* neither side wins by spelling one DNS name differently (`llm.example.com.` vs `llm.example.com`).
|
|
18
|
+
*/
|
|
19
|
+
export function normaliseAiEgressHost(value: string): string {
|
|
20
|
+
return value
|
|
21
|
+
.trim()
|
|
22
|
+
.toLowerCase()
|
|
23
|
+
.replace(/\.(?=$|:)/, '');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The configured allowlist as normalised entries; `[]` when unset (permissive — a local Ollama works out of the box).
|
|
28
|
+
*
|
|
29
|
+
* A comma-separated STRING is split rather than rejected: `NSC__AI__ALLOWED_BASE_URL_HOSTS` arrives as one, and reading
|
|
30
|
+
* it as "not configured" silently switched the control off until 11.39.x. A value that is neither array nor string
|
|
31
|
+
* carries no hostnames: the list is empty and that is LOGGED, because from the outside it looks exactly like "unset".
|
|
32
|
+
*/
|
|
33
|
+
export function resolveAiEgressAllowlist(log: Pick<Logger, 'error'> = logger): string[] {
|
|
34
|
+
const configured = ConfigService.get<unknown>('ai.allowedBaseUrlHosts');
|
|
35
|
+
if (configured === undefined || configured === null) {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
const entries = typeof configured === 'string' ? configured.split(',') : configured;
|
|
39
|
+
if (!Array.isArray(entries)) {
|
|
40
|
+
log.error(
|
|
41
|
+
`ai.allowedBaseUrlHosts is a ${typeof configured} and carries no hostnames — the SSRF egress ` +
|
|
42
|
+
'allowlist is NOT active. Use an array or a comma-separated string.',
|
|
43
|
+
);
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
return entries.map((host) => normaliseAiEgressHost(String(host))).filter(Boolean);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The spellings of a URL's host an allowlist entry may name: `host` (with a non-default port), `hostname` (any port),
|
|
51
|
+
* and `hostname:<default port>` for an operator who wrote the port out. Nothing here widens the set of reachable hosts.
|
|
52
|
+
*/
|
|
53
|
+
export function aiEgressHostCandidates(url: URL): string[] {
|
|
54
|
+
const defaultPort = url.protocol === 'https:' ? '443' : url.protocol === 'http:' ? '80' : '';
|
|
55
|
+
const candidates = [url.host, url.hostname];
|
|
56
|
+
if (defaultPort && url.host === url.hostname) {
|
|
57
|
+
candidates.push(`${url.hostname}:${defaultPort}`);
|
|
58
|
+
}
|
|
59
|
+
return candidates;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Throws `ServiceUnavailableException` (`AI_CONNECTION_NOT_AVAILABLE`) when an allowlist is configured and the URL's
|
|
64
|
+
* host is not on it, `AI_CONNECTION_INVALID_URL` when the URL does not parse. No allowlist → every URL passes.
|
|
65
|
+
*/
|
|
66
|
+
export function assertAiEgressAllowed(url: string | URL, connectionName = 'AI connection'): void {
|
|
67
|
+
const allowedHosts = resolveAiEgressAllowlist();
|
|
68
|
+
if (!allowedHosts.length) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
let parsed: URL;
|
|
72
|
+
try {
|
|
73
|
+
parsed = url instanceof URL ? url : new URL(url);
|
|
74
|
+
} catch {
|
|
75
|
+
throw new ServiceUnavailableException(ErrorCode.AI_CONNECTION_INVALID_URL);
|
|
76
|
+
}
|
|
77
|
+
const candidates = aiEgressHostCandidates(parsed).map(normaliseAiEgressHost);
|
|
78
|
+
if (!candidates.some((candidate) => allowedHosts.includes(candidate))) {
|
|
79
|
+
logger.warn(`AI connection "${connectionName}" host "${parsed.host}" is not in ai.allowedBaseUrlHosts`);
|
|
80
|
+
throw new ServiceUnavailableException(ErrorCode.AI_CONNECTION_NOT_AVAILABLE);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A `fetch` that refuses every URL outside `ai.allowedBaseUrlHosts` before sending — for a model provider a project
|
|
86
|
+
* builds itself (`createAnthropic({ apiKey, fetch })`). Hand it to the provider; the AI SDK provider packages send every
|
|
87
|
+
* request through the `fetch` they were given. The allowlist is read on every call, so a configuration change applies
|
|
88
|
+
* without a restart.
|
|
89
|
+
*/
|
|
90
|
+
export function createAiEgressFetch(connectionName = 'AI connection', base: typeof fetch = fetch): typeof fetch {
|
|
91
|
+
// async: a refusal is a rejected promise, as every fetch failure is — never a synchronous throw
|
|
92
|
+
const guarded = async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
|
|
93
|
+
const url = typeof input === 'string' || input instanceof URL ? input : input.url;
|
|
94
|
+
assertAiEgressAllowed(url, connectionName);
|
|
95
|
+
return base(input, init);
|
|
96
|
+
};
|
|
97
|
+
return guarded as typeof fetch;
|
|
98
|
+
}
|