@composio/core 0.16.0 → 0.18.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 (51) hide show
  1. package/dist/{CustomTool-Bk38kFp0.d.mts → CustomTool-BKhHv2hJ.d.mts} +1 -1
  2. package/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-C4tv-GL1.mjs} +1 -1
  3. package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
  4. package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-CBtSnWrm.mjs} +27 -11
  5. package/dist/cancellation-jUVItfHw.mjs +704 -0
  6. package/dist/{composio-DSs-1AhC.d.mts → composio-CldtZUyC.d.mts} +254 -247
  7. package/dist/{BaseProvider-D7p2OPEx.d.mts → customTool.types-DC5fPOOi.d.mts} +2954 -82
  8. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
  9. package/dist/{errors-BcEUHZbq.mjs → errors-DyZt79fi.mjs} +3 -0
  10. package/dist/experimental/index.d.mts +2 -2
  11. package/dist/experimental/index.mjs +1 -1
  12. package/dist/{fileUtils.node-BQ0fWge3.mjs → fileUtils.node-BwpUOF0s.mjs} +4 -4
  13. package/dist/index.d.mts +105 -7
  14. package/dist/index.mjs +94 -116
  15. package/dist/models/Files.node.mjs +2 -2
  16. package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-B0w8dqpv.mjs} +23 -6
  17. package/dist/ssrfGuard.node-DlxO8uzr.mjs +307 -0
  18. package/dist/{types-B4k-qoOf.d.mts → types-BgsRW-XH.d.mts} +2 -2
  19. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  20. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  21. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  22. package/dist/utils/modifiers/FileToolModifier.node.mjs +57 -101
  23. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  24. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  25. package/dist/utils/ssrfGuard.node.d.mts +25 -6
  26. package/dist/utils/ssrfGuard.node.mjs +2 -152
  27. package/dist/utils/ssrfGuard.workerd.d.mts +13 -1
  28. package/dist/utils/ssrfGuard.workerd.mjs +13 -1
  29. package/package.json +8 -4
  30. package/src/errors/ToolErrors.ts +1 -0
  31. package/src/errors/ValidationErrors.ts +2 -0
  32. package/src/index.ts +6 -0
  33. package/src/models/RemoteFile.ts +7 -2
  34. package/src/models/ToolRouterSession.ts +36 -8
  35. package/src/models/ToolRouterSessionFileMount.ts +14 -8
  36. package/src/models/Tools.ts +102 -39
  37. package/src/provider/BaseProvider.ts +53 -1
  38. package/src/provider/OpenAIProvider.ts +43 -15
  39. package/src/services/telemetry/TelemetryService.ts +27 -12
  40. package/src/types/provider.types.ts +15 -0
  41. package/src/utils/fileUtils.node.ts +8 -2
  42. package/src/utils/jsonSchema.ts +505 -27
  43. package/src/utils/modifiers/FileToolModifier.node.ts +85 -181
  44. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +199 -0
  45. package/src/utils/pinnedDispatcher.node.ts +118 -0
  46. package/src/utils/sensitiveFileUploadPaths.ts +36 -9
  47. package/src/utils/ssrfGuard.node.ts +100 -11
  48. package/src/utils/ssrfGuard.workerd.ts +16 -0
  49. package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
  50. package/dist/cancellation-NVtGf3St.mjs +0 -364
  51. package/dist/customTool.types-cGHcIBX-.d.mts +0 -2859
@@ -1,153 +1,3 @@
1
- import { t as ComposioBlockedInternalUrlError } from "../SsrfErrors-DNJt57GL.mjs";
2
- import { lookup } from "node:dns/promises";
3
- import { isIP } from "node:net";
1
+ import { i as ssrfSafeFetchWhereSupported, n as isBlockedIp, r as ssrfSafeFetch, t as assertSafeFetchTarget } from "../ssrfGuard.node-DlxO8uzr.mjs";
4
2
 
5
- //#region src/utils/ssrfGuard.node.ts
6
- /**
7
- * SSRF guard for user-supplied URL file inputs.
8
- *
9
- * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
10
- * file upload during tool execution fetch arbitrary user-provided URLs. Without
11
- * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
12
- * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
13
- * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
14
- * space — turning the SDK into a server-side request forgery probe.
15
- *
16
- * This module validates the *resolved* address (not just the hostname string,
17
- * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
18
- * follows redirects manually so each hop is re-validated.
19
- *
20
- * Known residual: a DNS name could resolve to a public address here and rebind
21
- * to an internal one before the underlying `fetch` connects (a TOCTOU / DNS
22
- * rebinding window). Closing that fully requires pinning the validated IP at
23
- * connect time (a custom dispatcher), which is out of scope for this guard.
24
- */
25
- const MAX_REDIRECTS = 5;
26
- const ipv4ToLong = (ip) => {
27
- const [a, b, c, d] = ip.split(".").map(Number);
28
- return (a << 24 >>> 0 | b << 16 | c << 8 | d) >>> 0;
29
- };
30
- const IPV4_BLOCKED_CIDRS = [
31
- ["0.0.0.0", 8],
32
- ["10.0.0.0", 8],
33
- ["100.64.0.0", 10],
34
- ["127.0.0.0", 8],
35
- ["169.254.0.0", 16],
36
- ["172.16.0.0", 12],
37
- ["192.0.0.0", 24],
38
- ["192.0.2.0", 24],
39
- ["192.168.0.0", 16],
40
- ["198.18.0.0", 15],
41
- ["198.51.100.0", 24],
42
- ["203.0.113.0", 24],
43
- ["224.0.0.0", 4],
44
- ["240.0.0.0", 4]
45
- ];
46
- const isBlockedIpv4Long = (long) => IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
47
- const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
48
- return (long & mask) === (ipv4ToLong(base) & mask);
49
- });
50
- /**
51
- * Expand an IPv6 string into its 8 16-bit groups, converting any trailing
52
- * dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
53
- * the input cannot be parsed.
54
- */
55
- const expandIpv6 = (ip) => {
56
- let addr = ip;
57
- const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
58
- if (v4Match) {
59
- const long = ipv4ToLong(v4Match[2]);
60
- addr = `${v4Match[1]}${(long >>> 16 & 65535).toString(16)}:${(long & 65535).toString(16)}`;
61
- }
62
- const halves = addr.split("::");
63
- if (halves.length > 2) return null;
64
- const head = halves[0] ? halves[0].split(":") : [];
65
- const tail = halves.length === 2 ? halves[1] ? halves[1].split(":") : [] : [];
66
- let groups;
67
- if (halves.length === 2) {
68
- const missing = 8 - head.length - tail.length;
69
- if (missing < 0) return null;
70
- groups = [
71
- ...head,
72
- ...Array(missing).fill("0"),
73
- ...tail
74
- ];
75
- } else groups = head;
76
- if (groups.length !== 8) return null;
77
- return groups.map((g) => parseInt(g || "0", 16));
78
- };
79
- const isBlockedIpv6 = (ip) => {
80
- const h = expandIpv6(ip);
81
- if (!h) return true;
82
- if (h.every((x) => x === 0)) return true;
83
- if (h.slice(0, 7).every((x) => x === 0) && h[7] === 1) return true;
84
- const isMappedOrCompat = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0 && (h[5] === 65535 || h[5] === 0);
85
- const isNat64 = h[0] === 100 && h[1] === 65435 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
86
- if (isMappedOrCompat || isNat64) return isBlockedIpv4Long((h[6] << 16 >>> 0 | h[7]) >>> 0);
87
- if ((h[0] & 65024) === 64512) return true;
88
- if ((h[0] & 65472) === 65152) return true;
89
- if ((h[0] & 65280) === 65280) return true;
90
- return false;
91
- };
92
- /**
93
- * True when `ip` is a private, loopback, link-local, or otherwise
94
- * non-publicly-routable address. Fails closed (returns `true`) for anything that
95
- * is not a valid IPv4/IPv6 literal.
96
- */
97
- const isBlockedIp = (ip) => {
98
- const family = isIP(ip);
99
- if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
100
- if (family === 6) return isBlockedIpv6(ip);
101
- return true;
102
- };
103
- /**
104
- * Validate a single URL: it must be http(s), its host must resolve, and every
105
- * resolved address must be publicly routable. Throws
106
- * {@link ComposioBlockedInternalUrlError} otherwise.
107
- */
108
- const assertSafeFetchTarget = async (rawUrl) => {
109
- let url;
110
- try {
111
- url = new URL(rawUrl);
112
- } catch {
113
- throw new ComposioBlockedInternalUrlError("Refusing to fetch a malformed URL", { url: rawUrl });
114
- }
115
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new ComposioBlockedInternalUrlError(`Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`, { url: rawUrl });
116
- const host = url.hostname.replace(/^\[|\]$/g, "");
117
- let resolved;
118
- try {
119
- resolved = await lookup(host, {
120
- all: true,
121
- verbatim: true
122
- });
123
- } catch {
124
- throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
125
- }
126
- for (const { address } of resolved) if (isBlockedIp(address)) throw new ComposioBlockedInternalUrlError(`Refusing to fetch "${host}" — it resolves to a private, loopback, or link-local address`, {
127
- url: rawUrl,
128
- resolvedIp: address
129
- });
130
- };
131
- /**
132
- * Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
133
- * connecting and re-validates every redirect hop (redirects are followed
134
- * manually up to {@link MAX_REDIRECTS}). Intermediate redirect bodies are
135
- * cancelled; non-redirect responses are returned unchanged.
136
- */
137
- const ssrfSafeFetch = async (rawUrl, init = {}, maxRedirects = MAX_REDIRECTS) => {
138
- let currentUrl = rawUrl;
139
- for (let hop = 0; hop <= maxRedirects; hop++) {
140
- await assertSafeFetchTarget(currentUrl);
141
- const response = await fetch(currentUrl, {
142
- ...init,
143
- redirect: "manual"
144
- });
145
- if (!(response.status >= 300 && response.status < 400 && response.headers.has("location"))) return response;
146
- await response.body?.cancel().catch(() => void 0);
147
- currentUrl = new URL(response.headers.get("location"), currentUrl).toString();
148
- }
149
- throw new ComposioBlockedInternalUrlError(`Refusing to fetch: too many redirects (max ${maxRedirects})`, { url: rawUrl });
150
- };
151
-
152
- //#endregion
153
- export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch };
3
+ export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -5,5 +5,17 @@
5
5
  * falling back to an unguarded fetch.
6
6
  */
7
7
  declare const ssrfSafeFetch: (rawUrl: string) => Promise<Response>;
8
+ /**
9
+ * Unguarded `fetch`, for the call sites that must keep working here.
10
+ *
11
+ * Failing closed is the right default for a URL the caller chose to upload, but
12
+ * applying it to Tool Router session file transfers would take a working
13
+ * feature away from Workers instead of closing a hole reachable there. The
14
+ * guard exists to stop a URL from reaching private address space the SDK's host
15
+ * can see; an edge worker has no such vantage point — it cannot resolve DNS to
16
+ * check, and its `fetch` does not originate inside the caller's network. The
17
+ * Node build applies the full guard.
18
+ */
19
+ declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit) => Promise<Response>;
8
20
  //#endregion
9
- export { ssrfSafeFetch };
21
+ export { ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -12,6 +12,18 @@ const ssrfSafeFetch = async (rawUrl) => {
12
12
  possibleFixes: ["Fetch the public URL yourself and pass a File or ArrayBuffer instead", "Run the URL upload in a Node.js or Bun runtime"]
13
13
  });
14
14
  };
15
+ /**
16
+ * Unguarded `fetch`, for the call sites that must keep working here.
17
+ *
18
+ * Failing closed is the right default for a URL the caller chose to upload, but
19
+ * applying it to Tool Router session file transfers would take a working
20
+ * feature away from Workers instead of closing a hole reachable there. The
21
+ * guard exists to stop a URL from reaching private address space the SDK's host
22
+ * can see; an edge worker has no such vantage point — it cannot resolve DNS to
23
+ * check, and its `fetch` does not originate inside the caller's network. The
24
+ * Node build applies the full guard.
25
+ */
26
+ const ssrfSafeFetchWhereSupported = async (rawUrl, init = {}) => fetch(rawUrl, init);
15
27
 
16
28
  //#endregion
17
- export { ssrfSafeFetch };
29
+ export { ssrfSafeFetch, ssrfSafeFetchWhereSupported };
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@composio/core",
3
3
  "type": "module",
4
- "version": "0.16.0",
4
+ "engines": {
5
+ "node": ">=22.22.3"
6
+ },
7
+ "version": "0.18.0",
5
8
  "description": "",
6
9
  "main": "dist/index.mjs",
7
10
  "publishConfig": {
@@ -92,10 +95,10 @@
92
95
  "@type-challenges/utils": "^0.1.1",
93
96
  "@types/semver": "^7.8.0",
94
97
  "tsdown": "^0.22.14",
95
- "tsx": "^4.23.5",
98
+ "tsx": "^4.23.12",
96
99
  "typedoc": "^0.28.20",
97
100
  "typescript": "npm:@typescript/typescript6@^6.0.2",
98
- "vitest": "^4.1.10",
101
+ "vitest": "^4.1.11",
99
102
  "zod": "^4.4.3"
100
103
  },
101
104
  "peerDependencies": {
@@ -109,8 +112,9 @@
109
112
  "picocolors": "^1.1.1",
110
113
  "pusher-js": "^8.6.0",
111
114
  "semver": "^7.8.5",
115
+ "undici": "^7.29.0",
112
116
  "zod-to-json-schema": "^3.25.2",
113
- "@composio/json-schema-to-zod": "0.3.0"
117
+ "@composio/json-schema-to-zod": "0.3.1"
114
118
  },
115
119
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
116
120
  "repository": {
@@ -204,6 +204,7 @@ export class ComposioToolVersionRequiredError extends ComposioError {
204
204
  'Set dangerouslySkipVersionCheck to true (this might cause unexpected behavior when new versions of the tools are released)',
205
205
  ],
206
206
  });
207
+ this.name = 'ComposioToolVersionRequiredError';
207
208
  }
208
209
  }
209
210
  export interface ComposioAPIServerErrorBody {
@@ -78,6 +78,7 @@ export class JsonSchemaToZodError extends ComposioError {
78
78
  ...options,
79
79
  code: options.code || ValidationErrorCodes.JSON_SCHEMA_TO_ZOD_ERROR,
80
80
  });
81
+ this.name = 'JsonSchemaToZodError';
81
82
  }
82
83
  }
83
84
 
@@ -95,5 +96,6 @@ export class JsonSchemaRefResolutionError extends ComposioError {
95
96
  ...options,
96
97
  code: options.code || ValidationErrorCodes.JSON_SCHEMA_REF_RESOLUTION_ERROR,
97
98
  });
99
+ this.name = 'JsonSchemaRefResolutionError';
98
100
  }
99
101
  }
package/src/index.ts CHANGED
@@ -9,12 +9,18 @@ export {
9
9
  deduplicateJsonSchemaRequiredArrays,
10
10
  ensureObjectTypeOnProperties,
11
11
  jsonSchemaToZodSchema,
12
+ omitNullToolArguments,
12
13
  removeNonRequiredProperties,
14
+ toStrictJsonSchema,
13
15
  } from './utils/jsonSchema';
14
16
  export type {
15
17
  DereferenceJsonSchemaOptions,
16
18
  UnresolvedRefReason,
17
19
  UnresolvedRefStrategy,
20
+ StrictSchemaChange,
21
+ StrictSchemaChangeReason,
22
+ StrictSchemaIncompatibility,
23
+ StrictJsonSchemaResult,
18
24
  } from './utils/jsonSchema';
19
25
  export { getExtensionFromMimeType } from './utils/mime';
20
26
  export { normalizeToolArguments } from './utils/toolArguments';
@@ -1,4 +1,5 @@
1
1
  import { platform } from '#platform';
2
+ import { ssrfSafeFetchWhereSupported } from '#ssrf_guard';
2
3
  import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from '../utils/constants';
3
4
 
4
5
  function getParentDir(filePath: string): string {
@@ -82,7 +83,10 @@ export class RemoteFile {
82
83
  * @throws RemoteFileDownloadError if the fetch fails
83
84
  */
84
85
  async buffer(): Promise<Uint8Array> {
85
- const response = await fetch(this.downloadUrl);
86
+ // SSRF guard: `downloadUrl` is set from an API response, so it is untrusted
87
+ // input like every other response field, and its bytes are handed straight
88
+ // back to the caller. See ssrfGuard.node.ts.
89
+ const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
86
90
  if (!response.ok) {
87
91
  throw new RemoteFileDownloadError(
88
92
  `Failed to download file: ${response.status} ${response.statusText}`,
@@ -116,7 +120,8 @@ export class RemoteFile {
116
120
  * @throws RemoteFileDownloadError if the fetch fails
117
121
  */
118
122
  async blob(): Promise<Blob> {
119
- const response = await fetch(this.downloadUrl);
123
+ // SSRF guard: see `buffer()`.
124
+ const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
120
125
  if (!response.ok) {
121
126
  throw new RemoteFileDownloadError(
122
127
  `Failed to download file: ${response.status} ${response.statusText}`,
@@ -41,7 +41,11 @@ import { ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, serializeExperimentalForWire } from
41
41
  import { z } from 'zod/v3';
42
42
  import { transform } from '../utils/transform';
43
43
  import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
44
- import { ComposioAclOnlyForSharedError, ValidationError } from '../errors';
44
+ import {
45
+ ComposioAclOnlyForSharedError,
46
+ ComposioInvalidModifierError,
47
+ ValidationError,
48
+ } from '../errors';
45
49
  import { Tools } from './Tools';
46
50
  import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
47
51
  import type {
@@ -51,7 +55,7 @@ import type {
51
55
  RegisteredCustomTool,
52
56
  RegisteredCustomToolkit,
53
57
  } from '../types/customTool.types';
54
- import type { Tool, ToolExecuteResponse } from '../types/tool.types';
58
+ import { ToolSchema, type Tool, type ToolExecuteResponse } from '../types/tool.types';
55
59
  import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
56
60
  import type {
57
61
  SessionExecuteParams,
@@ -190,13 +194,14 @@ export class ToolRouterSession<
190
194
  requestOptions?: ComposioRequestOptions
191
195
  ): Promise<ReturnType<TProvider['wrapTools']>> {
192
196
  const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
193
- const tools = await ToolsModel.getRawToolRouterSessionTools(
197
+ const rawTools = await ToolsModel.getRawToolRouterSessionTools(
194
198
  this.sessionId,
195
- modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined,
199
+ undefined,
196
200
  requestOptions
197
201
  );
202
+ const tools = await this.applySchemaModifier(rawTools, modifiers?.modifySchema);
198
203
  const sessionTools = await this.addPreloadedCustomTools(tools, modifiers);
199
- const toolBySlug = new Map(sessionTools.map(tool => [tool.slug.toUpperCase(), tool]));
204
+ const rawToolBySlug = new Map(rawTools.map(tool => [tool.slug.toUpperCase(), tool]));
200
205
 
201
206
  if (this.hasCustomTools()) {
202
207
  // Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOL
@@ -205,7 +210,7 @@ export class ToolRouterSession<
205
210
  input: Record<string, unknown>
206
211
  ): Promise<ToolExecuteResponse> => {
207
212
  if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
208
- return this.routeMultiExecute(input, ToolsModel, sessionTools, modifiers);
213
+ return this.routeMultiExecute(input, ToolsModel, rawTools, modifiers);
209
214
  }
210
215
  const customTool = findCustomTool(this.customToolsMap, toolSlug);
211
216
  if (customTool) {
@@ -217,7 +222,7 @@ export class ToolRouterSession<
217
222
  toolSlug,
218
223
  input,
219
224
  modifiers,
220
- toolBySlug.get(toolSlug.toUpperCase())
225
+ rawToolBySlug.get(toolSlug.toUpperCase())
221
226
  );
222
227
  };
223
228
 
@@ -233,10 +238,33 @@ export class ToolRouterSession<
233
238
  }
234
239
 
235
240
  // Standard path (no local tools)
236
- const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
241
+ const wrappedTools = modifiers?.modifySchema
242
+ ? ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers, rawTools)
243
+ : ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
237
244
  return wrappedTools as ReturnType<TProvider['wrapTools']>;
238
245
  }
239
246
 
247
+ private async applySchemaModifier(
248
+ tools: Tool[],
249
+ modifier?: SessionMetaToolOptions['modifySchema']
250
+ ): Promise<Tool[]> {
251
+ if (!modifier) {
252
+ return tools;
253
+ }
254
+ if (typeof modifier !== 'function') {
255
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
256
+ }
257
+ return Promise.all(
258
+ tools.map(tool =>
259
+ modifier({
260
+ toolSlug: tool.slug,
261
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
262
+ schema: ToolSchema.parse(tool),
263
+ })
264
+ )
265
+ );
266
+ }
267
+
240
268
  private async addPreloadedCustomTools(
241
269
  tools: Tool[],
242
270
  modifiers?: SessionMetaToolOptions
@@ -18,7 +18,7 @@ import {
18
18
  import { RemoteFile } from './RemoteFile';
19
19
  import { ValidationError } from '../errors';
20
20
  import { platform } from '#platform';
21
- import { ssrfSafeFetch } from '#ssrf_guard';
21
+ import { ssrfSafeFetch, ssrfSafeFetchWhereSupported } from '#ssrf_guard';
22
22
  import { getExtensionFromMimeType } from '../utils/mime';
23
23
  import { readResponseBodyWithLimit } from '../utils/readResponseBody';
24
24
  import { getRandomShortId } from '../utils/uuid';
@@ -240,13 +240,19 @@ export class ToolRouterSessionFilesMount {
240
240
  ? (createUploadURLResponse as { body: unknown }).body
241
241
  : createUploadURLResponse;
242
242
 
243
- const uploadResponse = await fetch((uploadURLData as { upload_url: string }).upload_url, {
244
- method: 'PUT',
245
- body: await fileToUpload.arrayBuffer(),
246
- headers: {
247
- 'Content-Type': mimetype,
248
- },
249
- });
243
+ // SSRF guard: `upload_url` comes from the API response, so the target is
244
+ // validated before the file's bytes are sent to it — the same treatment the
245
+ // user-supplied URL above already gets. See ssrfGuard.node.ts.
246
+ const uploadResponse = await ssrfSafeFetchWhereSupported(
247
+ (uploadURLData as { upload_url: string }).upload_url,
248
+ {
249
+ method: 'PUT',
250
+ body: await fileToUpload.arrayBuffer(),
251
+ headers: {
252
+ 'Content-Type': mimetype,
253
+ },
254
+ }
255
+ );
250
256
 
251
257
  if (!uploadResponse.ok) {
252
258
  throw new Error(`Failed to upload file: ${uploadResponse.statusText}`);
@@ -54,7 +54,11 @@ import { handleToolExecutionError } from '../errors/ToolErrors';
54
54
  import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
55
55
  import { CONFIG_DEFAULTS } from '../utils/config-defaults';
56
56
  import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
57
- import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
57
+ import {
58
+ dropEmptyFileUploads,
59
+ schemaHasFileUploadable,
60
+ } from '../utils/modifiers/FileToolModifier.utils.neutral';
61
+ import { dereferenceJsonSchema } from '../utils/jsonSchema';
58
62
  import { ComposioRequestOptions } from '../types/requestOptions.types';
59
63
  import { withCancellation } from '../utils/cancellation';
60
64
  import { ComposioRequestCancelledError } from '../errors/SDKErrors';
@@ -268,12 +272,56 @@ export class Tools<
268
272
  if (requestOptions?.signal?.aborted) {
269
273
  throw new ComposioRequestCancelledError();
270
274
  }
275
+ let modifiedParams = await this.applyFileUploadModifiers(
276
+ tool,
277
+ { toolSlug, toolkitSlug, params },
278
+ modifiers?.beforeFileUpload,
279
+ requestOptions
280
+ );
281
+
282
+ // apply the before execute modifiers
283
+ if (modifiers?.beforeExecute) {
284
+ if (typeof modifiers.beforeExecute === 'function') {
285
+ modifiedParams = await modifiers.beforeExecute({
286
+ toolSlug,
287
+ toolkitSlug,
288
+ params: modifiedParams,
289
+ });
290
+ if (requestOptions?.signal?.aborted) {
291
+ throw new ComposioRequestCancelledError();
292
+ }
293
+ } else {
294
+ throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
295
+ }
296
+ }
297
+ return modifiedParams;
298
+ }
299
+
300
+ /**
301
+ * Applies schema-aware file preprocessing shared by direct and Tool Router
302
+ * session execution. This always runs before the caller's `beforeExecute`
303
+ * hook so the hook observes the exact arguments sent to the backend.
304
+ */
305
+ private async applyFileUploadModifiers(
306
+ tool: Tool,
307
+ {
308
+ toolSlug,
309
+ toolkitSlug,
310
+ params,
311
+ }: {
312
+ toolSlug: string;
313
+ toolkitSlug: string;
314
+ params: ToolExecuteParams;
315
+ },
316
+ beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'],
317
+ requestOptions?: ComposioRequestOptions
318
+ ): Promise<ToolExecuteParams> {
271
319
  let modifiedParams = params;
272
320
  // if auto upload download files is enabled, upload the files to the Composio API
273
321
  if (this.autoUploadDownloadFiles) {
274
322
  const fileToolModifier = new FileToolModifier(this.client, {
275
323
  ...this.fileUploadPathOptions,
276
- beforeFileUpload: modifiers?.beforeFileUpload,
324
+ beforeFileUpload,
277
325
  });
278
326
  modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
279
327
  toolSlug,
@@ -284,40 +332,37 @@ export class Tools<
284
332
  if (requestOptions?.signal?.aborted) {
285
333
  throw new ComposioRequestCancelledError();
286
334
  }
287
- } else if (
288
- schemaHasFileUploadable(tool.inputParameters) &&
289
- !this.warnedAutoUploadDisabledForTool.has(toolSlug)
290
- ) {
291
- // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
292
- // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
293
- // produce a valid `s3key` and will hallucinate one, which then fails
294
- // at the staging-lookup step on the backend. Nudge the caller toward
295
- // manual staging or opting into auto-upload.
296
- this.warnedAutoUploadDisabledForTool.add(toolSlug);
297
- logger.warn(
298
- `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
299
- `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
300
- `the file argument as-is; if it isn't already a staged ` +
301
- `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
302
- ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
303
- `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
304
- ` 2) Enable auto-upload with a scoped allowlist: ` +
305
- `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
306
- );
307
- }
308
- // apply the before execute modifiers
309
- if (modifiers?.beforeExecute) {
310
- if (typeof modifiers.beforeExecute === 'function') {
311
- modifiedParams = await modifiers.beforeExecute({
312
- toolSlug,
313
- toolkitSlug,
314
- params: modifiedParams,
315
- });
316
- if (requestOptions?.signal?.aborted) {
317
- throw new ComposioRequestCancelledError();
318
- }
319
- } else {
320
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
335
+ } else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) {
336
+ // Auto-upload is opt-in, but "no file" must still be sent as an
337
+ // omitted key rather than `''`, which the backend rejects
338
+ // (https://github.com/ComposioHQ/composio/issues/4233).
339
+ if (modifiedParams.arguments) {
340
+ modifiedParams = {
341
+ ...modifiedParams,
342
+ arguments: (await dropEmptyFileUploads(
343
+ modifiedParams.arguments,
344
+ dereferenceJsonSchema(tool.inputParameters, { onUnresolved: 'sentinel' })
345
+ )) as ToolExecuteParams['arguments'],
346
+ };
347
+ }
348
+
349
+ if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) {
350
+ // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
351
+ // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
352
+ // produce a valid `s3key` and will hallucinate one, which then fails
353
+ // at the staging-lookup step on the backend. Nudge the caller toward
354
+ // manual staging or opting into auto-upload.
355
+ this.warnedAutoUploadDisabledForTool.add(toolSlug);
356
+ logger.warn(
357
+ `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
358
+ `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
359
+ `the file argument as-is; if it isn't already a staged ` +
360
+ `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
361
+ ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
362
+ `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
363
+ ` 2) Enable auto-upload with a scoped allowlist: ` +
364
+ `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
365
+ );
321
366
  }
322
367
  }
323
368
  return modifiedParams;
@@ -851,9 +896,10 @@ export class Tools<
851
896
  wrapToolsForToolRouter(
852
897
  sessionId: string,
853
898
  tools: Tool[],
854
- modifiers?: SessionExecuteMetaModifiers
899
+ modifiers?: SessionExecuteMetaModifiers,
900
+ rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
855
901
  ): Tool[] {
856
- const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, tools, modifiers);
902
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers);
857
903
  return this.provider.wrapTools(tools, executeToolFn) as Tool[];
858
904
  }
859
905
 
@@ -1150,9 +1196,25 @@ export class Tools<
1150
1196
  });
1151
1197
  }
1152
1198
 
1153
- // Apply beforeExecute modifier if provided
1154
1199
  let modifiedParams = body.arguments ?? {};
1155
1200
  const toolkitSlug = tool?.toolkit?.slug ?? 'composio';
1201
+
1202
+ if (tool) {
1203
+ const fileModifiedParams = await this.applyFileUploadModifiers(
1204
+ tool,
1205
+ {
1206
+ toolSlug,
1207
+ toolkitSlug,
1208
+ params: { arguments: modifiedParams },
1209
+ },
1210
+ undefined,
1211
+ requestOptions
1212
+ );
1213
+ modifiedParams = fileModifiedParams.arguments ?? {};
1214
+ }
1215
+
1216
+ // Apply beforeExecute modifier after file preprocessing so the hook sees
1217
+ // the same arguments that will be sent to the Tool Router.
1156
1218
  if (modifiers?.beforeExecute) {
1157
1219
  modifiedParams = await modifiers.beforeExecute({
1158
1220
  toolSlug,
@@ -1308,6 +1370,7 @@ export class Tools<
1308
1370
  * @deprecated The `customConnectionData` proxy param is deprecated and will be
1309
1371
  * removed in a future release. Use `customAuthParams` instead.
1310
1372
  */
1373
+ // oxlint-disable-next-line typescript/ban-ts-comment -- generated client versions disagree about this deprecated field
1311
1374
  // @ts-ignore
1312
1375
  custom_connection_data: toolProxyParams.data.customConnectionData,
1313
1376
  } as ComposioToolProxyParams;