@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.
Files changed (150) hide show
  1. package/.claude/rules/configurable-features.md +4 -0
  2. package/.claude/rules/package-management.md +35 -6
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +8 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  22. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  23. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  24. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  25. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  26. package/dist/core/common/services/request-context.service.d.ts +2 -0
  27. package/dist/core/common/services/request-context.service.js +3 -0
  28. package/dist/core/common/services/request-context.service.js.map +1 -1
  29. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  30. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  31. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  32. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  33. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  34. package/dist/core/modules/ai/core-ai.module.js +2 -0
  35. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  36. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  37. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  38. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  39. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  40. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  41. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  42. package/dist/core/modules/ai/index.d.ts +8 -0
  43. package/dist/core/modules/ai/index.js +8 -0
  44. package/dist/core/modules/ai/index.js.map +1 -1
  45. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  46. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  47. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  48. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  49. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  50. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  51. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  52. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  53. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  54. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  57. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  58. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  59. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  60. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  61. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  62. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  63. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  64. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  65. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  66. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  67. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  68. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  69. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  70. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  71. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  72. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  73. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  74. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  75. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  76. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  77. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  78. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  79. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  80. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  81. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  82. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  83. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  84. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  85. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  86. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  87. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  88. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  89. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  90. package/dist/core/modules/file/core-file.controller.js +8 -0
  91. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  92. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  93. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  94. package/dist/core.module.js +2 -1
  95. package/dist/core.module.js.map +1 -1
  96. package/dist/index.d.ts +1 -0
  97. package/dist/index.js +1 -0
  98. package/dist/index.js.map +1 -1
  99. package/dist/types/graphql-upload.d.ts +34 -2
  100. package/docs/REQUEST-LIFECYCLE.md +46 -9
  101. package/docs/security-overrides.md +44 -10
  102. package/migration-guides/12.9.3-to-12.9.4.md +137 -0
  103. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  104. package/package.json +62 -37
  105. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  106. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  107. package/src/core/common/helpers/context.helper.ts +14 -0
  108. package/src/core/common/helpers/decorator.helper.ts +5 -0
  109. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  110. package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
  111. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  112. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  113. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  114. package/src/core/common/services/request-context.service.ts +11 -0
  115. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  116. package/src/core/modules/ai/README.md +101 -0
  117. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  118. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  119. package/src/core/modules/ai/core-ai.module.ts +3 -0
  120. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  121. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  122. package/src/core/modules/ai/index.ts +8 -0
  123. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  124. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  125. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  126. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  127. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  128. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  129. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  130. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  131. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  132. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  133. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  134. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  135. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  136. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  137. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  138. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  139. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  140. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  141. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  142. package/src/core/modules/better-auth/README.md +204 -0
  143. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  144. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  145. package/src/core/modules/file/README.md +1 -0
  146. package/src/core/modules/file/core-file.controller.ts +17 -0
  147. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  148. package/src/core.module.ts +5 -1
  149. package/src/index.ts +1 -0
  150. package/src/types/graphql-upload.d.ts +34 -2
@@ -19,6 +19,7 @@ import { CoreAiResponse } from '../models/core-ai-response.model.js';
19
19
  import { CoreAiUsage } from '../models/core-ai-usage.model.js';
20
20
  import { CoreAiPromptInput } from '../inputs/core-ai-prompt.input.js';
21
21
  import { LlmProviderFactory } from '../providers/llm-provider.factory.js';
22
+ import { sanitizeToolResultForModel } from '../tools/ai-tool-result.helper.js';
22
23
  import { AiHookRegistry } from '../hooks/ai-hook.registry.js';
23
24
  import { AiHookEvent } from '../interfaces/ai-hook.interface.js';
24
25
  import { AiToolRegistry } from '../tools/ai-tool.registry.js';
@@ -1827,12 +1828,9 @@ export class CoreAiService {
1827
1828
  * model instances.
1828
1829
  */
1829
1830
  protected sanitizeResult(value: unknown, user: AiToolContext['currentUser']): unknown {
1830
- if (Array.isArray(value)) {
1831
- return value.map((v) => this.sanitizeResult(v, user));
1832
- }
1833
- if (value && typeof (value as { securityCheck?: unknown }).securityCheck === 'function') {
1834
- return (value as { securityCheck: (u: unknown) => unknown }).securityCheck(user);
1835
- }
1836
- return value;
1831
+ // securityCheck() on model instances, then the secret fields (password hash, reset tokens, encrypted API keys,
1832
+ // `security.secretFields`) leave the result whatever shape the tool returned them in — a plain object or a lean
1833
+ // document skipped securityCheck() and reached the model with them until 12.10.0
1834
+ return sanitizeToolResultForModel(value, user);
1837
1835
  }
1838
1836
  }
@@ -0,0 +1,153 @@
1
+ import { FRAMEWORK_SECRET_FIELDS } from '../../../common/helpers/redact-secrets.helper.js';
2
+ import { columnName } from '../../../common/persistence/sql/sql-naming.js';
3
+ import { ConfigService } from '../../../common/services/config.service.js';
4
+
5
+ /** How deep a result is walked; below that it is left as it is. */
6
+ const MAX_DEPTH = 32;
7
+
8
+ /**
9
+ * Removes secret fields from a tool result before it reaches the model (12.10.0, nestjs-ai plan §1: "secrets never
10
+ * reach a model").
11
+ *
12
+ * A tool result travels into the model's context and back to the client in `actions[].result`; the HTTP safety net
13
+ * (`CheckSecurityInterceptor`) never sees it on the model's side. `CoreAiService.sanitizeResult()` ran
14
+ * `securityCheck()` on model instances only, so a tool that returned a lean document or a plain object
15
+ * (`{ ...user }`) handed its `password` hash, reset token or encrypted API key to the model. The field list is the
16
+ * interceptor's: the framework defaults plus `security.secretFields`, each also under its SQL column name.
17
+ *
18
+ * Returns a copy; the tool's own value is never mutated. Values that are not plain data (Date, Buffer, ObjectId) are kept
19
+ * as they are; a Mongoose document is replaced by its stripped `toJSON()`; a class instance is copied to a plain object
20
+ * of its own enumerable fields.
21
+ */
22
+ export function stripSecretFieldsForModel(value: unknown): unknown {
23
+ return strip(value, secretKeys(), new WeakMap(), 0);
24
+ }
25
+
26
+ /**
27
+ * A tool result as a model (or an MCP client) may read it: `securityCheck(user)` on every model instance at any depth —
28
+ * inside arrays and plain wrappers such as the documented `{ success, data }` — the step the HTTP response pipeline takes,
29
+ * then {@link stripSecretFieldsForModel}. Used by the chat loop (`CoreAiService.sanitizeResult()`) and the MCP server
30
+ * (`CoreAiMcpService.mcpCallTool()`).
31
+ */
32
+ export function sanitizeToolResultForModel(value: unknown, user: unknown): unknown {
33
+ return stripSecretFieldsForModel(applySecurityChecks(value, user, new WeakMap(), 0));
34
+ }
35
+
36
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
37
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
38
+ return false;
39
+ }
40
+ const proto = Object.getPrototypeOf(value);
41
+ return proto === Object.prototype || proto === null;
42
+ }
43
+
44
+ function applySecurityChecks(value: unknown, user: unknown, seen: WeakMap<object, unknown>, depth: number): unknown {
45
+ if (!value || typeof value !== 'object' || depth > MAX_DEPTH) {
46
+ return value;
47
+ }
48
+ if (seen.has(value)) {
49
+ return seen.get(value);
50
+ }
51
+ if (typeof (value as { securityCheck?: unknown }).securityCheck === 'function') {
52
+ const checked = (value as { securityCheck: (u: unknown) => unknown }).securityCheck(user);
53
+ seen.set(value, checked);
54
+ return checked;
55
+ }
56
+ if (Array.isArray(value)) {
57
+ const copy: unknown[] = [];
58
+ seen.set(value, copy);
59
+ for (const item of value) {
60
+ copy.push(applySecurityChecks(item, user, seen, depth + 1));
61
+ }
62
+ return copy;
63
+ }
64
+ if (!isPlainObject(value)) {
65
+ return value;
66
+ }
67
+ const copy: Record<PropertyKey, unknown> = {};
68
+ seen.set(value, copy);
69
+ for (const key of Reflect.ownKeys(value)) {
70
+ if (Object.prototype.propertyIsEnumerable.call(value, key)) {
71
+ copy[key] = applySecurityChecks((value as Record<PropertyKey, unknown>)[key], user, seen, depth + 1);
72
+ }
73
+ }
74
+ return copy;
75
+ }
76
+
77
+ function secretKeys(): Set<string> {
78
+ const configured = ConfigService.configFastButReadOnly?.security?.secretFields;
79
+ const fields = [...FRAMEWORK_SECRET_FIELDS, ...(Array.isArray(configured) ? configured : [])];
80
+ const keys = new Set<string>();
81
+ for (const field of fields) {
82
+ if (typeof field !== 'string') {
83
+ continue;
84
+ }
85
+ keys.add(field);
86
+ try {
87
+ keys.add(columnName(field));
88
+ } catch {
89
+ // Not an identifier, so no column carries it
90
+ }
91
+ }
92
+ return keys;
93
+ }
94
+
95
+ function isOpaque(value: object): boolean {
96
+ return (
97
+ value instanceof Date ||
98
+ value instanceof RegExp ||
99
+ value instanceof Map ||
100
+ value instanceof Set ||
101
+ Buffer.isBuffer(value) ||
102
+ ArrayBuffer.isView(value) ||
103
+ (value as { _bsontype?: unknown })._bsontype !== undefined
104
+ );
105
+ }
106
+
107
+ /** A hydrated Mongoose document: what `JSON.stringify` would write of it is its `toJSON()`. */
108
+ function isMongooseDocument(value: object): value is { toJSON(): unknown } {
109
+ return (value as { $__?: unknown }).$__ !== undefined && typeof (value as { toJSON?: unknown }).toJSON === 'function';
110
+ }
111
+
112
+ function strip(value: unknown, keys: Set<string>, seen: WeakMap<object, unknown>, depth: number): unknown {
113
+ if (!value || typeof value !== 'object' || depth > MAX_DEPTH) {
114
+ return value;
115
+ }
116
+ if (seen.has(value)) {
117
+ return seen.get(value);
118
+ }
119
+ if (Array.isArray(value)) {
120
+ const copy: unknown[] = [];
121
+ seen.set(value, copy);
122
+ for (const item of value) {
123
+ copy.push(strip(item, keys, seen, depth + 1));
124
+ }
125
+ return copy;
126
+ }
127
+ if (isOpaque(value)) {
128
+ return value;
129
+ }
130
+ // A Mongoose document is serialised through its toJSON() — every stored field, secrets included — so that is what
131
+ // gets stripped
132
+ if (isMongooseDocument(value)) {
133
+ const json = strip(value.toJSON(), keys, seen, depth + 1);
134
+ seen.set(value, json);
135
+ return json;
136
+ }
137
+ const copy: Record<string, unknown> = {};
138
+ seen.set(value, copy);
139
+ for (const [key, item] of Object.entries(value)) {
140
+ if (keys.has(key)) {
141
+ continue;
142
+ }
143
+ copy[key] = strip(item, keys, seen, depth + 1);
144
+ }
145
+ // Symbol keys are markers of the framework's own (the ask_user_question sentinel), never data a model reads: JSON
146
+ // drops them, the run loop needs them
147
+ for (const symbol of Object.getOwnPropertySymbols(value)) {
148
+ if (Object.prototype.propertyIsEnumerable.call(value, symbol)) {
149
+ (copy as Record<symbol, unknown>)[symbol] = (value as Record<symbol, unknown>)[symbol];
150
+ }
151
+ }
152
+ return copy;
153
+ }
@@ -0,0 +1,134 @@
1
+ import type { AiToolAuthorization, AiToolContext, IAiTool } from '../interfaces/ai-tool.interface.js';
2
+
3
+ /**
4
+ * Standard Schema support for `IAiTool.parameters` (12.10.0, nestjs-ai plan §3): a tool may declare its parameters
5
+ * with Zod 4.2+, ArkType, Valibot (`toStandardJsonSchema()`) or any other schema that implements Standard Schema WITH
6
+ * JSON Schema (`~standard.jsonSchema`) — the shape `@nestjs/ai` and `@nestjs/mcp` accept too, so one schema serves all
7
+ * three. Duck-typed: the core imports no schema library.
8
+ */
9
+
10
+ /** A Standard Schema that also produces JSON Schema (https://standardschema.dev). */
11
+ export interface AiStandardSchema {
12
+ readonly '~standard': {
13
+ readonly jsonSchema?: { readonly input: (options: { target: string }) => Record<string, unknown> };
14
+ readonly validate: (
15
+ value: unknown,
16
+ ) =>
17
+ | { readonly issues?: undefined; readonly value: unknown }
18
+ | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray<unknown> }> }
19
+ | Promise<
20
+ | { readonly issues?: undefined; readonly value: unknown }
21
+ | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray<unknown> }> }
22
+ >;
23
+ readonly vendor: string;
24
+ readonly version: 1;
25
+ };
26
+ }
27
+
28
+ /** Whether `value` is a Standard Schema (with or without JSON Schema). */
29
+ export function isStandardSchema(value: unknown): value is AiStandardSchema {
30
+ const standard = (value as AiStandardSchema | undefined)?.['~standard'];
31
+ return !!standard && typeof standard === 'object' && typeof standard.validate === 'function';
32
+ }
33
+
34
+ /** JSON Schema drafts in order of preference: what model providers read, then what MCP uses. */
35
+ const JSON_SCHEMA_TARGETS = ['draft-07', 'draft-2020-12'];
36
+
37
+ /**
38
+ * The JSON Schema of a Standard Schema's INPUT side (what the model writes). Throws when the schema cannot produce one
39
+ * or describes something other than an object — a tool's arguments are an object, and a schema the model cannot be
40
+ * sent is a configuration error, not something to guess around.
41
+ */
42
+ export function standardSchemaToJsonSchema(schema: AiStandardSchema, where: string): Record<string, any> {
43
+ const standard = schema['~standard'];
44
+ if (typeof standard.jsonSchema?.input !== 'function') {
45
+ throw new Error(
46
+ `${where}: the "${standard.vendor}" schema cannot produce JSON Schema (no ~standard.jsonSchema), which the model ` +
47
+ 'needs. Zod needs 4.2 or later; Valibot needs toStandardJsonSchema() from @valibot/to-json-schema.',
48
+ );
49
+ }
50
+ let failure: unknown;
51
+ for (const target of JSON_SCHEMA_TARGETS) {
52
+ try {
53
+ const root = standard.jsonSchema.input({ target });
54
+ if (root && typeof root === 'object') {
55
+ if (root.type !== undefined && root.type !== 'object') {
56
+ throw new Error(
57
+ `${where}: tool arguments are an object, and this schema describes ${JSON.stringify(root.type)}`,
58
+ );
59
+ }
60
+ return root as Record<string, any>;
61
+ }
62
+ } catch (error) {
63
+ failure = error;
64
+ if ((error as Error)?.message?.startsWith(where)) {
65
+ throw error;
66
+ }
67
+ }
68
+ }
69
+ throw new Error(`${where}: the schema cannot be converted to JSON Schema: ${(failure as Error)?.message ?? failure}`);
70
+ }
71
+
72
+ /** Validation issues as one line each, with their path — what the model reads to correct itself. */
73
+ export function formatSchemaIssues(issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<unknown> }>): string {
74
+ return issues
75
+ .map((issue) => {
76
+ const path = (issue.path ?? [])
77
+ .map((segment) =>
78
+ String(
79
+ segment && typeof segment === 'object' && 'key' in segment ? (segment as { key: unknown }).key : segment,
80
+ ),
81
+ )
82
+ .join('.');
83
+ return path ? `${path}: ${issue.message}` : issue.message;
84
+ })
85
+ .join('; ');
86
+ }
87
+
88
+ /**
89
+ * A tool whose `parameters` is a Standard Schema, as the registry stores it: `parameters` becomes the JSON Schema (what
90
+ * the model, the prompt catalog and MCP `tools/list` read), and `authorize()` and `execute()` receive the VALIDATED
91
+ * arguments — invalid ones never reach either: `authorize()` refuses with the issues, `execute()` reports them as a
92
+ * failed call the model can correct. Any other tool is returned unchanged.
93
+ */
94
+ export function withStandardSchemaParameters(tool: IAiTool): IAiTool {
95
+ const schema: unknown = tool.parameters;
96
+ if (!isStandardSchema(schema)) {
97
+ return tool;
98
+ }
99
+ const where = `AI tool "${tool.name}" parameters`;
100
+ const jsonSchema = standardSchemaToJsonSchema(schema, where);
101
+
102
+ const validate = async (args: Record<string, any>) => {
103
+ const outcome = await schema['~standard'].validate(args ?? {});
104
+ if ('issues' in outcome && outcome.issues) {
105
+ return { error: `Invalid arguments: ${formatSchemaIssues(outcome.issues)}` };
106
+ }
107
+ return { value: ((outcome as { value?: unknown }).value ?? {}) as Record<string, any> };
108
+ };
109
+
110
+ const normalised: IAiTool = Object.create(tool, {
111
+ execute: {
112
+ value: async (args: Record<string, any>, context: AiToolContext) => {
113
+ const checked = await validate(args);
114
+ if ('error' in checked) {
115
+ return { message: checked.error, success: false };
116
+ }
117
+ return tool.execute.call(tool, checked.value, context);
118
+ },
119
+ },
120
+ parameters: { enumerable: true, value: jsonSchema },
121
+ });
122
+ if (typeof tool.authorize === 'function') {
123
+ Object.defineProperty(normalised, 'authorize', {
124
+ value: async (args: Record<string, any>, context: AiToolContext): Promise<AiToolAuthorization | boolean> => {
125
+ const checked = await validate(args);
126
+ if ('error' in checked) {
127
+ return { allowed: false, reason: checked.error };
128
+ }
129
+ return tool.authorize.call(tool, checked.value, context);
130
+ },
131
+ });
132
+ }
133
+ return normalised;
134
+ }
@@ -10,6 +10,7 @@ import {
10
10
  tenantSatisfiableRoles,
11
11
  } from '../../tenant/core-tenant.helpers.js';
12
12
  import { IAiTool } from '../interfaces/ai-tool.interface.js';
13
+ import { withStandardSchemaParameters } from './ai-tool-schema.helper.js';
13
14
 
14
15
  /**
15
16
  * Minimal shape of the current user needed for tool-visibility checks.
@@ -40,12 +41,16 @@ export class AiToolRegistry {
40
41
 
41
42
  /**
42
43
  * Register (or override) a tool by its name.
44
+ *
45
+ * `parameters` may be a Standard Schema with JSON Schema (Zod 4.2+, ArkType, Valibot via `toStandardJsonSchema()`)
46
+ * since 12.10.0: it is stored as its JSON Schema, and `authorize()` / `execute()` receive validated arguments
47
+ * (`withStandardSchemaParameters()`). A schema that cannot produce JSON Schema throws here, at registration.
43
48
  */
44
49
  register(tool: IAiTool): void {
45
50
  if (this.tools.has(tool.name)) {
46
51
  this.logger.warn(`AI tool "${tool.name}" is being overridden.`);
47
52
  }
48
- this.tools.set(tool.name, tool);
53
+ this.tools.set(tool.name, withStandardSchemaParameters(tool));
49
54
  this.logger.debug(`Registered AI tool: ${tool.name}`);
50
55
  }
51
56
 
@@ -1,13 +1,18 @@
1
- import { CanActivate, ExecutionContext, Logger, mixin, Optional } from '@nestjs/common';
1
+ import { CanActivate, ExecutionContext, Logger, mixin, Optional, UnauthorizedException } from '@nestjs/common';
2
2
  import { ModuleRef } from '@nestjs/core';
3
3
  import { GqlExecutionContext } from '@nestjs/graphql';
4
4
  import { AuthModuleOptions, Type } from '@nestjs/passport';
5
5
  import passport from 'passport';
6
6
 
7
+ import {
8
+ isAgentCallContext,
9
+ resolveAgentCallRequest,
10
+ } from '../../../common/helpers/execution-context-request.helper.js';
7
11
  import { enforceApiTokenRoute, getApiTokenContext } from '../../api-token/core-api-token.helpers.js';
8
12
  import { BetterAuthTokenService } from '../../better-auth/better-auth-token.service.js';
9
13
  import { BetterAuthenticatedUser } from '../../better-auth/better-auth.types.js';
10
14
  import { CoreBetterAuthService } from '../../better-auth/core-better-auth.service.js';
15
+ import { ErrorCode } from '../../error-code/index.js';
11
16
  import { AuthGuardStrategy } from '../auth-guard-strategy.enum.js';
12
17
  import { ExpiredRefreshTokenException } from '../exceptions/expired-refresh-token.exception.js';
13
18
  import { ExpiredTokenException } from '../exceptions/expired-token.exception.js';
@@ -165,6 +170,11 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
165
170
 
166
171
  const options = { ...defaultOptions, ...this.options };
167
172
  const request = this.getRequest(context);
173
+ // An agent function / MCP call without a request is anonymous (nestjs-ai plan §1): this guard authenticates, so
174
+ // it refuses — Passport would otherwise be handed nothing, or the call's arguments.
175
+ if (!request && isAgentCallContext(context)) {
176
+ throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
177
+ }
168
178
  const existingUser = request?.[options.property || defaultOptions.property];
169
179
 
170
180
  // An API token was already authenticated by CoreApiTokenMiddleware. Neither Passport nor
@@ -195,7 +205,9 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
195
205
  }
196
206
 
197
207
  // Proceed with Passport authentication for other strategies
198
- const response = context?.switchToHttp()?.getResponse();
208
+ // On an agent / MCP call the second argument is the call, not a response: Passport gets the request's own
209
+ // response object (Express sets `req.res`).
210
+ const response = isAgentCallContext(context) ? request?.res : context?.switchToHttp()?.getResponse();
199
211
  const passportFn = createPassportContext(request, response);
200
212
  const user = await passportFn(
201
213
  type || this.options?.defaultStrategy,
@@ -270,6 +282,11 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
270
282
  * Prepare request
271
283
  */
272
284
  getRequest<T = any>(context: ExecutionContext): T {
285
+ // An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
286
+ if (isAgentCallContext(context)) {
287
+ return (resolveAgentCallRequest(context) ?? null) as T;
288
+ }
289
+
273
290
  // Try to get request GraphQL context
274
291
  try {
275
292
  const ctx = GqlExecutionContext.create(context)?.getContext();
@@ -2,6 +2,10 @@ import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable }
2
2
  import { GqlExecutionContext } from '@nestjs/graphql';
3
3
 
4
4
  import { LegacyAuthRateLimiter } from '../services/legacy-auth-rate-limiter.service.js';
5
+ import {
6
+ isAgentCallContext,
7
+ resolveAgentCallRequest,
8
+ } from '../../../common/helpers/execution-context-request.helper.js';
5
9
 
6
10
  /**
7
11
  * Guard for rate limiting Legacy Auth endpoints
@@ -72,8 +76,11 @@ export class LegacyAuthRateLimitGuard implements CanActivate {
72
76
  return { endpoint, ip };
73
77
  }
74
78
 
75
- // HTTP context
76
- const request = context.switchToHttp().getRequest();
79
+ // HTTP context — or an agent function / MCP call, whose request is the one it runs in, never its arguments
80
+ // (nestjs-ai plan §1)
81
+ const request = isAgentCallContext(context)
82
+ ? resolveAgentCallRequest(context)
83
+ : context.switchToHttp().getRequest();
77
84
  const ip = this.getClientIp(request);
78
85
 
79
86
  // The handler, never the URL: the URL carries the query string and the client's spelling of the path
@@ -10,7 +10,11 @@ import {
10
10
  import { ModuleRef, Reflector } from '@nestjs/core';
11
11
  import { GqlExecutionContext } from '@nestjs/graphql';
12
12
 
13
- import { resolveGuardRequest } from '../../../common/helpers/execution-context-request.helper.js';
13
+ import {
14
+ isAgentCallContext,
15
+ resolveAgentCallRequest,
16
+ resolveGuardRequest,
17
+ } from '../../../common/helpers/execution-context-request.helper.js';
14
18
  import { firstValueFrom, isObservable } from 'rxjs';
15
19
 
16
20
  import { RoleEnum } from '../../../common/enums/role.enum.js';
@@ -147,6 +151,19 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
147
151
  throw new ForbiddenException(ErrorCode.ACCESS_DENIED);
148
152
  }
149
153
 
154
+ // An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
155
+ // stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
156
+ // where the route is public. Kept in sync with BetterAuthRolesGuard (nestjs-ai plan §1).
157
+ if (isAgentCallContext(context) && !this.getRequest(context)) {
158
+ // The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
159
+ // S_EVERYONE does not open a method that asks for S_USER
160
+ const effective = reflectorRoles?.[0]?.some((value) => !!value) ? reflectorRoles[0] : roles;
161
+ if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
162
+ return true;
163
+ }
164
+ throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
165
+ }
166
+
150
167
  // API tokens are decided BEFORE the public-route shortcut below: a token is denied on every route
151
168
  // that does not declare @ApiTokenScopes(), public ones included (see core-api-token.helpers).
152
169
  // A tenant token is fully decided there. A user token was authenticated by CoreApiTokenMiddleware,
@@ -289,6 +306,11 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
289
306
  cookies?: Record<string, string>;
290
307
  headers?: Record<string, string | string[] | undefined>;
291
308
  } {
309
+ // An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
310
+ if (isAgentCallContext(context)) {
311
+ return resolveAgentCallRequest(context) ?? null;
312
+ }
313
+
292
314
  // Try GraphQL context first
293
315
  try {
294
316
  const gqlContext = GqlExecutionContext.create(context);
@@ -459,6 +459,17 @@ After integration, verify:
459
459
  an existing user still signs in through it. A provider meant for self-registration carries
460
460
  `disableSignUp: false` (12.3.0+)
461
461
 
462
+ ### Optional: Social provider with its own options (12.10.0+, e.g. Microsoft Entra ID)
463
+
464
+ - [ ] `GET /iam/features` lists the provider in `socialProviders`
465
+ - [ ] `POST /iam/sign-in/social` with `{ "provider": "microsoft", "disableRedirect": true }` answers a `url` with the
466
+ configured tenant in the path (`login.microsoftonline.com/<tenantId>/…`, not `common`) and exactly the
467
+ configured scopes in `scope` (`openid profile email` for an identity-only sign-in)
468
+ - [ ] The app registration's redirect URI is `<baseUrl>/iam/callback/<provider>`
469
+ - [ ] A failed sign-in lands in the app (12.10.0+): `GET <baseUrl>/iam/callback/<provider>` without parameters answers
470
+ `302` to `<appUrl>/auth/login?error=state_not_found`, not the API's "Error" page (`betterAuth.errorUrl`)
471
+ - [ ] The login page shows a text of its own for each `error` code and never renders `error_description`
472
+
462
473
  ### Additional checks for Migration scenario:
463
474
 
464
475
  - [ ] Sign-in via Legacy Auth works for BetterAuth-created users