@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
@@ -0,0 +1,307 @@
1
+ import { t as ComposioBlockedInternalUrlError } from "./SsrfErrors-DNJt57GL.mjs";
2
+ import { lookup } from "node:dns/promises";
3
+ import { isIP } from "node:net";
4
+
5
+ //#region src/utils/pinnedDispatcher.node.ts
6
+ /**
7
+ * The `globalThis` symbols that hold the process-wide dispatcher `fetch` falls
8
+ * back to. Every undici in the process shares them — including the one inside
9
+ * the Node runtime — and `setGlobalDispatcher` writes both, so reading them
10
+ * directly sees the same dispatcher the runtime's own `fetch` would use.
11
+ *
12
+ * Read rather than imported: importing `undici` installs a dispatcher of its
13
+ * own as an import side effect (see {@link loadUndici}), which is exactly what
14
+ * this module must not do at load time.
15
+ */
16
+ const GLOBAL_DISPATCHER_SYMBOLS = [Symbol.for("undici.globalDispatcher.1"), Symbol.for("undici.globalDispatcher.2")];
17
+ /**
18
+ * `undici`, imported on first use rather than at module load.
19
+ *
20
+ * Importing it runs `if (getGlobalDispatcher() === undefined) setGlobalDispatcher(new Agent())`
21
+ * as a side effect, which would hand every unrelated `fetch` in the host
22
+ * application this package's undici instead of the runtime's own — a global
23
+ * change no caller asked for by importing `@composio/core`. Deferring the
24
+ * import to the first pinned request keeps that side effect on the code path
25
+ * that actually needs undici, and behind the `hasCustomGlobalDispatcher` check
26
+ * that reads the slot's true, pre-import state.
27
+ *
28
+ * A process that does make a pinned request still ends up on this package's
29
+ * `Agent` if nothing had claimed the slot yet. That much is not reversible:
30
+ * undici defines the slot non-configurable and writable, so it cannot be
31
+ * cleared back to empty — assigning `undefined` leaves the runtime's own
32
+ * `fetch` asserting on a missing dispatcher.
33
+ */
34
+ let undici;
35
+ const loadUndici = () => undici ??= import("undici");
36
+ /**
37
+ * A `fetch` dispatcher that connects to `addresses` instead of resolving the
38
+ * hostname again.
39
+ *
40
+ * The SSRF guard resolves a hostname to decide whether a URL is safe to fetch.
41
+ * `fetch` would then resolve that hostname a second time when it opens the
42
+ * socket, and the two answers need not match: a short-TTL record can answer
43
+ * with a public address for the check and an internal one for the connect
44
+ * (DNS rebinding). Pinning the connect to the address that was validated
45
+ * removes the second lookup, so there is nothing left to rebind.
46
+ *
47
+ * Only the connect target is replaced. The request still carries the original
48
+ * hostname in `Host` and offers it as TLS SNI, so certificate verification is
49
+ * unchanged — connecting by IP with the IP as SNI would fail against every
50
+ * origin whose certificate names a hostname.
51
+ *
52
+ * The dispatcher is handed to the runtime's own `fetch`, so callers that stub
53
+ * `globalThis.fetch` keep working. That does tie the `undici` major to the one
54
+ * Node's `fetch` speaks — undici 8 dispatchers are rejected by the Node
55
+ * versions this package supports — which is why the dependency is pinned to
56
+ * `^7`, and why `pinnedDispatcher.node.test.ts` exercises a real socket on
57
+ * every Node version in CI rather than mocking the transport.
58
+ */
59
+ const createPinnedDispatcher = async (addresses) => {
60
+ const { Agent } = await loadUndici();
61
+ return new Agent({ connect: { lookup: (_hostname, options, callback) => {
62
+ if (options.all) {
63
+ callback(null, addresses.map((address) => ({
64
+ address,
65
+ family: isIP(address)
66
+ })));
67
+ return;
68
+ }
69
+ const [address] = addresses;
70
+ callback(null, address, isIP(address));
71
+ } } });
72
+ };
73
+ /**
74
+ * Whether the process-wide dispatcher `fetch` falls back to (when a request
75
+ * carries no `dispatcher` of its own) is something other than a stock `Agent`.
76
+ *
77
+ * A `ProxyAgent`, `EnvHttpProxyAgent`, or custom dispatcher installed through
78
+ * `setGlobalDispatcher` is visible here, and pinning stands down for it: the
79
+ * connect would dial the validated origin instead of that route's next hop.
80
+ *
81
+ * Nothing installed yet is *not* custom. The dispatcher slot is empty until
82
+ * either the runtime's `fetch` or an undici import fills it, so an absent
83
+ * dispatcher means no caller has configured a route — treating it as custom
84
+ * would disable pinning for every process that had not yet made a request.
85
+ *
86
+ * Stock-ness is compared by constructor *name*, deliberately not with
87
+ * `instanceof Agent`: an `Agent` created by the runtime's internal undici is a
88
+ * different class from this package's `Agent`, so once the runtime's own
89
+ * `fetch` has initialized its default dispatcher, an `instanceof` check would
90
+ * report a stock setup as custom and silently disable pinning.
91
+ */
92
+ const hasCustomGlobalDispatcher = () => {
93
+ const slots = globalThis;
94
+ const dispatcher = GLOBAL_DISPATCHER_SYMBOLS.map((symbol) => slots[symbol]).find((installed) => installed !== void 0);
95
+ return dispatcher !== void 0 && dispatcher.constructor?.name !== "Agent";
96
+ };
97
+
98
+ //#endregion
99
+ //#region src/utils/ssrfGuard.node.ts
100
+ /**
101
+ * SSRF guard for user-supplied URL file inputs.
102
+ *
103
+ * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
104
+ * file upload during tool execution fetch arbitrary user-provided URLs. Without
105
+ * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
106
+ * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
107
+ * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
108
+ * space — turning the SDK into a server-side request forgery probe.
109
+ *
110
+ * This module validates the *resolved* address (not just the hostname string,
111
+ * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
112
+ * follows redirects manually so each hop is re-validated.
113
+ *
114
+ * The address that was validated is also the address connected to: `fetch` gets
115
+ * a dispatcher pinned to it (see {@link createPinnedDispatcher}), so the
116
+ * hostname is never resolved a second time. Without that, a name could resolve
117
+ * to a public address during validation and rebind to an internal one before
118
+ * the connect — a TOCTOU window the Python guard closes the same way.
119
+ *
120
+ * Residual: a hop whose effective dispatcher is a configured route — a
121
+ * caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
122
+ * `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
123
+ * the runtime's env-proxy mode (`NODE_USE_ENV_PROXY`) — keeps only the
124
+ * pre-flight validation. Pinning would dial the validated address instead of
125
+ * the proxy, and the proxy resolves the hostname itself where the SDK cannot
126
+ * see or pin that resolution. The Python guard carries the same residual for
127
+ * the same reason (`_proxy_applies`).
128
+ */
129
+ const MAX_REDIRECTS = 5;
130
+ /**
131
+ * Whether the runtime would route `url` through an env proxy the SDK cannot
132
+ * see into. Only meaningful when `NODE_USE_ENV_PROXY` opts the built-in
133
+ * `fetch` into env proxies (Node >= 24); without that flag the runtime's
134
+ * `fetch` ignores `HTTP_PROXY`/`HTTPS_PROXY` entirely, so mirroring Python's
135
+ * bare env-var check would drop pinning for users whose fetch never proxied.
136
+ *
137
+ * `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
138
+ * pinning is safe again); per-host `NO_PROXY` entries are treated
139
+ * conservatively as proxied rather than parsed.
140
+ */
141
+ const envProxyApplies = (url) => {
142
+ if (!["1", "true"].includes((process.env.NODE_USE_ENV_PROXY ?? "").toLowerCase())) return false;
143
+ if ((process.env.NO_PROXY ?? process.env.no_proxy ?? "") === "*") return false;
144
+ const schemeVar = url.protocol === "https:" ? "HTTPS_PROXY" : "HTTP_PROXY";
145
+ return Boolean(process.env[schemeVar] ?? process.env[schemeVar.toLowerCase()]);
146
+ };
147
+ const ipv4ToLong = (ip) => {
148
+ const [a, b, c, d] = ip.split(".").map(Number);
149
+ return (a << 24 >>> 0 | b << 16 | c << 8 | d) >>> 0;
150
+ };
151
+ const IPV4_BLOCKED_CIDRS = [
152
+ ["0.0.0.0", 8],
153
+ ["10.0.0.0", 8],
154
+ ["100.64.0.0", 10],
155
+ ["127.0.0.0", 8],
156
+ ["169.254.0.0", 16],
157
+ ["172.16.0.0", 12],
158
+ ["192.0.0.0", 24],
159
+ ["192.0.2.0", 24],
160
+ ["192.168.0.0", 16],
161
+ ["198.18.0.0", 15],
162
+ ["198.51.100.0", 24],
163
+ ["203.0.113.0", 24],
164
+ ["224.0.0.0", 4],
165
+ ["240.0.0.0", 4]
166
+ ];
167
+ const isBlockedIpv4Long = (long) => IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
168
+ const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
169
+ return (long & mask) === (ipv4ToLong(base) & mask);
170
+ });
171
+ /**
172
+ * Expand an IPv6 string into its 8 16-bit groups, converting any trailing
173
+ * dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
174
+ * the input cannot be parsed.
175
+ */
176
+ const expandIpv6 = (ip) => {
177
+ let addr = ip;
178
+ const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
179
+ if (v4Match) {
180
+ const long = ipv4ToLong(v4Match[2]);
181
+ addr = `${v4Match[1]}${(long >>> 16 & 65535).toString(16)}:${(long & 65535).toString(16)}`;
182
+ }
183
+ const halves = addr.split("::");
184
+ if (halves.length > 2) return null;
185
+ const head = halves[0] ? halves[0].split(":") : [];
186
+ const tail = halves.length === 2 ? halves[1] ? halves[1].split(":") : [] : [];
187
+ let groups;
188
+ if (halves.length === 2) {
189
+ const missing = 8 - head.length - tail.length;
190
+ if (missing < 0) return null;
191
+ groups = [
192
+ ...head,
193
+ ...Array(missing).fill("0"),
194
+ ...tail
195
+ ];
196
+ } else groups = head;
197
+ if (groups.length !== 8) return null;
198
+ return groups.map((g) => parseInt(g || "0", 16));
199
+ };
200
+ const isBlockedIpv6 = (ip) => {
201
+ const h = expandIpv6(ip);
202
+ if (!h) return true;
203
+ if (h.every((x) => x === 0)) return true;
204
+ if (h.slice(0, 7).every((x) => x === 0) && h[7] === 1) return true;
205
+ const isMappedOrCompat = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0 && (h[5] === 65535 || h[5] === 0);
206
+ const isNat64 = h[0] === 100 && h[1] === 65435 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
207
+ if (isMappedOrCompat || isNat64) return isBlockedIpv4Long((h[6] << 16 >>> 0 | h[7]) >>> 0);
208
+ if ((h[0] & 65024) === 64512) return true;
209
+ if ((h[0] & 65472) === 65152) return true;
210
+ if ((h[0] & 65280) === 65280) return true;
211
+ return false;
212
+ };
213
+ /**
214
+ * True when `ip` is a private, loopback, link-local, or otherwise
215
+ * non-publicly-routable address. Fails closed (returns `true`) for anything that
216
+ * is not a valid IPv4/IPv6 literal.
217
+ */
218
+ const isBlockedIp = (ip) => {
219
+ const family = isIP(ip);
220
+ if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
221
+ if (family === 6) return isBlockedIpv6(ip);
222
+ return true;
223
+ };
224
+ /**
225
+ * Validate a single URL: it must be http(s), its host must resolve, and every
226
+ * resolved address must be publicly routable. Throws
227
+ * {@link ComposioBlockedInternalUrlError} otherwise.
228
+ *
229
+ * @returns the validated addresses to connect to, in resolver order. Callers
230
+ * must connect to *those* rather than let the client resolve the hostname
231
+ * again; see {@link ssrfSafeFetch}.
232
+ */
233
+ const assertSafeFetchTarget = async (rawUrl) => {
234
+ let url;
235
+ try {
236
+ url = new URL(rawUrl);
237
+ } catch {
238
+ throw new ComposioBlockedInternalUrlError("Refusing to fetch a malformed URL", { url: rawUrl });
239
+ }
240
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new ComposioBlockedInternalUrlError(`Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`, { url: rawUrl });
241
+ const host = url.hostname.replace(/^\[|\]$/g, "");
242
+ let resolved;
243
+ try {
244
+ resolved = await lookup(host, {
245
+ all: true,
246
+ verbatim: true
247
+ });
248
+ } catch {
249
+ throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
250
+ }
251
+ if (resolved.length === 0) throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
252
+ 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`, {
253
+ url: rawUrl,
254
+ resolvedIp: address
255
+ });
256
+ return resolved.map(({ address }) => address);
257
+ };
258
+ /**
259
+ * Drop-in replacement for `fetch` that blocks SSRF. Validates the target, then
260
+ * connects to the address it validated, and re-validates and re-pins every
261
+ * redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
262
+ * Intermediate redirect bodies are cancelled; non-redirect responses are
263
+ * returned unchanged.
264
+ *
265
+ * A hop whose effective dispatcher is a configured route (caller-supplied
266
+ * `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
267
+ * pinned — see the module residual above.
268
+ */
269
+ const ssrfSafeFetch = async (rawUrl, init = {}, maxRedirects = MAX_REDIRECTS) => {
270
+ let currentUrl = rawUrl;
271
+ for (let hop = 0; hop <= maxRedirects; hop++) {
272
+ const addresses = await assertSafeFetchTarget(currentUrl);
273
+ const dispatcher = init.dispatcher !== void 0 || envProxyApplies(new URL(currentUrl)) || hasCustomGlobalDispatcher() ? void 0 : await createPinnedDispatcher(addresses);
274
+ let response;
275
+ try {
276
+ response = await fetch(currentUrl, dispatcher === void 0 ? {
277
+ ...init,
278
+ redirect: "manual"
279
+ } : {
280
+ ...init,
281
+ redirect: "manual",
282
+ dispatcher
283
+ });
284
+ } catch (error) {
285
+ if (dispatcher !== void 0) await dispatcher.close().catch(() => void 0);
286
+ throw error;
287
+ }
288
+ if (dispatcher !== void 0) dispatcher.close().catch(() => void 0);
289
+ if (!(response.status >= 300 && response.status < 400 && response.headers.has("location"))) return response;
290
+ await response.body?.cancel().catch(() => void 0);
291
+ currentUrl = new URL(response.headers.get("location"), currentUrl).toString();
292
+ }
293
+ throw new ComposioBlockedInternalUrlError(`Refusing to fetch: too many redirects (max ${maxRedirects})`, { url: rawUrl });
294
+ };
295
+ /**
296
+ * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.
297
+ *
298
+ * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the
299
+ * caller chose to upload — the alternative is fetching it unvalidated — but not
300
+ * for Tool Router session file transfers, where refusing would remove a working
301
+ * feature from Workers rather than close a hole reachable there. On Node this
302
+ * is the full guard; only the edge build differs.
303
+ */
304
+ const ssrfSafeFetchWhereSupported = ssrfSafeFetch;
305
+
306
+ //#endregion
307
+ export { ssrfSafeFetchWhereSupported as i, isBlockedIp as n, ssrfSafeFetch as r, assertSafeFetchTarget as t };
@@ -1,5 +1,5 @@
1
- import { n as BaseComposioProvider } from "./BaseProvider-D7p2OPEx.mjs";
2
- import { n as ComposioConfig } from "./composio-DSs-1AhC.mjs";
1
+ import { Mn as BaseComposioProvider } from "./customTool.types-DC5fPOOi.mjs";
2
+ import { n as ComposioConfig } from "./composio-CldtZUyC.mjs";
3
3
  //#region src/utils/config-defaults/types.d.ts
4
4
  /**
5
5
  * Configuration defaults for Composio.
@@ -1,4 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-B4k-qoOf.mjs";
1
+ import { t as ConfigDefaults } from "../../types-BgsRW-XH.mjs";
2
2
  //#region src/utils/config-defaults/ConfigDefaults.node.d.ts
3
3
  declare const CONFIG_DEFAULTS: ConfigDefaults;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-B4k-qoOf.mjs";
1
+ import { t as ConfigDefaults } from "../../types-BgsRW-XH.mjs";
2
2
  //#region src/utils/config-defaults/ConfigDefaults.workerd.d.ts
3
3
  declare const CONFIG_DEFAULTS: ConfigDefaults;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-D7p2OPEx.mjs";
1
+ import { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-DC5fPOOi.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
  //#region src/utils/modifiers/FileToolModifier.node.d.ts
4
4
  declare class FileToolModifier {
@@ -1,9 +1,9 @@
1
1
  import { i as logger } from "../../SsrfErrors-DNJt57GL.mjs";
2
- import { f as ComposioRequestCancelledError } from "../../errors-BcEUHZbq.mjs";
2
+ import { f as ComposioRequestCancelledError } from "../../errors-DyZt79fi.mjs";
3
3
  import { a as ComposioSensitiveFilePathBlockedError, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "../../FileModifierErrors-B8V8_3VE.mjs";
4
- import { i as transformProperties, n as schemaHasFileProperty, t as isPlainObject } from "../../FileToolModifier.utils.neutral-B5rT711M.mjs";
5
- import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-NVtGf3St.mjs";
6
- import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-BQ0fWge3.mjs";
4
+ import { a as isEmptyFileValue, c as transformProperties, i as getSchemaVariants, l as walkFileUploadableLeaves, o as isPlainObject, r as findSchemaVariantWithFileProperty, t as DELETE_VALUE } from "../../FileToolModifier.utils.neutral-D_YkHwZP.mjs";
5
+ import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-jUVItfHw.mjs";
6
+ import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-BwpUOF0s.mjs";
7
7
 
8
8
  //#region src/utils/modifiers/FileToolModifier.node.ts
9
9
  /**
@@ -17,61 +17,50 @@ import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFr
17
17
  * https://github.com/ComposioHQ/composio/issues/3307) instead of throwing.
18
18
  */
19
19
  const resolveFileSchema = (schema) => schema ? dereferenceJsonSchema(schema, { onUnresolved: "sentinel" }) : schema;
20
- const getSchemaVariants = (schema) => [
21
- ...schema?.anyOf ?? [],
22
- ...schema?.oneOf ?? [],
23
- ...schema?.allOf ?? []
24
- ];
25
- const jsonSchemaTypeMatchesValue = (schema, value) => {
26
- const schemaType = schema.type;
27
- if (Array.isArray(schemaType)) return schemaType.some((type) => jsonSchemaTypeMatchesValue({
28
- ...schema,
29
- type
30
- }, value));
31
- if (schemaType === void 0) {
32
- if (schema.properties) return isPlainObject(value);
33
- if (schema.items) return Array.isArray(value);
34
- return false;
35
- }
36
- switch (schemaType) {
37
- case "array": return Array.isArray(value);
38
- case "object": return isPlainObject(value);
39
- case "string": return typeof value === "string";
40
- case "integer": return Number.isInteger(value);
41
- case "number": return typeof value === "number";
42
- case "boolean": return typeof value === "boolean";
43
- case "null": return value === null;
44
- default: return false;
45
- }
46
- };
47
- const findSchemaVariantWithFileProperty = (schema, property, value) => {
48
- const candidates = getSchemaVariants(schema).filter((variant) => schemaHasFileProperty(variant, property));
49
- return candidates.find((candidate) => jsonSchemaTypeMatchesValue(candidate, value)) ?? candidates[0];
50
- };
51
20
  /**
52
- * Recursively walks a runtime value and its matching JSON-Schema node,
53
- * uploading any string path whose schema node has `file_uploadable: true`.
54
- * The function returns a **new** value with all substitutions applied;
55
- * nothing is mutated in-place.
21
+ * Stages one `file_uploadable` leaf: a local path / URL string or a `File`
22
+ * is uploaded to S3 and replaced by its `{ name, mimetype, s3key }`
23
+ * descriptor; `''` means "no file" and is dropped from the request;
24
+ * anything else (e.g. an already-staged descriptor) passes through.
56
25
  */
57
- const hydrateFiles = async (value, schema, ctx) => {
58
- if (schema?.file_uploadable) {
59
- if (typeof value !== "string" && !(value instanceof File)) return value;
60
- const runBeforeFileUpload = async (path, source) => {
61
- if (!ctx.beforeFileUpload) return path;
62
- const out = await ctx.beforeFileUpload({
63
- path,
64
- source,
65
- toolSlug: ctx.toolSlug,
66
- toolkitSlug: ctx.toolkitSlug
67
- });
68
- if (out === false) throw new ComposioFileUploadAbortedError("File upload was aborted because beforeFileUpload returned false.");
69
- return out;
70
- };
71
- if (typeof value === "string") {
72
- const pathOrUrl = await runBeforeFileUpload(value, isHttpUrl(value) ? "url" : "path");
73
- logger.debug(`Uploading file "${pathOrUrl}"`);
74
- return getFileDataAfterUploadingToS3(pathOrUrl, {
26
+ const stageFileValue = async (value, ctx) => {
27
+ if (isEmptyFileValue(value)) return DELETE_VALUE;
28
+ if (typeof value !== "string" && !(value instanceof File)) return value;
29
+ const runBeforeFileUpload = async (path, source) => {
30
+ if (!ctx.beforeFileUpload) return path;
31
+ const out = await ctx.beforeFileUpload({
32
+ path,
33
+ source,
34
+ toolSlug: ctx.toolSlug,
35
+ toolkitSlug: ctx.toolkitSlug
36
+ });
37
+ if (out === false) throw new ComposioFileUploadAbortedError("File upload was aborted because beforeFileUpload returned false.");
38
+ return out;
39
+ };
40
+ if (typeof value === "string") {
41
+ const pathOrUrl = await runBeforeFileUpload(value, isHttpUrl(value) ? "url" : "path");
42
+ logger.debug(`Uploading file "${pathOrUrl}"`);
43
+ return getFileDataAfterUploadingToS3(pathOrUrl, {
44
+ toolSlug: ctx.toolSlug,
45
+ toolkitSlug: ctx.toolkitSlug,
46
+ client: ctx.client,
47
+ sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
48
+ fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
49
+ fileUploadAllowlist: ctx.fileUploadAllowlist,
50
+ signal: ctx.signal
51
+ });
52
+ }
53
+ if (ctx.beforeFileUpload) {
54
+ const out = await ctx.beforeFileUpload({
55
+ path: value.name,
56
+ source: "file",
57
+ toolSlug: ctx.toolSlug,
58
+ toolkitSlug: ctx.toolkitSlug
59
+ });
60
+ if (out === false) throw new ComposioFileUploadAbortedError("File upload was aborted because beforeFileUpload returned false.");
61
+ if (typeof out === "string" && out !== value.name) {
62
+ logger.debug(`Uploading file from path "${out}" (replaced File: ${value.name})`);
63
+ return getFileDataAfterUploadingToS3(out, {
75
64
  toolSlug: ctx.toolSlug,
76
65
  toolkitSlug: ctx.toolkitSlug,
77
66
  client: ctx.client,
@@ -81,49 +70,16 @@ const hydrateFiles = async (value, schema, ctx) => {
81
70
  signal: ctx.signal
82
71
  });
83
72
  }
84
- if (ctx.beforeFileUpload) {
85
- const out = await ctx.beforeFileUpload({
86
- path: value.name,
87
- source: "file",
88
- toolSlug: ctx.toolSlug,
89
- toolkitSlug: ctx.toolkitSlug
90
- });
91
- if (out === false) throw new ComposioFileUploadAbortedError("File upload was aborted because beforeFileUpload returned false.");
92
- if (typeof out === "string" && out !== value.name) {
93
- logger.debug(`Uploading file from path "${out}" (replaced File: ${value.name})`);
94
- return getFileDataAfterUploadingToS3(out, {
95
- toolSlug: ctx.toolSlug,
96
- toolkitSlug: ctx.toolkitSlug,
97
- client: ctx.client,
98
- sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
99
- fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
100
- fileUploadAllowlist: ctx.fileUploadAllowlist,
101
- signal: ctx.signal
102
- });
103
- }
104
- }
105
- logger.debug(`Uploading file "${value.name}"`);
106
- return getFileDataAfterUploadingToS3(value, {
107
- toolSlug: ctx.toolSlug,
108
- toolkitSlug: ctx.toolkitSlug,
109
- client: ctx.client,
110
- sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
111
- fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
112
- signal: ctx.signal
113
- });
114
- }
115
- const uploadableVariant = findSchemaVariantWithFileProperty(schema, "file_uploadable", value);
116
- if (uploadableVariant) return hydrateFiles(value, uploadableVariant, ctx);
117
- if (schema?.type === "object" && schema.properties && isPlainObject(value)) {
118
- const transformed = {};
119
- for (const [k, v] of Object.entries(value)) transformed[k] = await hydrateFiles(v, schema.properties[k], ctx);
120
- return transformed;
121
73
  }
122
- if (schema?.type === "array" && schema.items && Array.isArray(value)) {
123
- const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;
124
- return Promise.all(value.map((item) => hydrateFiles(item, itemSchema, ctx)));
125
- }
126
- return value;
74
+ logger.debug(`Uploading file "${value.name}"`);
75
+ return getFileDataAfterUploadingToS3(value, {
76
+ toolSlug: ctx.toolSlug,
77
+ toolkitSlug: ctx.toolkitSlug,
78
+ client: ctx.client,
79
+ sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
80
+ fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
81
+ signal: ctx.signal
82
+ });
127
83
  };
128
84
  /**
129
85
  * Downloads a file from S3 and returns a replacement object.
@@ -212,13 +168,13 @@ var FileToolModifier = class {
212
168
  const { arguments: args } = params;
213
169
  if (!args || typeof args !== "object") return params;
214
170
  try {
215
- const newArgs = await withCancellation(() => hydrateFiles(args, resolveFileSchema(tool.inputParameters), {
171
+ const newArgs = await withCancellation(() => walkFileUploadableLeaves(args, resolveFileSchema(tool.inputParameters), (value) => stageFileValue(value, {
216
172
  toolSlug,
217
173
  toolkitSlug,
218
174
  client: this.client,
219
175
  ...this.fileUploadPathOptions,
220
176
  signal
221
- }), signal);
177
+ })), signal);
222
178
  return {
223
179
  ...params,
224
180
  arguments: newArgs
@@ -1,4 +1,4 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-D7p2OPEx.mjs";
1
+ import { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-DC5fPOOi.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
  //#region src/utils/modifiers/FileToolModifier.workerd.d.ts
4
4
  declare class FileToolModifier {
@@ -1,4 +1,4 @@
1
- import { i as transformProperties } from "../../FileToolModifier.utils.neutral-B5rT711M.mjs";
1
+ import { c as transformProperties } from "../../FileToolModifier.utils.neutral-D_YkHwZP.mjs";
2
2
 
3
3
  //#region src/utils/modifiers/FileToolModifier.workerd.ts
4
4
  const UNSUPPORTED_MESSAGE = "File upload/download modifiers are not available on edge runtimes yet. Please set `dangerouslyAllowAutoUploadDownloadFiles: false` (or unset it; it defaults to false) or run Composio in another JS runtime (Node.js / Bun).";
@@ -9,14 +9,33 @@ declare const isBlockedIp: (ip: string) => boolean;
9
9
  * Validate a single URL: it must be http(s), its host must resolve, and every
10
10
  * resolved address must be publicly routable. Throws
11
11
  * {@link ComposioBlockedInternalUrlError} otherwise.
12
+ *
13
+ * @returns the validated addresses to connect to, in resolver order. Callers
14
+ * must connect to *those* rather than let the client resolve the hostname
15
+ * again; see {@link ssrfSafeFetch}.
12
16
  */
13
- declare const assertSafeFetchTarget: (rawUrl: string) => Promise<void>;
17
+ declare const assertSafeFetchTarget: (rawUrl: string) => Promise<string[]>;
14
18
  /**
15
- * Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
16
- * connecting and re-validates every redirect hop (redirects are followed
17
- * manually up to {@link MAX_REDIRECTS}). Intermediate redirect bodies are
18
- * cancelled; non-redirect responses are returned unchanged.
19
+ * Drop-in replacement for `fetch` that blocks SSRF. Validates the target, then
20
+ * connects to the address it validated, and re-validates and re-pins every
21
+ * redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
22
+ * Intermediate redirect bodies are cancelled; non-redirect responses are
23
+ * returned unchanged.
24
+ *
25
+ * A hop whose effective dispatcher is a configured route (caller-supplied
26
+ * `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
27
+ * pinned — see the module residual above.
19
28
  */
20
29
  declare const ssrfSafeFetch: (rawUrl: string, init?: RequestInit, maxRedirects?: number) => Promise<Response>;
30
+ /**
31
+ * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.
32
+ *
33
+ * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the
34
+ * caller chose to upload — the alternative is fetching it unvalidated — but not
35
+ * for Tool Router session file transfers, where refusing would remove a working
36
+ * feature from Workers rather than close a hole reachable there. On Node this
37
+ * is the full guard; only the edge build differs.
38
+ */
39
+ declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit, maxRedirects?: number) => Promise<Response>;
21
40
  //#endregion
22
- export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch };
41
+ export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch, ssrfSafeFetchWhereSupported };