@composio/core 0.14.0 → 0.15.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 (52) hide show
  1. package/dist/{BaseProvider-lCxnjFKQ.d.mts → BaseProvider-BN2-Nktx.d.mts} +224 -180
  2. package/dist/{CustomTool-C_5NvBsX.mjs → CustomTool-l-j5HtEf.mjs} +1 -1
  3. package/dist/{CustomTool-CmokRT9q.d.mts → CustomTool-zjeDpZ91.d.mts} +1 -2
  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-DuGJSwUt.mjs} +3 -3
  7. package/dist/{cancellation-W65QRyj2.mjs → cancellation-BbJ-UQ__.mjs} +2 -2
  8. package/dist/{composio-6C8kHtqc.d.mts → composio-Bf8hnBBq.d.mts} +24 -21
  9. package/dist/{customTool.types-kFhNYuzh.d.mts → customTool.types-Bhom9a2R.d.mts} +73 -40
  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-BQ0fWge3.mjs} +9 -154
  15. package/dist/index.d.mts +1585 -752
  16. package/dist/index.mjs +39 -20
  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 +1 -2
  21. package/dist/platform/node.mjs +24 -0
  22. package/dist/platform/workerd.d.mts +1 -2
  23. package/dist/platform/workerd.mjs +30 -3
  24. package/dist/{sensitiveFileUploadPaths-B1OLsd8F.mjs → sensitiveFileUploadPaths-BVEt0peg.mjs} +64 -9
  25. package/dist/{types-yCrveqAj.d.mts → types-CePuCfD-.d.mts} +2 -3
  26. package/dist/{types-DY1r-kN9.d.mts → types-D5A2wzBl.d.mts} +8 -0
  27. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -2
  28. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -2
  29. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -2
  30. package/dist/utils/modifiers/FileToolModifier.node.mjs +5 -4
  31. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -2
  32. package/dist/utils/ssrfGuard.node.d.mts +22 -0
  33. package/dist/utils/ssrfGuard.node.mjs +153 -0
  34. package/dist/utils/ssrfGuard.workerd.d.mts +9 -0
  35. package/dist/utils/ssrfGuard.workerd.mjs +17 -0
  36. package/package.json +17 -11
  37. package/src/errors/SsrfErrors.ts +4 -3
  38. package/src/models/ToolRouterSessionFileMount.ts +10 -3
  39. package/src/platform/node.ts +40 -0
  40. package/src/platform/types.ts +9 -0
  41. package/src/platform/workerd.ts +35 -3
  42. package/src/telemetry/redact.ts +6 -1
  43. package/src/types/tool.types.ts +52 -8
  44. package/src/utils/fileUtils.node.ts +5 -2
  45. package/src/utils/modifiers/FileToolModifier.node.ts +3 -3
  46. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +6 -4
  47. package/src/utils/readResponseBody.ts +63 -0
  48. package/src/utils/sdk.ts +2 -2
  49. package/src/utils/sensitiveFileUploadPaths.ts +12 -9
  50. package/src/utils/ssrfGuard.node.ts +12 -8
  51. package/src/utils/ssrfGuard.workerd.ts +19 -0
  52. package/src/utils/version.ts +21 -20
@@ -0,0 +1,63 @@
1
+ /** Maximum size accepted for files fetched from user-supplied URLs (100 MiB). */
2
+ export const MAX_URL_UPLOAD_SIZE_BYTES = 100 * 1024 * 1024;
3
+
4
+ const sizeLimitError = (actualSize: number, maxBytes: number): Error =>
5
+ new Error(`File size (${actualSize} bytes) exceeds maximum allowed size (${maxBytes} bytes)`);
6
+
7
+ /**
8
+ * Read a fetch response without allowing an untrusted server to exhaust memory.
9
+ *
10
+ * `Content-Length` is checked as an early rejection, but the streamed byte
11
+ * count is authoritative because the header can be absent or dishonest.
12
+ */
13
+ export const readResponseBodyWithLimit = async (
14
+ response: Response,
15
+ maxBytes: number = MAX_URL_UPLOAD_SIZE_BYTES
16
+ ): Promise<Uint8Array> => {
17
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
18
+ throw new RangeError('maxBytes must be a non-negative safe integer');
19
+ }
20
+
21
+ const contentLength = response.headers.get('content-length')?.trim();
22
+ if (contentLength && /^\d+$/.test(contentLength)) {
23
+ const declaredSize = Number(contentLength);
24
+ if (!Number.isSafeInteger(declaredSize) || declaredSize > maxBytes) {
25
+ const error = sizeLimitError(declaredSize, maxBytes);
26
+ await response.body?.cancel(error).catch(() => undefined);
27
+ throw error;
28
+ }
29
+ }
30
+
31
+ if (!response.body) {
32
+ return new Uint8Array();
33
+ }
34
+
35
+ const reader = response.body.getReader();
36
+ const chunks: Uint8Array[] = [];
37
+ let totalBytes = 0;
38
+
39
+ try {
40
+ while (true) {
41
+ const { done, value } = await reader.read();
42
+ if (done) break;
43
+ if (!value || value.byteLength === 0) continue;
44
+
45
+ totalBytes += value.byteLength;
46
+ if (totalBytes > maxBytes) {
47
+ await reader.cancel(sizeLimitError(totalBytes, maxBytes));
48
+ throw sizeLimitError(totalBytes, maxBytes);
49
+ }
50
+ chunks.push(value);
51
+ }
52
+ } finally {
53
+ reader.releaseLock();
54
+ }
55
+
56
+ const body = new Uint8Array(totalBytes);
57
+ let offset = 0;
58
+ for (const chunk of chunks) {
59
+ body.set(chunk, offset);
60
+ offset += chunk.byteLength;
61
+ }
62
+ return body;
63
+ };
package/src/utils/sdk.ts CHANGED
@@ -64,8 +64,8 @@ export function getSDKConfig(baseUrl?: string | null, apiKey?: string | null) {
64
64
  *
65
65
  * Priority order:
66
66
  * 1. If defaultVersions is a string, use it as global version for all toolkits
67
- * 2. Environment variables (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>)
68
- * 3. User-provided toolkit version mappings (defaultVersions object)
67
+ * 2. User-provided toolkit version mappings (defaultVersions object)
68
+ * 3. Environment variables (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>)
69
69
  * 4. Fallback to 'latest' if no versions are configured
70
70
  *
71
71
  * @param defaultVersions - Optional default versions configuration (string for global version or object mapping toolkit names to versions)
@@ -12,7 +12,8 @@ import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErr
12
12
 
13
13
  /**
14
14
  * Path segments (a single path component) that indicate a sensitive directory when
15
- * they appear anywhere in a resolved local path. Compared case-insensitively on Windows.
15
+ * they appear anywhere in a resolved local path. Matching follows the case sensitivity
16
+ * of the filesystem containing that path.
16
17
  */
17
18
  export const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: readonly string[] = [
18
19
  '.ssh',
@@ -30,12 +31,10 @@ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
30
31
  /** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
31
32
  const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
32
33
 
33
- const isWindows = typeof process !== 'undefined' && process.platform === 'win32';
34
-
35
34
  /**
36
35
  * Returns normalized path segments, resolving symlinks when the path exists.
37
36
  */
38
- function normalizePathSegments(filePath: string): string[] {
37
+ function normalizePath(filePath: string): { resolvedPath: string; segments: string[] } {
39
38
  const absolute = platform.resolvePath(filePath);
40
39
  let resolved = absolute;
41
40
  try {
@@ -45,7 +44,10 @@ function normalizePathSegments(filePath: string): string[] {
45
44
  } catch {
46
45
  // If realpath fails (e.g. race), use resolved path
47
46
  }
48
- return resolved.split(/[/\\]+/).filter(Boolean);
47
+ return {
48
+ resolvedPath: resolved,
49
+ segments: resolved.split(/[/\\]+/).filter(Boolean),
50
+ };
49
51
  }
50
52
 
51
53
  /**
@@ -63,16 +65,17 @@ function getSensitiveFileUploadPathBlockReason(
63
65
  filePath: string,
64
66
  additionalDenySegments?: string[]
65
67
  ): string | null {
66
- const segments = normalizePathSegments(filePath);
68
+ const { resolvedPath, segments } = normalizePath(filePath);
69
+ const isCaseSensitive = platform.isFileSystemCaseSensitive?.(resolvedPath) ?? true;
70
+ const normalizeSegment = (segment: string) => (isCaseSensitive ? segment : segment.toLowerCase());
67
71
  const deny = new Set(
68
72
  [
69
73
  ...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
70
74
  ...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),
71
- ].map(s => (isWindows ? s.toLowerCase() : s))
75
+ ].map(normalizeSegment)
72
76
  );
73
77
 
74
- // Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.
75
- const segmentsForMatch = isWindows ? segments.map(s => s.toLowerCase()) : segments;
78
+ const segmentsForMatch = isCaseSensitive ? segments : segments.map(normalizeSegment);
76
79
  for (let i = 0; i < segments.length; i++) {
77
80
  if (deny.has(segmentsForMatch[i]!)) {
78
81
  return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
@@ -5,12 +5,12 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
5
5
  /**
6
6
  * SSRF guard for user-supplied URL file inputs.
7
7
  *
8
- * `composio.files.upload(url)` and automatic file upload during tool execution
9
- * fetch arbitrary user-provided URLs. Without a guard, a caller (or a tool
10
- * argument produced by an LLM) can point the SDK at internal infrastructure —
11
- * loopback, RFC1918 ranges, link-local cloud-metadata endpoints
12
- * (`169.254.169.254`), or a public URL that 3xx-redirects into internal space —
13
- * turning the SDK into a server-side request forgery probe.
8
+ * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
9
+ * file upload during tool execution fetch arbitrary user-provided URLs. Without
10
+ * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
11
+ * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
12
+ * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
13
+ * space — turning the SDK into a server-side request forgery probe.
14
14
  *
15
15
  * This module validates the *resolved* address (not just the hostname string,
16
16
  * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
@@ -171,8 +171,8 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
171
171
  /**
172
172
  * Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
173
173
  * connecting and re-validates every redirect hop (redirects are followed
174
- * manually up to {@link MAX_REDIRECTS}). Non-redirect responses are returned
175
- * unchanged.
174
+ * manually up to {@link MAX_REDIRECTS}). Intermediate redirect bodies are
175
+ * cancelled; non-redirect responses are returned unchanged.
176
176
  */
177
177
  export const ssrfSafeFetch = async (
178
178
  rawUrl: string,
@@ -192,6 +192,10 @@ export const ssrfSafeFetch = async (
192
192
  return response;
193
193
  }
194
194
 
195
+ // Only `location` is read from a redirect, so release its body explicitly rather
196
+ // than leaving it to the garbage collector (mirrors `readResponseBodyWithLimit`).
197
+ await response.body?.cancel().catch(() => undefined);
198
+
195
199
  currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
196
200
  }
197
201
 
@@ -0,0 +1,19 @@
1
+ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
2
+
3
+ /**
4
+ * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
5
+ * hostname is publicly routable before connecting. Fail closed instead of
6
+ * falling back to an unguarded fetch.
7
+ */
8
+ export const ssrfSafeFetch = async (rawUrl: string): Promise<Response> => {
9
+ throw new ComposioBlockedInternalUrlError(
10
+ 'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',
11
+ {
12
+ url: rawUrl,
13
+ possibleFixes: [
14
+ 'Fetch the public URL yourself and pass a File or ArrayBuffer instead',
15
+ 'Run the URL upload in a Node.js or Bun runtime',
16
+ ],
17
+ }
18
+ );
19
+ };
@@ -2,26 +2,14 @@ import logger from './logger';
2
2
  import { IS_DEVELOPMENT_OR_CI } from './constants';
3
3
  import semver from 'semver';
4
4
 
5
- /**
6
- * Compares two semantic versions and returns true if the first version is newer than the second.
7
- * @param version1 The first version to compare
8
- * @param version2 The second version to compare
9
- * @returns boolean indicating if version1 is newer than version2
10
- */
11
- export function isNewerVersion(version1: string, version2: string): boolean {
12
- const v1 = version1.split('.').map(Number);
13
- const v2 = version2.split('.').map(Number);
14
-
15
- for (let i = 0; i < 3; i++) {
16
- if (v1[i] > v2[i]) return true;
17
- if (v1[i] < v2[i]) return false;
18
- }
19
- return false;
20
- }
5
+ const VERSION_CHECK_TIMEOUT_MS = 2_000;
21
6
 
22
7
  /**
23
8
  * Checks for the latest version of the Composio SDK from NPM.
24
9
  * If a newer version is available, it logs a warning to the console.
10
+ *
11
+ * Best-effort: never throws. The npm registry request is aborted after
12
+ * {@link VERSION_CHECK_TIMEOUT_MS} milliseconds.
25
13
  */
26
14
  export async function checkForLatestVersionFromNPM(currentVersion: string) {
27
15
  try {
@@ -42,14 +30,27 @@ export async function checkForLatestVersionFromNPM(currentVersion: string) {
42
30
  return;
43
31
  }
44
32
 
45
- // @TODO: Check if fetch is available, if not use node-fetch
46
- const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
47
- const data = await response.json();
33
+ // Bound this best-effort request so a stalled registry cannot leave it pending
34
+ // indefinitely. A hand-rolled timer rather than AbortSignal.timeout so it can be
35
+ // cleared the moment the response lands: an uncleared timer is itself pending work,
36
+ // which on workerd pins the request context open for the full timeout on every
37
+ // successful check.
38
+ const controller = new AbortController();
39
+ const timer = setTimeout(() => controller.abort(), VERSION_CHECK_TIMEOUT_MS);
40
+ let data;
41
+ try {
42
+ const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`, {
43
+ signal: controller.signal,
44
+ });
45
+ data = await response.json();
46
+ } finally {
47
+ clearTimeout(timer);
48
+ }
48
49
  const latestVersion = data.version;
49
50
 
50
51
  if (semver.gt(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
51
52
  logger.info(
52
- `🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
53
+ `🚀 Upgrade available! Your ${packageName} version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
53
54
  );
54
55
  }
55
56
  } catch (_error) {