@composio/core 0.14.0 → 0.14.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 (41) hide show
  1. package/dist/{BaseProvider-lCxnjFKQ.d.mts → BaseProvider-Dc5yKZhk.d.mts} +81 -82
  2. package/dist/{CustomTool-CmokRT9q.d.mts → CustomTool-4nVuwLzO.d.mts} +1 -2
  3. package/dist/{CustomTool-C_5NvBsX.mjs → CustomTool-l-j5HtEf.mjs} +1 -1
  4. package/dist/FileModifierErrors-B8V8_3VE.mjs +97 -0
  5. package/dist/{SsrfErrors-BQRozkeU.mjs → SsrfErrors-DNJt57GL.mjs} +5 -98
  6. package/dist/{Telemetry-llfvticE.mjs → Telemetry-CF0rNHu2.mjs} +2 -2
  7. package/dist/{cancellation-W65QRyj2.mjs → cancellation-BbJ-UQ__.mjs} +2 -2
  8. package/dist/{composio-6C8kHtqc.d.mts → composio-ChU3eD9F.d.mts} +260 -257
  9. package/dist/{customTool.types-kFhNYuzh.d.mts → customTool.types-CX2-LbfI.d.mts} +142 -109
  10. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +2 -0
  11. package/dist/{errors-B165yJUQ.mjs → errors-BcEUHZbq.mjs} +2 -1
  12. package/dist/experimental/index.d.mts +2 -2
  13. package/dist/experimental/index.mjs +1 -1
  14. package/dist/{fileUtils.node-iPFi2o4i.mjs → fileUtils.node-DOkW4PBg.mjs} +5 -153
  15. package/dist/index.d.mts +1585 -753
  16. package/dist/index.mjs +14 -10
  17. package/dist/models/Files.node.d.mts +2 -11
  18. package/dist/models/Files.node.mjs +2 -2
  19. package/dist/models/Files.workerd.d.mts +0 -1
  20. package/dist/platform/node.d.mts +0 -1
  21. package/dist/platform/workerd.d.mts +0 -1
  22. package/dist/platform/workerd.mjs +27 -3
  23. package/dist/{sensitiveFileUploadPaths-B1OLsd8F.mjs → sensitiveFileUploadPaths-C43dHP7S.mjs} +52 -2
  24. package/dist/{types-yCrveqAj.d.mts → types-D5N60gUD.d.mts} +2 -3
  25. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -2
  26. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -2
  27. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -2
  28. package/dist/utils/modifiers/FileToolModifier.node.mjs +5 -4
  29. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -2
  30. package/dist/utils/ssrfGuard.node.d.mts +22 -0
  31. package/dist/utils/ssrfGuard.node.mjs +152 -0
  32. package/dist/utils/ssrfGuard.workerd.d.mts +9 -0
  33. package/dist/utils/ssrfGuard.workerd.mjs +17 -0
  34. package/package.json +14 -9
  35. package/src/errors/SsrfErrors.ts +4 -3
  36. package/src/models/ToolRouterSessionFileMount.ts +7 -3
  37. package/src/platform/workerd.ts +30 -3
  38. package/src/utils/fileUtils.node.ts +2 -2
  39. package/src/utils/readResponseBody.ts +63 -0
  40. package/src/utils/ssrfGuard.node.ts +6 -6
  41. package/src/utils/ssrfGuard.workerd.ts +19 -0
package/dist/index.mjs CHANGED
@@ -1,10 +1,11 @@
1
- import { _ as USER_DATA_FILE_NAME, a as ComposioFileUploadError, b as getEnvsWithPrefix, c as FileModifierErrorCodes, d as COMPOSIO_DIR, f as COMPOSIO_LOG_LEVEL, g as TEMP_FILES_DIRECTORY_NAME, h as IS_DEVELOPMENT_OR_CI, i as ComposioFileUploadAbortedError, l as ComposioError, m as DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID, n as SsrfErrorCodes, o as ComposioFileUploadPathNotAllowedError, p as DEFAULT_BASE_URL, r as ComposioFileNotFoundError, s as ComposioSensitiveFilePathBlockedError, t as ComposioBlockedInternalUrlError, u as logger, v as constants_exports, y as getEnvVariable } from "./SsrfErrors-BQRozkeU.mjs";
2
- import { A as ToolErrorCodes, B as ComposioSharedAccessDeniedError, C as ComposioInvalidExecuteFunctionError, D as ComposioToolExecutionError, E as ComposioProviderNotDefinedError, F as ComposioAclOnlyForSharedError, H as ConnectedAccountErrorCodes, I as ComposioConnectedAccountNotFoundError, L as ComposioFailedToCreateConnectedAccountLink, M as ConnectionRequestErrorCodes, N as ConnectionRequestFailedError, O as ComposioToolNotFoundError, P as ConnectionRequestTimeoutError, R as ComposioLegacyConnectedAccountsEndpointRetiredError, S as ComposioGlobalExecuteToolFnNotSetError, T as ComposioInvalidToolArgumentsError, U as AuthConfigErrorCodes, V as ComposioSharedConnectionNotAccessibleError, W as ComposioAuthConfigNotFoundError, _ as ValidationError, a as ComposioFailedToSubscribeToPusherChannelError, b as ComposioToolkitNotFoundError, c as ComposioWebhookPayloadError, d as ComposioNoAPIKeyError, f as ComposioRequestCancelledError, g as JsonSchemaToZodError, h as JsonSchemaRefResolutionError, i as ComposioFailedToGetSDKRealtimeCredentialsError, j as handleToolExecutionError, k as ComposioToolVersionRequiredError, l as ComposioWebhookSignatureVerificationError, m as isRequestAbortError, n as RemoteFileErrorCodes, o as ComposioFailedToUnsubscribeFromPusherChannelError, p as SDKErrorCodes, r as ComposioFailedToCreatePusherClientError, s as ComposioTriggerTypeNotFoundError, t as RemoteFileDownloadError, u as TriggerErrorCodes, v as ValidationErrorCodes, w as ComposioInvalidModifierError, x as ToolkitErrorCodes, y as ComposioToolkitFetchError, z as ComposioMultipleConnectedAccountsError } from "./errors-B165yJUQ.mjs";
1
+ import { a as COMPOSIO_DIR, c as DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID, d as USER_DATA_FILE_NAME, f as constants_exports, i as logger, l as IS_DEVELOPMENT_OR_CI, m as getEnvsWithPrefix, n as SsrfErrorCodes, o as COMPOSIO_LOG_LEVEL, p as getEnvVariable, r as ComposioError, s as DEFAULT_BASE_URL, t as ComposioBlockedInternalUrlError, u as TEMP_FILES_DIRECTORY_NAME } from "./SsrfErrors-DNJt57GL.mjs";
2
+ import { A as ToolErrorCodes, B as ComposioSharedAccessDeniedError, C as ComposioInvalidExecuteFunctionError, D as ComposioToolExecutionError, E as ComposioProviderNotDefinedError, F as ComposioAclOnlyForSharedError, H as ConnectedAccountErrorCodes, I as ComposioConnectedAccountNotFoundError, L as ComposioFailedToCreateConnectedAccountLink, M as ConnectionRequestErrorCodes, N as ConnectionRequestFailedError, O as ComposioToolNotFoundError, P as ConnectionRequestTimeoutError, R as ComposioLegacyConnectedAccountsEndpointRetiredError, S as ComposioGlobalExecuteToolFnNotSetError, T as ComposioInvalidToolArgumentsError, U as AuthConfigErrorCodes, V as ComposioSharedConnectionNotAccessibleError, W as ComposioAuthConfigNotFoundError, _ as ValidationError, a as ComposioFailedToSubscribeToPusherChannelError, b as ComposioToolkitNotFoundError, c as ComposioWebhookPayloadError, d as ComposioNoAPIKeyError, f as ComposioRequestCancelledError, g as JsonSchemaToZodError, h as JsonSchemaRefResolutionError, i as ComposioFailedToGetSDKRealtimeCredentialsError, j as handleToolExecutionError, k as ComposioToolVersionRequiredError, l as ComposioWebhookSignatureVerificationError, m as isRequestAbortError, n as RemoteFileErrorCodes, o as ComposioFailedToUnsubscribeFromPusherChannelError, p as SDKErrorCodes, r as ComposioFailedToCreatePusherClientError, s as ComposioTriggerTypeNotFoundError, t as RemoteFileDownloadError, u as TriggerErrorCodes, v as ValidationErrorCodes, w as ComposioInvalidModifierError, x as ToolkitErrorCodes, y as ComposioToolkitFetchError, z as ComposioMultipleConnectedAccountsError } from "./errors-BcEUHZbq.mjs";
3
+ import { a as ComposioSensitiveFilePathBlockedError, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, o as FileModifierErrorCodes, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "./FileModifierErrors-B8V8_3VE.mjs";
3
4
  import { r as schemaHasFileUploadable, t as isPlainObject } from "./FileToolModifier.utils.neutral-B5rT711M.mjs";
4
- import { a as removeNonRequiredProperties, i as jsonSchemaToZodSchema, n as deduplicateJsonSchemaRequiredArrays, r as dereferenceJsonSchema, t as withCancellation } from "./cancellation-W65QRyj2.mjs";
5
- import { t as telemetry } from "./Telemetry-llfvticE.mjs";
6
- import { i as arrayBufferToBase64, n as assertSafeFileUploadPath, r as isBlockedSensitiveFileUploadPath, s as getRandomShortId, t as BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS } from "./sensitiveFileUploadPaths-B1OLsd8F.mjs";
7
- import { a as createCustomToolkit, c as getPreloadedCustomToolSlugs, d as CreateCustomToolBaseSchema, f as CreateCustomToolkitBaseSchema, i as createCustomTool, l as serializeCustomToolkits, n as buildCustomToolsMap, o as findCustomToolMapEntryByFinalSlug, p as CustomToolSlugSchema, r as buildCustomToolsMapFromResponse, s as findCustomToolMapEntryByToolkitAndOriginalSlug, t as assertNoCustomToolSlugsInPreload, u as serializeCustomTools } from "./CustomTool-C_5NvBsX.mjs";
5
+ import { a as removeNonRequiredProperties, i as jsonSchemaToZodSchema, n as deduplicateJsonSchemaRequiredArrays, r as dereferenceJsonSchema, t as withCancellation } from "./cancellation-BbJ-UQ__.mjs";
6
+ import { t as telemetry } from "./Telemetry-CF0rNHu2.mjs";
7
+ import { a as arrayBufferToBase64, c as getRandomShortId, i as readResponseBodyWithLimit, n as assertSafeFileUploadPath, r as isBlockedSensitiveFileUploadPath, t as BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS } from "./sensitiveFileUploadPaths-C43dHP7S.mjs";
8
+ import { a as createCustomToolkit, c as getPreloadedCustomToolSlugs, d as CreateCustomToolBaseSchema, f as CreateCustomToolkitBaseSchema, i as createCustomTool, l as serializeCustomToolkits, n as buildCustomToolsMap, o as findCustomToolMapEntryByFinalSlug, p as CustomToolSlugSchema, r as buildCustomToolsMapFromResponse, s as findCustomToolMapEntryByToolkitAndOriginalSlug, t as assertNoCustomToolSlugsInPreload, u as serializeCustomTools } from "./CustomTool-l-j5HtEf.mjs";
8
9
  import ComposioClient, { APIError, BadRequestError } from "@composio/client";
9
10
  import { FileToolModifier } from "#file_tool_modifier";
10
11
  import z, { z as z$1 } from "zod/v3";
@@ -13,6 +14,7 @@ import { platform } from "#platform";
13
14
  import { APIError as APIError$1 } from "openai";
14
15
  import semver from "semver";
15
16
  import { Files } from "#files";
17
+ import { ssrfSafeFetch } from "#ssrf_guard";
16
18
 
17
19
  //#region src/types/authConfigs.types.ts
18
20
  const AuthConfigTypes = {
@@ -6004,7 +6006,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
6004
6006
 
6005
6007
  //#endregion
6006
6008
  //#region package.json
6007
- var version = "0.14.0";
6009
+ var version = "0.14.1";
6008
6010
 
6009
6011
  //#endregion
6010
6012
  //#region src/utils/session.ts
@@ -6861,9 +6863,9 @@ var ToolRouterSessionFilesMount = class {
6861
6863
  async normalizeUploadInput(input, options) {
6862
6864
  if (typeof input === "string") {
6863
6865
  if (input.startsWith("http://") || input.startsWith("https://")) {
6864
- const response = await fetch(input);
6866
+ const response = await ssrfSafeFetch(input);
6865
6867
  if (!response.ok) throw new Error(`Failed to fetch file from URL: ${response.statusText}`);
6866
- const arrayBuffer = await response.arrayBuffer();
6868
+ const content = await readResponseBodyWithLimit(response);
6867
6869
  const mimeType = (response.headers.get("content-type") || "application/octet-stream").split(";")[0].trim();
6868
6870
  const segments = new URL(input).pathname.split("/").filter(Boolean);
6869
6871
  let filename = segments.length > 0 ? segments[segments.length - 1] : "";
@@ -6872,7 +6874,7 @@ var ToolRouterSessionFilesMount = class {
6872
6874
  filename = `${getRandomShortId()}.${extension}`;
6873
6875
  }
6874
6876
  return {
6875
- fileToUpload: new File([arrayBuffer], filename, { type: mimeType }),
6877
+ fileToUpload: new File([content], filename, { type: mimeType }),
6876
6878
  remotePath: options.remotePath ?? filename,
6877
6879
  mimetype: mimeType
6878
6880
  };
@@ -6908,6 +6910,8 @@ var ToolRouterSessionFilesMount = class {
6908
6910
  *
6909
6911
  * Accepts a file path (local or URL), a native File object, or a raw buffer.
6910
6912
  * The file is stored in the virtual filesystem associated with the tool router session.
6913
+ * URL inputs require a Node.js or Bun runtime so the destination can be DNS-validated;
6914
+ * edge runtimes must fetch the file themselves and pass a File or ArrayBuffer.
6911
6915
  *
6912
6916
  * @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array).
6913
6917
  * @param options - Optional configuration. When passing a buffer, remotePath is required.
@@ -1,6 +1,5 @@
1
1
  import { n as FileUploadData, t as FileDownloadData } from "../files.types-DeMC_mAW.mjs";
2
2
  import ComposioClient from "@composio/client";
3
-
4
3
  //#region src/models/Files.node.d.ts
5
4
  declare class Files {
6
5
  private readonly client;
@@ -27,11 +26,7 @@ declare class Files {
27
26
  * toolkitSlug: 'google_drive'
28
27
  * });
29
28
  * */
30
- upload({
31
- file,
32
- toolSlug,
33
- toolkitSlug
34
- }: {
29
+ upload({ file, toolSlug, toolkitSlug }: {
35
30
  file: File | string;
36
31
  toolSlug: string;
37
32
  toolkitSlug: string;
@@ -41,11 +36,7 @@ declare class Files {
41
36
  * @param s3key - The S3 key of the file to download.
42
37
  * @returns The file data.
43
38
  */
44
- download({
45
- toolSlug,
46
- s3Url,
47
- mimeType
48
- }: {
39
+ download({ toolSlug, s3Url, mimeType }: {
49
40
  s3Url: string;
50
41
  toolSlug: string;
51
42
  mimeType: string;
@@ -1,5 +1,5 @@
1
- import { t as telemetry } from "../Telemetry-llfvticE.mjs";
2
- import { n as getFileDataAfterUploadingToS3, t as downloadFileFromS3 } from "../fileUtils.node-iPFi2o4i.mjs";
1
+ import { t as telemetry } from "../Telemetry-CF0rNHu2.mjs";
2
+ import { n as getFileDataAfterUploadingToS3, t as downloadFileFromS3 } from "../fileUtils.node-DOkW4PBg.mjs";
3
3
 
4
4
  //#region src/models/Files.node.ts
5
5
  var Files = class {
@@ -1,5 +1,4 @@
1
1
  import ComposioClient from "@composio/client";
2
-
3
2
  //#region src/models/Files.workerd.d.ts
4
3
  /**
5
4
  * Files class for Cloudflare Workers / Edge runtimes.
@@ -1,5 +1,4 @@
1
1
  import { t as Platform } from "../types-DY1r-kN9.mjs";
2
-
3
2
  //#region src/platform/node.d.ts
4
3
  /**
5
4
  * Node.js platform implementation.
@@ -1,5 +1,4 @@
1
1
  import { t as Platform } from "../types-DY1r-kN9.mjs";
2
-
3
2
  //#region src/platform/workerd.d.ts
4
3
  /**
5
4
  * Cloudflare Workers / Edge runtime platform implementation.
@@ -1,4 +1,28 @@
1
1
  //#region src/platform/workerd.ts
2
+ const SLASH_CHAR_CODE = 47;
3
+ /**
4
+ * Trailing-slash trim without a regex. The equivalent pattern backtracks
5
+ * quadratically on long runs of slashes (CodeQL js/polynomial-redos), so this
6
+ * walks the string from the end instead. Returns the input unchanged when
7
+ * there is nothing to trim, so the common case allocates nothing.
8
+ */
9
+ const trimTrailingSlashes = (value) => {
10
+ let end = value.length;
11
+ while (end > 0 && value.charCodeAt(end - 1) === SLASH_CHAR_CODE) end--;
12
+ return end === value.length ? value : value.slice(0, end);
13
+ };
14
+ /**
15
+ * Leading-and-trailing slash trim without a regex, matching the semantics of
16
+ * the previous leading/trailing slash-trim replace for every input, including
17
+ * a string that is entirely slashes.
18
+ */
19
+ const trimSurroundingSlashes = (value) => {
20
+ let start = 0;
21
+ let end = value.length;
22
+ while (start < end && value.charCodeAt(start) === SLASH_CHAR_CODE) start++;
23
+ while (end > start && value.charCodeAt(end - 1) === SLASH_CHAR_CODE) end--;
24
+ return start === 0 && end === value.length ? value : value.slice(start, end);
25
+ };
2
26
  /**
3
27
  * Cloudflare Workers / Edge runtime platform implementation.
4
28
  * Provides stub implementations for file system operations that are unavailable in edge runtimes.
@@ -11,8 +35,8 @@ const platform = {
11
35
  },
12
36
  joinPath(...paths) {
13
37
  return paths.map((segment, index) => {
14
- if (index === 0) return segment.replace(/\/+$/, "");
15
- return segment.replace(/^\/+|\/+$/g, "");
38
+ if (index === 0) return trimTrailingSlashes(segment);
39
+ return trimSurroundingSlashes(segment);
16
40
  }).filter(Boolean).join("/");
17
41
  },
18
42
  resolvePath(...paths) {
@@ -22,7 +46,7 @@ const platform = {
22
46
  return filePath.startsWith("/");
23
47
  },
24
48
  basename(filePath) {
25
- const segments = filePath.replace(/\/+$/, "").split("/");
49
+ const segments = trimTrailingSlashes(filePath).split("/");
26
50
  return segments[segments.length - 1] || "";
27
51
  },
28
52
  existsSync(_filePath) {
@@ -1,4 +1,4 @@
1
- import { s as ComposioSensitiveFilePathBlockedError } from "./SsrfErrors-BQRozkeU.mjs";
1
+ import { a as ComposioSensitiveFilePathBlockedError } from "./FileModifierErrors-B8V8_3VE.mjs";
2
2
  import { platform } from "#platform";
3
3
 
4
4
  //#region src/utils/uuid.ts
@@ -32,6 +32,56 @@ const uint8ArrayToBase64 = (bytes) => {
32
32
  return btoa(binary);
33
33
  };
34
34
 
35
+ //#endregion
36
+ //#region src/utils/readResponseBody.ts
37
+ /** Maximum size accepted for files fetched from user-supplied URLs (100 MiB). */
38
+ const MAX_URL_UPLOAD_SIZE_BYTES = 100 * 1024 * 1024;
39
+ const sizeLimitError = (actualSize, maxBytes) => /* @__PURE__ */ new Error(`File size (${actualSize} bytes) exceeds maximum allowed size (${maxBytes} bytes)`);
40
+ /**
41
+ * Read a fetch response without allowing an untrusted server to exhaust memory.
42
+ *
43
+ * `Content-Length` is checked as an early rejection, but the streamed byte
44
+ * count is authoritative because the header can be absent or dishonest.
45
+ */
46
+ const readResponseBodyWithLimit = async (response, maxBytes = MAX_URL_UPLOAD_SIZE_BYTES) => {
47
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError("maxBytes must be a non-negative safe integer");
48
+ const contentLength = response.headers.get("content-length")?.trim();
49
+ if (contentLength && /^\d+$/.test(contentLength)) {
50
+ const declaredSize = Number(contentLength);
51
+ if (!Number.isSafeInteger(declaredSize) || declaredSize > maxBytes) {
52
+ const error = sizeLimitError(declaredSize, maxBytes);
53
+ await response.body?.cancel(error).catch(() => void 0);
54
+ throw error;
55
+ }
56
+ }
57
+ if (!response.body) return /* @__PURE__ */ new Uint8Array();
58
+ const reader = response.body.getReader();
59
+ const chunks = [];
60
+ let totalBytes = 0;
61
+ try {
62
+ while (true) {
63
+ const { done, value } = await reader.read();
64
+ if (done) break;
65
+ if (!value || value.byteLength === 0) continue;
66
+ totalBytes += value.byteLength;
67
+ if (totalBytes > maxBytes) {
68
+ await reader.cancel(sizeLimitError(totalBytes, maxBytes));
69
+ throw sizeLimitError(totalBytes, maxBytes);
70
+ }
71
+ chunks.push(value);
72
+ }
73
+ } finally {
74
+ reader.releaseLock();
75
+ }
76
+ const body = new Uint8Array(totalBytes);
77
+ let offset = 0;
78
+ for (const chunk of chunks) {
79
+ body.set(chunk, offset);
80
+ offset += chunk.byteLength;
81
+ }
82
+ return body;
83
+ };
84
+
35
85
  //#endregion
36
86
  //#region src/utils/sensitiveFileUploadPaths.ts
37
87
  /**
@@ -111,4 +161,4 @@ function assertSafeFileUploadPath(filePath, options) {
111
161
  }
112
162
 
113
163
  //#endregion
114
- export { base64ToUint8Array as a, getRandomUUID as c, arrayBufferToBase64 as i, assertSafeFileUploadPath as n, uint8ArrayToBase64 as o, isBlockedSensitiveFileUploadPath as r, getRandomShortId as s, BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS as t };
164
+ export { arrayBufferToBase64 as a, getRandomShortId as c, readResponseBodyWithLimit as i, getRandomUUID as l, assertSafeFileUploadPath as n, base64ToUint8Array as o, isBlockedSensitiveFileUploadPath as r, uint8ArrayToBase64 as s, BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS as t };
@@ -1,6 +1,5 @@
1
- import { n as BaseComposioProvider } from "./BaseProvider-lCxnjFKQ.mjs";
2
- import { n as ComposioConfig } from "./composio-6C8kHtqc.mjs";
3
-
1
+ import { n as BaseComposioProvider } from "./BaseProvider-Dc5yKZhk.mjs";
2
+ import { n as ComposioConfig } from "./composio-ChU3eD9F.mjs";
4
3
  //#region src/utils/config-defaults/types.d.ts
5
4
  /**
6
5
  * Configuration defaults for Composio.
@@ -1,5 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-yCrveqAj.mjs";
2
-
1
+ import { t as ConfigDefaults } from "../../types-D5N60gUD.mjs";
3
2
  //#region src/utils/config-defaults/ConfigDefaults.node.d.ts
4
3
  declare const CONFIG_DEFAULTS: ConfigDefaults;
5
4
  //#endregion
@@ -1,5 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-yCrveqAj.mjs";
2
-
1
+ import { t as ConfigDefaults } from "../../types-D5N60gUD.mjs";
3
2
  //#region src/utils/config-defaults/ConfigDefaults.workerd.d.ts
4
3
  declare const CONFIG_DEFAULTS: ConfigDefaults;
5
4
  //#endregion
@@ -1,6 +1,5 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-lCxnjFKQ.mjs";
1
+ import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-Dc5yKZhk.mjs";
2
2
  import ComposioClient from "@composio/client";
3
-
4
3
  //#region src/utils/modifiers/FileToolModifier.node.d.ts
5
4
  declare class FileToolModifier {
6
5
  private client;
@@ -1,8 +1,9 @@
1
- import { a as ComposioFileUploadError, i as ComposioFileUploadAbortedError, o as ComposioFileUploadPathNotAllowedError, r as ComposioFileNotFoundError, s as ComposioSensitiveFilePathBlockedError, u as logger } from "../../SsrfErrors-BQRozkeU.mjs";
2
- import { f as ComposioRequestCancelledError } from "../../errors-B165yJUQ.mjs";
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";
3
4
  import { i as transformProperties, n as schemaHasFileProperty, t as isPlainObject } from "../../FileToolModifier.utils.neutral-B5rT711M.mjs";
4
- import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-W65QRyj2.mjs";
5
- import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-iPFi2o4i.mjs";
5
+ import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-BbJ-UQ__.mjs";
6
+ import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-DOkW4PBg.mjs";
6
7
 
7
8
  //#region src/utils/modifiers/FileToolModifier.node.ts
8
9
  /**
@@ -1,6 +1,5 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-lCxnjFKQ.mjs";
1
+ import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-Dc5yKZhk.mjs";
2
2
  import ComposioClient from "@composio/client";
3
-
4
3
  //#region src/utils/modifiers/FileToolModifier.workerd.d.ts
5
4
  declare class FileToolModifier {
6
5
  constructor(_client: ComposioClient);
@@ -0,0 +1,22 @@
1
+ //#region src/utils/ssrfGuard.node.d.ts
2
+ /**
3
+ * True when `ip` is a private, loopback, link-local, or otherwise
4
+ * non-publicly-routable address. Fails closed (returns `true`) for anything that
5
+ * is not a valid IPv4/IPv6 literal.
6
+ */
7
+ declare const isBlockedIp: (ip: string) => boolean;
8
+ /**
9
+ * Validate a single URL: it must be http(s), its host must resolve, and every
10
+ * resolved address must be publicly routable. Throws
11
+ * {@link ComposioBlockedInternalUrlError} otherwise.
12
+ */
13
+ declare const assertSafeFetchTarget: (rawUrl: string) => Promise<void>;
14
+ /**
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}). Non-redirect responses are returned
18
+ * unchanged.
19
+ */
20
+ declare const ssrfSafeFetch: (rawUrl: string, init?: RequestInit, maxRedirects?: number) => Promise<Response>;
21
+ //#endregion
22
+ export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch };
@@ -0,0 +1,152 @@
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/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}). Non-redirect responses are returned
135
+ * 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
+ currentUrl = new URL(response.headers.get("location"), currentUrl).toString();
147
+ }
148
+ throw new ComposioBlockedInternalUrlError(`Refusing to fetch: too many redirects (max ${maxRedirects})`, { url: rawUrl });
149
+ };
150
+
151
+ //#endregion
152
+ export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch };
@@ -0,0 +1,9 @@
1
+ //#region src/utils/ssrfGuard.workerd.d.ts
2
+ /**
3
+ * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
4
+ * hostname is publicly routable before connecting. Fail closed instead of
5
+ * falling back to an unguarded fetch.
6
+ */
7
+ declare const ssrfSafeFetch: (rawUrl: string) => Promise<Response>;
8
+ //#endregion
9
+ export { ssrfSafeFetch };
@@ -0,0 +1,17 @@
1
+ import { t as ComposioBlockedInternalUrlError } from "../SsrfErrors-DNJt57GL.mjs";
2
+
3
+ //#region src/utils/ssrfGuard.workerd.ts
4
+ /**
5
+ * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
6
+ * hostname is publicly routable before connecting. Fail closed instead of
7
+ * falling back to an unguarded fetch.
8
+ */
9
+ const ssrfSafeFetch = async (rawUrl) => {
10
+ throw new ComposioBlockedInternalUrlError("URL file uploads are not supported in edge runtimes because the destination cannot be safely validated", {
11
+ url: rawUrl,
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
+ });
14
+ };
15
+
16
+ //#endregion
17
+ export { ssrfSafeFetch };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@composio/core",
3
3
  "type": "module",
4
- "version": "0.14.0",
4
+ "version": "0.14.1",
5
5
  "description": "",
6
6
  "main": "dist/index.mjs",
7
7
  "publishConfig": {
@@ -31,6 +31,12 @@
31
31
  "edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
32
32
  "node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
33
33
  "default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
34
+ },
35
+ "#ssrf_guard": {
36
+ "workerd": "./dist/utils/ssrfGuard.workerd.mjs",
37
+ "edge-light": "./dist/utils/ssrfGuard.workerd.mjs",
38
+ "node": "./dist/utils/ssrfGuard.node.mjs",
39
+ "default": "./dist/utils/ssrfGuard.node.mjs"
34
40
  }
35
41
  },
36
42
  "exports": {
@@ -85,10 +91,10 @@
85
91
  "devDependencies": {
86
92
  "@type-challenges/utils": "^0.1.1",
87
93
  "@types/semver": "^7.7.1",
88
- "tsdown": "^0.22.3",
89
- "tsx": "^4.23.0",
94
+ "tsdown": "^0.22.14",
95
+ "tsx": "^4.23.1",
90
96
  "typedoc": "^0.28.20",
91
- "typescript": "^6.0.3",
97
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
92
98
  "vitest": "^4.1.10",
93
99
  "zod": "^4.4.3"
94
100
  },
@@ -96,11 +102,11 @@
96
102
  "zod": ">=3.25.76 <5"
97
103
  },
98
104
  "dependencies": {
99
- "@composio/client": "0.1.0-alpha.75",
105
+ "@composio/client": "0.1.0-alpha.76",
100
106
  "@types/json-schema": "^7.0.15",
101
- "openai": "^6.45.0",
107
+ "openai": "^6.49.0",
102
108
  "picocolors": "^1.1.1",
103
- "pusher-js": "^8.5.0",
109
+ "pusher-js": "^8.6.0",
104
110
  "semver": "^7.8.5",
105
111
  "zod-to-json-schema": "^3.25.2",
106
112
  "@composio/json-schema-to-zod": "0.2.1"
@@ -119,8 +125,7 @@
119
125
  "clean": "git clean -xdf node_modules",
120
126
  "build": "pnpm exec tsdown",
121
127
  "test": "vitest run",
122
- "typecheck": "pnpm exec tsgo --noEmit --skipLibCheck && pnpm exec tsgo --noEmit --skipLibCheck -p tsconfig.type-tests.json",
123
- "typecheck:tsc": "tsc --noEmit --skipLibCheck && tsc --noEmit --skipLibCheck -p tsconfig.type-tests.json",
128
+ "typecheck": "tsc --noEmit --skipLibCheck && tsc --noEmit --skipLibCheck -p tsconfig.type-tests.json",
124
129
  "generate:docs": "tsx scripts/generate-docs.ts"
125
130
  },
126
131
  "types": "dist/index.d.mts"
@@ -14,9 +14,10 @@ export interface ComposioBlockedInternalUrlErrorOptions extends Omit<ComposioErr
14
14
  /**
15
15
  * Thrown when a URL file input resolves to a private, loopback, link-local, or
16
16
  * otherwise internal address, or points at a non-http(s) scheme. Guards against
17
- * turning `composio.files.upload(url)` (and automatic upload during tool
18
- * execution) into a server-side request forgery (SSRF) probe of internal
19
- * infrastructure such as cloud metadata endpoints (`169.254.169.254`).
17
+ * turning URL-based file uploads (including Tool Router session files and
18
+ * automatic upload during tool execution) into a server-side request forgery
19
+ * (SSRF) probe of internal infrastructure such as cloud metadata endpoints
20
+ * (`169.254.169.254`).
20
21
  */
21
22
  export class ComposioBlockedInternalUrlError extends ComposioError {
22
23
  constructor(
@@ -18,7 +18,9 @@ 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
22
  import { getExtensionFromMimeType } from '../utils/mime';
23
+ import { readResponseBodyWithLimit } from '../utils/readResponseBody';
22
24
  import { getRandomShortId } from '../utils/uuid';
23
25
 
24
26
  /**
@@ -110,11 +112,11 @@ export class ToolRouterSessionFilesMount {
110
112
  ): Promise<{ fileToUpload: File; remotePath: string; mimetype: string }> {
111
113
  if (typeof input === 'string') {
112
114
  if (input.startsWith('http://') || input.startsWith('https://')) {
113
- const response = await fetch(input);
115
+ const response = await ssrfSafeFetch(input);
114
116
  if (!response.ok) {
115
117
  throw new Error(`Failed to fetch file from URL: ${response.statusText}`);
116
118
  }
117
- const arrayBuffer = await response.arrayBuffer();
119
+ const content = await readResponseBodyWithLimit(response);
118
120
  const rawContentType = response.headers.get('content-type') || 'application/octet-stream';
119
121
  const mimeType = rawContentType.split(';')[0].trim();
120
122
  const url = new URL(input);
@@ -125,7 +127,7 @@ export class ToolRouterSessionFilesMount {
125
127
  const extension = getExtensionFromMimeType(mimeType);
126
128
  filename = `${getRandomShortId()}.${extension}`;
127
129
  }
128
- const file = new File([arrayBuffer], filename, { type: mimeType });
130
+ const file = new File([content as BlobPart], filename, { type: mimeType });
129
131
  return {
130
132
  fileToUpload: file,
131
133
  remotePath: options.remotePath ?? filename,
@@ -178,6 +180,8 @@ export class ToolRouterSessionFilesMount {
178
180
  *
179
181
  * Accepts a file path (local or URL), a native File object, or a raw buffer.
180
182
  * The file is stored in the virtual filesystem associated with the tool router session.
183
+ * URL inputs require a Node.js or Bun runtime so the destination can be DNS-validated;
184
+ * edge runtimes must fetch the file themselves and pass a File or ArrayBuffer.
181
185
  *
182
186
  * @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array).
183
187
  * @param options - Optional configuration. When passing a buffer, remotePath is required.