@composio/core 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-Bz0f52QR.mjs} +16 -6
  2. package/dist/{CustomTool-Uip-fhPw.d.mts → CustomTool-VRfWzMix.d.mts} +1 -1
  3. package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-CwB-Inm9.mjs} +1 -1
  4. package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
  5. package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-xhdVE4yw.mjs} +123 -3
  6. package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-Dw9W5RSp.mjs} +28 -44
  7. package/dist/cancellation-P5YUlcfz.mjs +704 -0
  8. package/dist/{composio-B27X6i6A.d.mts → composio-Cb3d1jFe.d.mts} +250 -244
  9. package/dist/{customTool.types-B2Ava_j5.d.mts → customTool.types-B6ej_8XZ.d.mts} +146 -144
  10. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
  11. package/dist/docs/reference/sdk-reference/typescript/session.mdx +4 -3
  12. package/dist/{errors-BcEUHZbq.mjs → errors-Ue9wMrPK.mjs} +5 -2
  13. package/dist/experimental/index.d.mts +2 -2
  14. package/dist/experimental/index.mjs +1 -1
  15. package/dist/{fileUtils.node-B1Wn848p.mjs → fileUtils.node-KE5Fa-af.mjs} +7 -7
  16. package/dist/index.d.mts +108 -8
  17. package/dist/index.mjs +109 -55
  18. package/dist/models/Files.node.mjs +2 -2
  19. package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-QN7w4n8v.mjs} +24 -7
  20. package/dist/ssrfGuard.node-BLX6b-Rf.mjs +384 -0
  21. package/dist/{types-DdZJuMm2.d.mts → types-CGdgK442.d.mts} +2 -2
  22. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  23. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  24. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  25. package/dist/utils/modifiers/FileToolModifier.node.mjs +59 -103
  26. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  27. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  28. package/dist/utils/ssrfGuard.node.d.mts +14 -5
  29. package/dist/utils/ssrfGuard.node.mjs +1 -161
  30. package/dist/utils/ssrfGuard.workerd.d.mts +1 -1
  31. package/dist/utils/ssrfGuard.workerd.mjs +2 -2
  32. package/package.json +25 -3
  33. package/src/errors/ToolErrors.ts +1 -0
  34. package/src/errors/ValidationErrors.ts +2 -0
  35. package/src/index.ts +6 -0
  36. package/src/models/CustomTool.ts +41 -6
  37. package/src/models/RemoteFile.ts +54 -36
  38. package/src/models/ToolRouterSession.ts +45 -12
  39. package/src/models/Tools.ts +102 -39
  40. package/src/models/Triggers.ts +15 -0
  41. package/src/services/telemetry/TelemetryService.ts +27 -12
  42. package/src/telemetry/redact.ts +133 -6
  43. package/src/utils/fileUtils.node.ts +10 -2
  44. package/src/utils/jsonSchema.ts +505 -27
  45. package/src/utils/logger.ts +6 -6
  46. package/src/utils/modifiers/FileToolModifier.node.ts +85 -181
  47. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +199 -0
  48. package/src/utils/pinnedDispatcher.node.ts +214 -0
  49. package/src/utils/sdk.ts +1 -1
  50. package/src/utils/sensitiveFileUploadPaths.ts +36 -9
  51. package/src/utils/ssrfGuard.node.ts +101 -11
  52. package/src/utils/ssrfGuard.workerd.ts +5 -1
  53. package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
  54. package/dist/cancellation-NVtGf3St.mjs +0 -364
@@ -0,0 +1,384 @@
1
+ import { t as ComposioBlockedInternalUrlError } from "./SsrfErrors-xhdVE4yw.mjs";
2
+ import { lookup } from "node:dns/promises";
3
+ import { isIP } from "node:net";
4
+ import { request } from "node:http";
5
+ import { request as request$1 } from "node:https";
6
+ import { Readable } from "node:stream";
7
+
8
+ //#region src/utils/pinnedDispatcher.node.ts
9
+ /**
10
+ * The `globalThis` symbols that hold the process-wide dispatcher `fetch` falls
11
+ * back to. Every undici in the process shares them — including the one inside
12
+ * the Node runtime — and `setGlobalDispatcher` writes both, so reading them
13
+ * directly sees the same dispatcher the runtime's own `fetch` would use.
14
+ *
15
+ * Read rather than imported: importing `undici` installs a dispatcher of its
16
+ * own as an import side effect (see {@link loadUndici}), which is exactly what
17
+ * this module must not do at load time.
18
+ */
19
+ const GLOBAL_DISPATCHER_SYMBOLS = [Symbol.for("undici.globalDispatcher.1"), Symbol.for("undici.globalDispatcher.2")];
20
+ /**
21
+ * `undici`, imported on first use rather than at module load.
22
+ *
23
+ * Importing it runs `if (getGlobalDispatcher() === undefined) setGlobalDispatcher(new Agent())`
24
+ * as a side effect, which would hand every unrelated `fetch` in the host
25
+ * application this package's undici instead of the runtime's own — a global
26
+ * change no caller asked for by importing `@composio/core`. Deferring the
27
+ * import to the first pinned request keeps that side effect on the code path
28
+ * that actually needs undici, and behind the `hasCustomGlobalDispatcher` check
29
+ * that reads the slot's true, pre-import state.
30
+ *
31
+ * A process that does make a pinned request still ends up on this package's
32
+ * `Agent` if nothing had claimed the slot yet. That much is not reversible:
33
+ * undici defines the slot non-configurable and writable, so it cannot be
34
+ * cleared back to empty — assigning `undefined` leaves the runtime's own
35
+ * `fetch` asserting on a missing dispatcher.
36
+ */
37
+ let undici;
38
+ const loadUndici = () => undici ??= import("undici");
39
+ const lookupPinnedAddresses = (addresses, options, callback) => {
40
+ if (options.all) {
41
+ callback(null, addresses.map((address) => ({
42
+ address,
43
+ family: isIP(address)
44
+ })));
45
+ return;
46
+ }
47
+ const [address] = addresses;
48
+ callback(null, address, isIP(address));
49
+ };
50
+ const knownBodyLength = (body) => {
51
+ if (body === null || body === void 0) return void 0;
52
+ if (typeof body === "string") return new TextEncoder().encode(body).byteLength;
53
+ if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
54
+ if (body instanceof ArrayBuffer) return body.byteLength;
55
+ if (ArrayBuffer.isView(body)) return body.byteLength;
56
+ if (body instanceof Blob) return body.size;
57
+ };
58
+ /**
59
+ * A `fetch` dispatcher that connects to `addresses` instead of resolving the
60
+ * hostname again.
61
+ *
62
+ * The SSRF guard resolves a hostname to decide whether a URL is safe to fetch.
63
+ * `fetch` would then resolve that hostname a second time when it opens the
64
+ * socket, and the two answers need not match: a short-TTL record can answer
65
+ * with a public address for the check and an internal one for the connect
66
+ * (DNS rebinding). Pinning the connect to the address that was validated
67
+ * removes the second lookup, so there is nothing left to rebind.
68
+ *
69
+ * Only the connect target is replaced. The request still carries the original
70
+ * hostname in `Host` and offers it as TLS SNI, so certificate verification is
71
+ * unchanged — connecting by IP with the IP as SNI would fail against every
72
+ * origin whose certificate names a hostname.
73
+ *
74
+ * The dispatcher is handed to the runtime's own `fetch`, so callers that stub
75
+ * `globalThis.fetch` keep working. That does tie the `undici` major to the one
76
+ * Node's `fetch` speaks — undici 8 dispatchers are rejected by the Node
77
+ * versions this package supports — which is why the dependency is pinned to
78
+ * `^7`, and why `pinnedDispatcher.node.test.ts` exercises a real socket on
79
+ * every Node version in CI rather than mocking the transport.
80
+ */
81
+ const createPinnedDispatcher = async (addresses) => {
82
+ const { Agent } = await loadUndici();
83
+ return new Agent({ connect: { lookup: (_hostname, options, callback) => {
84
+ lookupPinnedAddresses(addresses, options, callback);
85
+ } } });
86
+ };
87
+ /**
88
+ * Fetch through the Node-compatible HTTP client while pinning DNS resolution.
89
+ *
90
+ * Bun implements the Node HTTP client and its `lookup` hook, but its native
91
+ * `fetch` ignores undici's `dispatcher` option. This transport preserves the
92
+ * original hostname for Host and TLS SNI while making the socket use an
93
+ * address that the SSRF guard already validated.
94
+ */
95
+ const pinnedHttpFetch = async (rawUrl, init, addresses) => {
96
+ const normalized = new Request(rawUrl, init);
97
+ const url = new URL(rawUrl);
98
+ const request$2 = url.protocol === "https:" ? request$1 : request;
99
+ const headers = new Headers(normalized.headers);
100
+ const bodyLength = knownBodyLength(init.body);
101
+ if (bodyLength !== void 0 && !headers.has("content-length")) headers.set("content-length", String(bodyLength));
102
+ return new Promise((resolve, reject) => {
103
+ const outgoing = request$2(url, {
104
+ method: normalized.method,
105
+ headers: Object.fromEntries(headers.entries()),
106
+ signal: normalized.signal,
107
+ lookup: (_hostname, options, callback) => lookupPinnedAddresses(addresses, options, callback)
108
+ }, (incoming) => {
109
+ const headers = new Headers();
110
+ for (let index = 0; index < incoming.rawHeaders.length; index += 2) headers.append(incoming.rawHeaders[index], incoming.rawHeaders[index + 1]);
111
+ const status = incoming.statusCode ?? 500;
112
+ const body = [
113
+ 101,
114
+ 103,
115
+ 204,
116
+ 205,
117
+ 304
118
+ ].includes(status) ? null : Readable.toWeb(incoming);
119
+ resolve(new Response(body, {
120
+ status,
121
+ statusText: incoming.statusMessage,
122
+ headers
123
+ }));
124
+ });
125
+ outgoing.once("error", reject);
126
+ (async () => {
127
+ try {
128
+ if (normalized.body) {
129
+ const reader = normalized.body.getReader();
130
+ while (true) {
131
+ const { done, value } = await reader.read();
132
+ if (done) break;
133
+ if (!outgoing.write(value)) await new Promise((resolveDrain) => outgoing.once("drain", resolveDrain));
134
+ }
135
+ }
136
+ outgoing.end();
137
+ } catch (error) {
138
+ outgoing.destroy(error instanceof Error ? error : new Error(String(error)));
139
+ }
140
+ })();
141
+ });
142
+ };
143
+ /**
144
+ * Whether the process-wide dispatcher `fetch` falls back to (when a request
145
+ * carries no `dispatcher` of its own) is something other than a stock `Agent`.
146
+ *
147
+ * A `ProxyAgent`, `EnvHttpProxyAgent`, or custom dispatcher installed through
148
+ * `setGlobalDispatcher` is visible here, and pinning stands down for it: the
149
+ * connect would dial the validated origin instead of that route's next hop.
150
+ *
151
+ * Nothing installed yet is *not* custom. The dispatcher slot is empty until
152
+ * either the runtime's `fetch` or an undici import fills it, so an absent
153
+ * dispatcher means no caller has configured a route — treating it as custom
154
+ * would disable pinning for every process that had not yet made a request.
155
+ *
156
+ * Stock-ness is compared by constructor *name*, deliberately not with
157
+ * `instanceof Agent`: an `Agent` created by the runtime's internal undici is a
158
+ * different class from this package's `Agent`, so once the runtime's own
159
+ * `fetch` has initialized its default dispatcher, an `instanceof` check would
160
+ * report a stock setup as custom and silently disable pinning.
161
+ */
162
+ const hasCustomGlobalDispatcher = () => {
163
+ const slots = globalThis;
164
+ const dispatcher = GLOBAL_DISPATCHER_SYMBOLS.map((symbol) => slots[symbol]).find((installed) => installed !== void 0);
165
+ return dispatcher !== void 0 && dispatcher.constructor?.name !== "Agent";
166
+ };
167
+
168
+ //#endregion
169
+ //#region src/utils/ssrfGuard.node.ts
170
+ /**
171
+ * SSRF guard for user-supplied URL file inputs.
172
+ *
173
+ * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
174
+ * file upload during tool execution fetch arbitrary user-provided URLs. Without
175
+ * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
176
+ * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
177
+ * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
178
+ * space — turning the SDK into a server-side request forgery probe.
179
+ *
180
+ * This module validates the *resolved* address (not just the hostname string,
181
+ * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
182
+ * follows redirects manually so each hop is re-validated.
183
+ *
184
+ * The address that was validated is also the address connected to: `fetch` gets
185
+ * a dispatcher pinned to it (see {@link createPinnedDispatcher}), so the
186
+ * hostname is never resolved a second time. Without that, a name could resolve
187
+ * to a public address during validation and rebind to an internal one before
188
+ * the connect — a TOCTOU window the Python guard closes the same way.
189
+ *
190
+ * Residual: a hop whose effective dispatcher is a configured route — a
191
+ * caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
192
+ * `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
193
+ * the runtime's env-proxy mode (automatic on Bun, opt-in via
194
+ * `NODE_USE_ENV_PROXY` on Node) — keeps only the
195
+ * pre-flight validation. Pinning would dial the validated address instead of
196
+ * the proxy, and the proxy resolves the hostname itself where the SDK cannot
197
+ * see or pin that resolution. The Python guard carries the same residual for
198
+ * the same reason (`_proxy_applies`).
199
+ */
200
+ const MAX_REDIRECTS = 5;
201
+ /**
202
+ * Whether the runtime would route `url` through an env proxy the SDK cannot
203
+ * see into. Bun honors proxy environment variables automatically. Node's
204
+ * built-in `fetch` requires the `NODE_USE_ENV_PROXY` opt-in (Node >= 24), so
205
+ * a bare env-var check on Node would drop pinning for users whose fetch never
206
+ * proxied.
207
+ *
208
+ * `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
209
+ * pinning is safe again); per-host `NO_PROXY` entries are treated
210
+ * conservatively as proxied rather than parsed.
211
+ */
212
+ const envProxyApplies = (url, isBun) => {
213
+ if (!(isBun || ["1", "true"].includes((process.env.NODE_USE_ENV_PROXY ?? "").toLowerCase()))) return false;
214
+ if ((process.env.NO_PROXY ?? process.env.no_proxy ?? "") === "*") return false;
215
+ const schemeVar = url.protocol === "https:" ? "HTTPS_PROXY" : "HTTP_PROXY";
216
+ return Boolean(process.env[schemeVar] ?? process.env[schemeVar.toLowerCase()]);
217
+ };
218
+ const ipv4ToLong = (ip) => {
219
+ const [a, b, c, d] = ip.split(".").map(Number);
220
+ return (a << 24 >>> 0 | b << 16 | c << 8 | d) >>> 0;
221
+ };
222
+ const IPV4_BLOCKED_CIDRS = [
223
+ ["0.0.0.0", 8],
224
+ ["10.0.0.0", 8],
225
+ ["100.64.0.0", 10],
226
+ ["127.0.0.0", 8],
227
+ ["169.254.0.0", 16],
228
+ ["172.16.0.0", 12],
229
+ ["192.0.0.0", 24],
230
+ ["192.0.2.0", 24],
231
+ ["192.168.0.0", 16],
232
+ ["198.18.0.0", 15],
233
+ ["198.51.100.0", 24],
234
+ ["203.0.113.0", 24],
235
+ ["224.0.0.0", 4],
236
+ ["240.0.0.0", 4]
237
+ ];
238
+ const isBlockedIpv4Long = (long) => IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
239
+ const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
240
+ return (long & mask) === (ipv4ToLong(base) & mask);
241
+ });
242
+ /**
243
+ * Expand an IPv6 string into its 8 16-bit groups, converting any trailing
244
+ * dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
245
+ * the input cannot be parsed.
246
+ */
247
+ const expandIpv6 = (ip) => {
248
+ let addr = ip;
249
+ const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
250
+ if (v4Match) {
251
+ const long = ipv4ToLong(v4Match[2]);
252
+ addr = `${v4Match[1]}${(long >>> 16 & 65535).toString(16)}:${(long & 65535).toString(16)}`;
253
+ }
254
+ const halves = addr.split("::");
255
+ if (halves.length > 2) return null;
256
+ const head = halves[0] ? halves[0].split(":") : [];
257
+ const tail = halves.length === 2 ? halves[1] ? halves[1].split(":") : [] : [];
258
+ let groups;
259
+ if (halves.length === 2) {
260
+ const missing = 8 - head.length - tail.length;
261
+ if (missing < 0) return null;
262
+ groups = [
263
+ ...head,
264
+ ...Array(missing).fill("0"),
265
+ ...tail
266
+ ];
267
+ } else groups = head;
268
+ if (groups.length !== 8) return null;
269
+ return groups.map((g) => parseInt(g || "0", 16));
270
+ };
271
+ const isBlockedIpv6 = (ip) => {
272
+ const h = expandIpv6(ip);
273
+ if (!h) return true;
274
+ if (h.every((x) => x === 0)) return true;
275
+ if (h.slice(0, 7).every((x) => x === 0) && h[7] === 1) return true;
276
+ const isMappedOrCompat = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0 && (h[5] === 65535 || h[5] === 0);
277
+ const isNat64 = h[0] === 100 && h[1] === 65435 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
278
+ if (isMappedOrCompat || isNat64) return isBlockedIpv4Long((h[6] << 16 >>> 0 | h[7]) >>> 0);
279
+ if ((h[0] & 65024) === 64512) return true;
280
+ if ((h[0] & 65472) === 65152) return true;
281
+ if ((h[0] & 65280) === 65280) return true;
282
+ return false;
283
+ };
284
+ /**
285
+ * True when `ip` is a private, loopback, link-local, or otherwise
286
+ * non-publicly-routable address. Fails closed (returns `true`) for anything that
287
+ * is not a valid IPv4/IPv6 literal.
288
+ */
289
+ const isBlockedIp = (ip) => {
290
+ const family = isIP(ip);
291
+ if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
292
+ if (family === 6) return isBlockedIpv6(ip);
293
+ return true;
294
+ };
295
+ /**
296
+ * Validate a single URL: it must be http(s), its host must resolve, and every
297
+ * resolved address must be publicly routable. Throws
298
+ * {@link ComposioBlockedInternalUrlError} otherwise.
299
+ *
300
+ * @returns the validated addresses to connect to, in resolver order. Callers
301
+ * must connect to *those* rather than let the client resolve the hostname
302
+ * again; see {@link ssrfSafeFetch}.
303
+ */
304
+ const assertSafeFetchTarget = async (rawUrl) => {
305
+ let url;
306
+ try {
307
+ url = new URL(rawUrl);
308
+ } catch {
309
+ throw new ComposioBlockedInternalUrlError("Refusing to fetch a malformed URL", { url: rawUrl });
310
+ }
311
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new ComposioBlockedInternalUrlError(`Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`, { url: rawUrl });
312
+ const host = url.hostname.replace(/^\[|\]$/g, "");
313
+ let resolved;
314
+ try {
315
+ resolved = await lookup(host, {
316
+ all: true,
317
+ verbatim: true
318
+ });
319
+ } catch {
320
+ throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
321
+ }
322
+ if (resolved.length === 0) throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
323
+ 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`, {
324
+ url: rawUrl,
325
+ resolvedIp: address
326
+ });
327
+ return resolved.map(({ address }) => address);
328
+ };
329
+ /**
330
+ * Drop-in replacement for `fetch` that blocks SSRF. Validates the target, then
331
+ * connects to the address it validated, and re-validates and re-pins every
332
+ * redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
333
+ * Intermediate redirect bodies are cancelled; non-redirect responses are
334
+ * returned unchanged.
335
+ *
336
+ * A hop whose effective dispatcher is a configured route (caller-supplied
337
+ * `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
338
+ * pinned — see the module residual above.
339
+ */
340
+ const ssrfSafeFetch = async (rawUrl, init = {}, maxRedirects = MAX_REDIRECTS) => {
341
+ let currentUrl = rawUrl;
342
+ for (let hop = 0; hop <= maxRedirects; hop++) {
343
+ const addresses = await assertSafeFetchTarget(currentUrl);
344
+ const isBun = typeof process.versions.bun === "string";
345
+ const respectConfiguredRoute = init.dispatcher !== void 0 || envProxyApplies(new URL(currentUrl), isBun) || hasCustomGlobalDispatcher();
346
+ const dispatcher = respectConfiguredRoute || isBun ? void 0 : await createPinnedDispatcher(addresses);
347
+ let response;
348
+ try {
349
+ if (isBun && !respectConfiguredRoute) response = await pinnedHttpFetch(currentUrl, {
350
+ ...init,
351
+ redirect: "manual"
352
+ }, addresses);
353
+ else response = await fetch(currentUrl, dispatcher === void 0 ? {
354
+ ...init,
355
+ redirect: "manual"
356
+ } : {
357
+ ...init,
358
+ redirect: "manual",
359
+ dispatcher
360
+ });
361
+ } catch (error) {
362
+ if (dispatcher !== void 0) await dispatcher.close().catch(() => void 0);
363
+ throw error;
364
+ }
365
+ if (dispatcher !== void 0) dispatcher.close().catch(() => void 0);
366
+ if (!(response.status >= 300 && response.status < 400 && response.headers.has("location"))) return response;
367
+ await response.body?.cancel().catch(() => void 0);
368
+ currentUrl = new URL(response.headers.get("location"), currentUrl).toString();
369
+ }
370
+ throw new ComposioBlockedInternalUrlError(`Refusing to fetch: too many redirects (max ${maxRedirects})`, { url: rawUrl });
371
+ };
372
+ /**
373
+ * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.
374
+ *
375
+ * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the
376
+ * caller chose to upload — the alternative is fetching it unvalidated — but not
377
+ * for Tool Router session file transfers, where refusing would remove a working
378
+ * feature from Workers rather than close a hole reachable there. On Node this
379
+ * is the full guard; only the edge build differs.
380
+ */
381
+ const ssrfSafeFetchWhereSupported = ssrfSafeFetch;
382
+
383
+ //#endregion
384
+ export { ssrfSafeFetchWhereSupported as i, isBlockedIp as n, ssrfSafeFetch as r, assertSafeFetchTarget as t };
@@ -1,5 +1,5 @@
1
- import { Mn as BaseComposioProvider } from "./customTool.types-B2Ava_j5.mjs";
2
- import { n as ComposioConfig } from "./composio-B27X6i6A.mjs";
1
+ import { Mn as BaseComposioProvider } from "./customTool.types-B6ej_8XZ.mjs";
2
+ import { n as ComposioConfig } from "./composio-Cb3d1jFe.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-DdZJuMm2.mjs";
1
+ import { t as ConfigDefaults } from "../../types-CGdgK442.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-DdZJuMm2.mjs";
1
+ import { t as ConfigDefaults } from "../../types-CGdgK442.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 { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-B2Ava_j5.mjs";
1
+ import { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-B6ej_8XZ.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
- import { i as logger } from "../../SsrfErrors-DNJt57GL.mjs";
2
- import { f as ComposioRequestCancelledError } from "../../errors-BcEUHZbq.mjs";
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-B1Wn848p.mjs";
1
+ import { i as logger } from "../../SsrfErrors-xhdVE4yw.mjs";
2
+ import { f as ComposioRequestCancelledError } from "../../errors-Ue9wMrPK.mjs";
3
+ import { a as ComposioSensitiveFilePathBlockedError, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "../../FileModifierErrors-CwB-Inm9.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-P5YUlcfz.mjs";
6
+ import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-KE5Fa-af.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 { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-B2Ava_j5.mjs";
1
+ import { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-B6ej_8XZ.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,13 +9,22 @@ 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>;
21
30
  /**