Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | // The upload pipeline runs in the caller's fiber: the FileSystem read and the |
| 2 | // presigned-URL request are effects of their own, and the core SDK's |
| 3 | // promise-based helpers (the path and URL guards, the body reader, the upload |
| 4 | // transport) are wrapped at each call. The caller resolves the platform |
| 5 | // services and the Composio client and passes the instances in as parameters. |
| 6 | import type * as FileSystem from 'effect/FileSystem'; |
| 7 | import type * as Path from 'effect/Path'; |
| 8 | import type { ComposioClientShape, ComposioError } from '@composio/client/effect'; |
| 9 | import { Data, Effect, Predicate, Schema } from 'effect'; |
| 10 | import mime from 'mime'; |
| 11 | import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug'; |
| 12 | import { isPlainRecord } from 'src/utils/parse-json'; |
| 13 | import { idempotent } from 'src/services/composio-request'; |
| 14 | |
| 15 | type JsonSchema = Record<string, unknown>; |
| 16 | /** |
| 17 | * Local path -> the name and MIME type to upload it under, for files their caller |
| 18 | * staged (`composio run` writes each script File to a generated path). Labels |
| 19 | * only: the path is still read, and checked against the denylist, as given. |
| 20 | */ |
| 21 | type StagedFiles = ReadonlyMap<string, { readonly name: string; readonly mimetype?: string }>; |
| 22 | |
| 23 | // The core helpers below are only reached once an execute actually carries |
| 24 | // a file input, so they are imported on that path rather than at module scope: |
| 25 | // `@composio/core`'s root entry evaluates the whole SDK, which every command |
| 26 | // would otherwise pay for at startup. The module registry memoizes the import. |
| 27 | const loadCoreFileUploadHelpers = Effect.promise(() => import('@composio/core')); |
| 28 | const loadSsrfSafeFetch = Effect.promise(() => import('@composio/core/utils/ssrf-guard')); |
| 29 | |
| 30 | export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUploadError')<{ |
| 31 | readonly cause?: unknown; |
| 32 | readonly message: string; |
| 33 | readonly reason: |
| 34 | 'not-uploadable' | 'source-fetch' | 'source-read' | 'unsupported-source' | 'upload'; |
| 35 | readonly status?: number; |
| 36 | }> {} |
| 37 | |
| 38 | /** |
| 39 | * Every failure of {@link uploadToolInputFiles}: reading or uploading a file, |
| 40 | * or the presigned-URL request, as the client's own error. |
| 41 | */ |
| 42 | export type ToolInputUploadError = ToolFileUploadError | ComposioError; |
| 43 | |
| 44 | // What a thrown value from the core SDK's helpers, or a platform error of the |
| 45 | // local read, becomes: the file could not be read as a source. An error this |
| 46 | // module raised itself passes through. |
| 47 | const asSourceReadError = (cause: unknown): ToolFileUploadError => |
| 48 | cause instanceof ToolFileUploadError |
| 49 | ? cause |
| 50 | : new ToolFileUploadError({ |
| 51 | cause, |
| 52 | message: cause instanceof Error ? cause.message : String(cause), |
| 53 | reason: 'source-read', |
| 54 | }); |
| 55 | |
| 56 | const decodeRunStagedFiles = Schema.decodeUnknownEffect( |
| 57 | Schema.fromJsonString( |
| 58 | Schema.Record( |
| 59 | Schema.String, |
| 60 | Schema.Struct({ name: Schema.String, mimetype: Schema.optional(Schema.String) }) |
| 61 | ) |
| 62 | ) |
| 63 | ); |
| 64 | |
| 65 | /** Read the per-execute labels without putting the file batch in the environment. */ |
| 66 | export const readRunStagedFiles = ( |
| 67 | fs: FileSystem.FileSystem, |
| 68 | manifestPath: string | undefined |
| 69 | ): Effect.Effect<StagedFiles, ToolFileUploadError> => |
| 70 | Effect.gen(function* () { |
| 71 | if (!manifestPath) return new Map(); |
| 72 | const content = yield* fs.readFileString(manifestPath).pipe(Effect.mapError(asSourceReadError)); |
| 73 | const labels = yield* decodeRunStagedFiles(content).pipe(Effect.mapError(asSourceReadError)); |
| 74 | return new Map(Object.entries(labels)); |
| 75 | }); |
| 76 | |
| 77 | // Releases a body this module does not read, ignoring a cancellation failure. |
| 78 | const discardBody = (response: Response) => |
| 79 | Effect.ignore(Effect.tryPromise(() => response.body?.cancel() ?? Promise.resolve())); |
| 80 | |
| 81 | const isFileLike = (value: unknown): value is File => |
| 82 | typeof File !== 'undefined' && value instanceof File; |
| 83 | |
| 84 | const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isObject(value); |
| 85 | |
| 86 | const getSchemaVariant = (value: unknown): ReadonlyArray<JsonSchema> => |
| 87 | Array.isArray(value) ? value.filter(isSchemaRecord) : []; |
| 88 | |
| 89 | // `items` is either one schema for every element or a tuple of per-index schemas. |
| 90 | const itemSchemaAt = (items: unknown, index: number): JsonSchema | undefined => { |
| 91 | const itemSchema = Array.isArray(items) ? items[index] : items; |
| 92 | return isSchemaRecord(itemSchema) ? itemSchema : undefined; |
| 93 | }; |
| 94 | |
| 95 | const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [ |
| 96 | ...getSchemaVariant(schema?.anyOf), |
| 97 | ...getSchemaVariant(schema?.oneOf), |
| 98 | ...getSchemaVariant(schema?.allOf), |
| 99 | ]; |
| 100 | |
| 101 | const transformSchema = (schema: JsonSchema): JsonSchema => { |
| 102 | if (schema.file_uploadable === true) { |
| 103 | return { |
| 104 | title: schema.title, |
| 105 | description: schema.description, |
| 106 | format: 'path', |
| 107 | type: 'string', |
| 108 | file_uploadable: true, |
| 109 | }; |
| 110 | } |
| 111 | |
| 112 | const transformed: JsonSchema = { ...schema }; |
| 113 | |
| 114 | if (isSchemaRecord(schema.properties)) { |
| 115 | transformed.properties = Object.fromEntries( |
| 116 | Object.entries(schema.properties).map(([key, value]) => [ |
| 117 | key, |
| 118 | isSchemaRecord(value) ? transformSchema(value) : value, |
| 119 | ]) |
| 120 | ); |
| 121 | } |
| 122 | |
| 123 | for (const key of ['anyOf', 'oneOf', 'allOf'] as const) { |
| 124 | if (Array.isArray(schema[key])) { |
| 125 | transformed[key] = schema[key].map(value => |
| 126 | isSchemaRecord(value) ? transformSchema(value) : value |
| 127 | ); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | if (Array.isArray(schema.items)) { |
| 132 | transformed.items = schema.items.map(value => |
| 133 | isSchemaRecord(value) ? transformSchema(value) : value |
| 134 | ); |
| 135 | } else if (isSchemaRecord(schema.items)) { |
| 136 | transformed.items = transformSchema(schema.items); |
| 137 | } |
| 138 | |
| 139 | return transformed; |
| 140 | }; |
| 141 | |
| 142 | export const normalizeFileUploadSchema = (schema: JsonSchema): JsonSchema => |
| 143 | isSchemaRecord(schema) ? transformSchema(schema) : schema; |
| 144 | |
| 145 | export const schemaHasFileUploadable = (schema: JsonSchema | undefined): boolean => { |
| 146 | if (!schema) return false; |
| 147 | if (schema.file_uploadable === true) return true; |
| 148 | |
| 149 | if (isSchemaRecord(schema.properties)) { |
| 150 | for (const property of Object.values(schema.properties)) { |
| 151 | if (isSchemaRecord(property) && schemaHasFileUploadable(property)) { |
| 152 | return true; |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | for (const variant of getSchemaVariants(schema)) { |
| 158 | if (schemaHasFileUploadable(variant)) { |
| 159 | return true; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | if (Array.isArray(schema.items)) { |
| 164 | return schema.items.some(item => isSchemaRecord(item) && schemaHasFileUploadable(item)); |
| 165 | } |
| 166 | |
| 167 | if (isSchemaRecord(schema.items)) { |
| 168 | return schemaHasFileUploadable(schema.items); |
| 169 | } |
| 170 | |
| 171 | return false; |
| 172 | }; |
| 173 | |
| 174 | // Where a value sits in the tool arguments: object keys and array indices. |
| 175 | export type ArgumentPath = ReadonlyArray<string | number>; |
| 176 | |
| 177 | // Whether a branch can describe the value, judged by its `const` properties. |
| 178 | // A supplied property with another value rules the branch out, as does a |
| 179 | // required one the caller left out; an omitted optional one rules nothing out. |
| 180 | const matchesDiscriminants = (schema: JsonSchema, value: unknown): boolean => { |
| 181 | if (!isSchemaRecord(schema.properties) || !isSchemaRecord(value)) return true; |
| 182 | const required = Array.isArray(schema.required) ? schema.required : []; |
| 183 | return Object.entries(schema.properties).every(([key, property]) => { |
| 184 | if (!isSchemaRecord(property) || !Object.hasOwn(property, 'const')) return true; |
| 185 | if (!Object.hasOwn(value, key)) return !required.includes(key); |
| 186 | return value[key] === property.const; |
| 187 | }); |
| 188 | }; |
| 189 | |
| 190 | // Bind array schemas to the caller's existing items. A schema-only path loses |
| 191 | // the index and would cause --file to replace the array with an object. |
| 192 | export const findFileUploadablePaths = ( |
| 193 | schema: JsonSchema | undefined, |
| 194 | basePath: ArgumentPath = [], |
| 195 | value?: unknown |
| 196 | ): ReadonlyArray<ArgumentPath> => { |
| 197 | if (!schema) return []; |
| 198 | |
| 199 | if (schema.file_uploadable === true) { |
| 200 | return [basePath]; |
| 201 | } |
| 202 | |
| 203 | const directPropertyPaths = isSchemaRecord(schema.properties) |
| 204 | ? Object.entries(schema.properties).flatMap(([key, property]) => |
| 205 | isSchemaRecord(property) |
| 206 | ? findFileUploadablePaths( |
| 207 | property, |
| 208 | [...basePath, key], |
| 209 | isSchemaRecord(value) ? value[key] : undefined |
| 210 | ) |
| 211 | : [] |
| 212 | ) |
| 213 | : []; |
| 214 | |
| 215 | const variantPaths = getSchemaVariants(schema) |
| 216 | .filter(variant => matchesDiscriminants(variant, value)) |
| 217 | .flatMap(variant => findFileUploadablePaths(variant, basePath, value)); |
| 218 | |
| 219 | const itemPaths = Array.isArray(value) |
| 220 | ? value.flatMap((item, index) => |
| 221 | findFileUploadablePaths(itemSchemaAt(schema.items, index), [...basePath, index], item) |
| 222 | ) |
| 223 | : []; |
| 224 | |
| 225 | const seen = new Set<string>(); |
| 226 | return [...directPropertyPaths, ...variantPaths, ...itemPaths].filter(pathParts => { |
| 227 | const key = JSON.stringify(pathParts); |
| 228 | if (seen.has(key)) return false; |
| 229 | seen.add(key); |
| 230 | return true; |
| 231 | }); |
| 232 | }; |
| 233 | |
| 234 | // Wording of inputs that take a file on the caller's machine, as the tool |
| 235 | // catalog writes it: "Path to the local file to attach", "Local filesystem path |
| 236 | // to the file to upload", "Path to the file to upload". |
| 237 | const LOCAL_FILE_DESCRIPTION = |
| 238 | /\blocal(?:ly)?[\s-]+(?:file|path|filesystem|file\s*system|disk)\b|\bpath\b[^.]{0,40}\bfile\b[^.]{0,40}\bupload/i; |
| 239 | |
| 240 | const describesLocalFile = (schema: JsonSchema): boolean => |
| 241 | [schema.title, schema.description].some( |
| 242 | text => Predicate.isString(text) && LOCAL_FILE_DESCRIPTION.test(text) |
| 243 | ); |
| 244 | |
| 245 | // A path-shaped value: a separator or an extension, and no URL scheme. Keeps a |
| 246 | // bare word such as "claude_code" from matching a file of that name. |
| 247 | const looksLikeFilePath = (path: Path.Path, value: string): boolean => |
| 248 | !/^[a-z][a-z0-9+.-]*:\/\//i.test(value) && |
| 249 | (value.includes('/') || value.includes('\\') || path.extname(value) !== ''); |
| 250 | |
| 251 | type LocalPathArgument = { |
| 252 | readonly argumentPath: ArgumentPath; |
| 253 | readonly value: string; |
| 254 | }; |
| 255 | |
| 256 | type UploadSite = { |
| 257 | readonly argumentPath: ArgumentPath; |
| 258 | readonly source: string | File; |
| 259 | }; |
| 260 | |
| 261 | /** |
| 262 | * The schema and every `anyOf`/`oneOf`/`allOf` branch under it, at any depth: |
| 263 | * all the schemas that can describe one value. Schemas are parsed JSON, so the |
| 264 | * walk ends, as `findFileUploadablePaths` does on the same schema. |
| 265 | */ |
| 266 | const schemasForValue = (schema: JsonSchema): ReadonlyArray<JsonSchema> => [ |
| 267 | schema, |
| 268 | ...getSchemaVariants(schema).flatMap(schemasForValue), |
| 269 | ]; |
| 270 | |
| 271 | const collectUploadSites = ( |
| 272 | value: unknown, |
| 273 | schema: JsonSchema | undefined, |
| 274 | argumentPath: ArgumentPath |
| 275 | ): ReadonlyArray<UploadSite> => { |
| 276 | if (schema?.file_uploadable === true) { |
| 277 | return Predicate.isString(value) || isFileLike(value) ? [{ argumentPath, source: value }] : []; |
| 278 | } |
| 279 | |
| 280 | const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable); |
| 281 | if (uploadableVariants.length > 0) { |
| 282 | return uploadableVariants.flatMap(variant => collectUploadSites(value, variant, argumentPath)); |
| 283 | } |
| 284 | |
| 285 | const properties = schema?.properties; |
| 286 | if (isSchemaRecord(properties) && Predicate.isObject(value)) { |
| 287 | return Object.entries(value).flatMap(([key, entry]) => |
| 288 | collectUploadSites(entry, isSchemaRecord(properties[key]) ? properties[key] : undefined, [ |
| 289 | ...argumentPath, |
| 290 | key, |
| 291 | ]) |
| 292 | ); |
| 293 | } |
| 294 | |
| 295 | if (schema?.type === 'array' && Array.isArray(value) && schema.items) { |
| 296 | return value.flatMap((item, index) => |
| 297 | collectUploadSites(item, itemSchemaAt(schema.items, index), [...argumentPath, index]) |
| 298 | ); |
| 299 | } |
| 300 | |
| 301 | return []; |
| 302 | }; |
| 303 | |
| 304 | /** |
| 305 | * Every argument `uploadToolInputFiles` uploads, once per location even when |
| 306 | * several branches mark it uploadable. The upload and the local-file guard |
| 307 | * both read this one walk, so the guard exempts exactly what is uploaded. |
| 308 | */ |
| 309 | const findUploadSites = (value: unknown, schema: JsonSchema): ReadonlyArray<UploadSite> => { |
| 310 | const seen = new Set<string>(); |
| 311 | return collectUploadSites(value, schema, []).filter(site => { |
| 312 | const key = JSON.stringify(site.argumentPath); |
| 313 | if (seen.has(key)) return false; |
| 314 | seen.add(key); |
| 315 | return true; |
| 316 | }); |
| 317 | }; |
| 318 | |
| 319 | /** |
| 320 | * A copy of `record` with `value` at `argumentPath`, creating the objects on |
| 321 | * the way. An index into anything but an existing array changes nothing. |
| 322 | */ |
| 323 | export const setArgumentAt = ( |
| 324 | record: Record<string, unknown>, |
| 325 | argumentPath: ArgumentPath, |
| 326 | value: unknown |
| 327 | ): Record<string, unknown> => { |
| 328 | const set = (current: unknown, remaining: ArgumentPath): unknown => { |
| 329 | const [key, ...rest] = remaining; |
| 330 | if (key === undefined) return value; |
| 331 | if (typeof key === 'number') { |
| 332 | if (!Array.isArray(current)) return current; |
| 333 | const copy = [...current]; |
| 334 | copy[key] = set(copy[key], rest); |
| 335 | return copy; |
| 336 | } |
| 337 | const copy = isPlainRecord(current) ? { ...current } : {}; |
| 338 | copy[key] = set(copy[key], rest); |
| 339 | return copy; |
| 340 | }; |
| 341 | const updated = set(record, argumentPath); |
| 342 | return isPlainRecord(updated) ? updated : record; |
| 343 | }; |
| 344 | |
| 345 | const collectLocalPathCandidates = ( |
| 346 | value: unknown, |
| 347 | schemas: ReadonlyArray<JsonSchema>, |
| 348 | argumentPath: ArgumentPath |
| 349 | ): ReadonlyArray<LocalPathArgument> => { |
| 350 | const nodes = schemas.flatMap(schemasForValue); |
| 351 | |
| 352 | if (Predicate.isString(value)) { |
| 353 | return nodes.some(describesLocalFile) ? [{ argumentPath, value }] : []; |
| 354 | } |
| 355 | |
| 356 | if (Array.isArray(value)) { |
| 357 | return value.flatMap((item, index) => |
| 358 | collectLocalPathCandidates( |
| 359 | item, |
| 360 | nodes.flatMap(node => { |
| 361 | const itemSchema = itemSchemaAt(node.items, index); |
| 362 | return itemSchema ? [itemSchema] : []; |
| 363 | }), |
| 364 | [...argumentPath, index] |
| 365 | ) |
| 366 | ); |
| 367 | } |
| 368 | |
| 369 | if (Predicate.isObject(value)) { |
| 370 | return Object.entries(value).flatMap(([key, entry]) => |
| 371 | collectLocalPathCandidates( |
| 372 | entry, |
| 373 | nodes.flatMap(node => { |
| 374 | const property = isSchemaRecord(node.properties) ? node.properties[key] : undefined; |
| 375 | return isSchemaRecord(property) ? [property] : []; |
| 376 | }), |
| 377 | [...argumentPath, key] |
| 378 | ) |
| 379 | ); |
| 380 | } |
| 381 | |
| 382 | return []; |
| 383 | }; |
| 384 | |
| 385 | /** |
| 386 | * The string arguments a schema describes as a local file without marking |
| 387 | * them `file_uploadable`. Composio runs the tool remotely and only uploads |
| 388 | * `file_uploadable` inputs, so such an argument reaches the tool as the text of |
| 389 | * the path, never as the file. Every branch that applies to a value is read |
| 390 | * for the description, and a value that is uploaded is never returned. |
| 391 | */ |
| 392 | export const findLocalPathArguments = ( |
| 393 | value: unknown, |
| 394 | schema: JsonSchema | undefined |
| 395 | ): ReadonlyArray<LocalPathArgument> => { |
| 396 | if (!schema) return []; |
| 397 | const uploaded = new Set( |
| 398 | findUploadSites(value, schema).map(site => JSON.stringify(site.argumentPath)) |
| 399 | ); |
| 400 | return collectLocalPathCandidates(value, [schema], []).filter( |
| 401 | candidate => !uploaded.has(JSON.stringify(candidate.argumentPath)) |
| 402 | ); |
| 403 | }; |
| 404 | |
| 405 | /** |
| 406 | * Fails when an argument the schema describes as a local file names a file |
| 407 | * that exists on this machine but the input is not `file_uploadable`: the tool |
| 408 | * would get the path text instead of the file and still report success |
| 409 | * (issue #4965). A path that does not exist here is left alone, since it may |
| 410 | * name a file on the remote side. |
| 411 | */ |
| 412 | export const rejectLocalFilesWithoutUpload = (params: { |
| 413 | readonly fs: FileSystem.FileSystem; |
| 414 | readonly path: Path.Path; |
| 415 | readonly toolSlug: string; |
| 416 | readonly arguments_: Record<string, unknown>; |
| 417 | readonly inputSchema: JsonSchema; |
| 418 | }) => |
| 419 | Effect.gen(function* () { |
| 420 | const candidates = findLocalPathArguments(params.arguments_, params.inputSchema).filter( |
| 421 | candidate => looksLikeFilePath(params.path, candidate.value) |
| 422 | ); |
| 423 | const localFiles = yield* Effect.filter(candidates, candidate => |
| 424 | params.fs.stat(candidate.value).pipe( |
| 425 | Effect.map(info => info.type === 'File'), |
| 426 | Effect.orElseSucceed(() => false) |
| 427 | ) |
| 428 | ); |
| 429 | if (localFiles.length === 0) return; |
| 430 | |
| 431 | const named = localFiles |
| 432 | .map(({ argumentPath, value }) => `"${argumentPath.join('.')}" (${value})`) |
| 433 | .join(', '); |
| 434 | return yield* new ToolFileUploadError({ |
| 435 | reason: 'not-uploadable', |
| 436 | message: |
| 437 | `${params.toolSlug} cannot upload local files: ${named} names a file on this machine, ` + |
| 438 | 'but the tool does not mark that input as a file upload, so Composio would receive the ' + |
| 439 | 'path text instead of the file content. Nothing was executed. Use a URL input if the ' + |
| 440 | 'tool has one, or report the tool schema to Composio.', |
| 441 | }); |
| 442 | }); |
| 443 | |
| 444 | const readFileFromUrl = (path: Path.Path, url: string) => |
| 445 | Effect.gen(function* () { |
| 446 | const { ssrfSafeFetch } = yield* loadSsrfSafeFetch; |
| 447 | const response = yield* Effect.tryPromise({ |
| 448 | try: signal => ssrfSafeFetch(url, { signal }), |
| 449 | catch: asSourceReadError, |
| 450 | }); |
| 451 | if (!response.ok) { |
| 452 | yield* discardBody(response); |
| 453 | return yield* new ToolFileUploadError({ |
| 454 | message: `Failed to fetch file: ${response.statusText}`, |
| 455 | reason: 'source-fetch', |
| 456 | status: response.status, |
| 457 | }); |
| 458 | } |
| 459 | |
| 460 | // Same cap as the core SDK's URL uploads: a remote server must not be able |
| 461 | // to exhaust memory with an oversized or never-ending body. Copied into a |
| 462 | // fresh ArrayBuffer-backed view for the same reason as readFileFromDisk. |
| 463 | const { readResponseBodyWithLimit } = yield* loadCoreFileUploadHelpers; |
| 464 | const body = yield* Effect.tryPromise({ |
| 465 | try: () => readResponseBodyWithLimit(response), |
| 466 | catch: asSourceReadError, |
| 467 | }); |
| 468 | const bytes = new Uint8Array(body); |
| 469 | const parsedUrl = new URL(url); |
| 470 | const fileName = path.basename(parsedUrl.pathname) || `file-${Date.now()}`; |
| 471 | |
| 472 | return { |
| 473 | bytes, |
| 474 | fileName, |
| 475 | mimeType: response.headers.get('content-type') || 'application/octet-stream', |
| 476 | }; |
| 477 | }); |
| 478 | |
| 479 | const readFileFromDisk = ( |
| 480 | fs: FileSystem.FileSystem, |
| 481 | path: Path.Path, |
| 482 | filePath: string, |
| 483 | stagedFiles: StagedFiles |
| 484 | ) => |
| 485 | Effect.gen(function* () { |
| 486 | // Enforce the sensitive-path denylist at the lowest-level local read, so any |
| 487 | // caller of this reader (not just `uploadToolInputFiles`) is protected. This |
| 488 | // is the single canonical guard shared with `@composio/core`; without it the |
| 489 | // CLI's upload path would silently exfiltrate ~/.ssh/id_rsa, ~/.aws/credentials, |
| 490 | // .env files, etc. (issue #3746 / GHSA-hp3h-89pf-5q58). URLs and File objects |
| 491 | // are intentionally not path-checked, matching the core SDK. |
| 492 | // |
| 493 | // The CLI intentionally exposes NO opt-out for this guard (unlike the core/Python |
| 494 | // SDKs' `sensitiveFileUploadProtection` flag): the primary attack vector is an |
| 495 | // agent that has been prompt-injected into supplying its own tool arguments, so a |
| 496 | // `--force`/env override would hand that attacker a trivial bypass. Pass a |
| 497 | // CLI-appropriate remediation so the error does not advertise an SDK-only opt-out. |
| 498 | const { assertSafeFileUploadPath } = yield* loadCoreFileUploadHelpers; |
| 499 | yield* Effect.try({ |
| 500 | try: () => |
| 501 | assertSafeFileUploadPath(filePath, { |
| 502 | remediation: |
| 503 | 'The Composio CLI always enforces this denylist and has no opt-out. To upload this ' + |
| 504 | 'file, copy it to a location outside sensitive directories (e.g. ~/.ssh, ~/.aws) and ' + |
| 505 | 'pass the copy instead.', |
| 506 | }), |
| 507 | catch: asSourceReadError, |
| 508 | }); |
| 509 | const bytes = yield* fs.readFile(filePath).pipe(Effect.mapError(asSourceReadError)); |
| 510 | // A staged file is uploaded under the name and type its caller declared. A |
| 511 | // local file carries no Content-Type, so otherwise the type is inferred from |
| 512 | // the name's extension. Tools validate it (Canva's import rejects a .pptx |
| 513 | // labelled `application/octet-stream`, #4984). |
| 514 | const staged = stagedFiles.get(filePath); |
| 515 | const stagedName = path.basename(staged?.name ?? ''); |
| 516 | const fileName = stagedName.length > 0 ? stagedName : path.basename(filePath); |
| 517 | return { |
| 518 | // Copy into a fresh ArrayBuffer-backed view: `fetch` bodies reject the |
| 519 | // wider ArrayBufferLike-backed Uint8Array that FileSystem returns. |
| 520 | bytes: new Uint8Array(bytes), |
| 521 | fileName, |
| 522 | mimeType: staged?.mimetype ?? mime.getType(fileName) ?? 'application/octet-stream', |
| 523 | }; |
| 524 | }); |
| 525 | |
| 526 | const readUploadSource = ( |
| 527 | fs: FileSystem.FileSystem, |
| 528 | path: Path.Path, |
| 529 | file: string | File, |
| 530 | stagedFiles: StagedFiles |
| 531 | ) => { |
| 532 | if (isFileLike(file)) { |
| 533 | return Effect.tryPromise({ try: () => file.arrayBuffer(), catch: asSourceReadError }).pipe( |
| 534 | Effect.map(buffer => ({ |
| 535 | bytes: new Uint8Array(buffer), |
| 536 | fileName: file.name || `file-${Date.now()}`, |
| 537 | mimeType: file.type || 'application/octet-stream', |
| 538 | })) |
| 539 | ); |
| 540 | } |
| 541 | |
| 542 | if (typeof file === 'string' && /^https?:\/\//i.test(file)) { |
| 543 | return readFileFromUrl(path, file); |
| 544 | } |
| 545 | |
| 546 | if (typeof file === 'string') { |
| 547 | return readFileFromDisk(fs, path, file, stagedFiles); |
| 548 | } |
| 549 | |
| 550 | return Effect.fail( |
| 551 | new ToolFileUploadError({ |
| 552 | message: 'Unsupported upload source', |
| 553 | reason: 'unsupported-source', |
| 554 | }) |
| 555 | ); |
| 556 | }; |
| 557 | |
| 558 | const uploadFile = (params: { |
| 559 | readonly fs: FileSystem.FileSystem; |
| 560 | readonly path: Path.Path; |
| 561 | readonly file: string | File; |
| 562 | readonly toolSlug: string; |
| 563 | readonly toolkitSlug: string; |
| 564 | readonly client: ComposioClientShape; |
| 565 | readonly stagedFiles: StagedFiles; |
| 566 | }) => |
| 567 | Effect.gen(function* () { |
| 568 | const fileData = yield* readUploadSource( |
| 569 | params.fs, |
| 570 | params.path, |
| 571 | params.file, |
| 572 | params.stagedFiles |
| 573 | ); |
| 574 | // eslint-disable-next-line no-restricted-imports -- MD5 for the presigned-upload checksum is not available in Web Crypto |
| 575 | const { createHash } = yield* Effect.promise(() => import('node:crypto')); |
| 576 | const md5 = createHash('md5').update(fileData.bytes).digest('hex'); |
| 577 | // Issuing an upload URL changes nothing until the upload, so a retry is safe. |
| 578 | const presigned = yield* params.client.files.createPresignedURL( |
| 579 | { |
| 580 | filename: fileData.fileName, |
| 581 | mimetype: fileData.mimeType, |
| 582 | md5, |
| 583 | tool_slug: params.toolSlug, |
| 584 | toolkit_slug: params.toolkitSlug, |
| 585 | }, |
| 586 | idempotent |
| 587 | ); |
| 588 | |
| 589 | const { ssrfSafeFetch } = yield* loadSsrfSafeFetch; |
| 590 | const uploadResponse = yield* Effect.tryPromise({ |
| 591 | try: signal => |
| 592 | ssrfSafeFetch(presigned.new_presigned_url, { |
| 593 | method: 'PUT', |
| 594 | body: fileData.bytes, |
| 595 | headers: { |
| 596 | 'Content-Type': fileData.mimeType, |
| 597 | 'Content-Length': fileData.bytes.byteLength.toString(), |
| 598 | }, |
| 599 | signal, |
| 600 | }), |
| 601 | catch: asSourceReadError, |
| 602 | }); |
| 603 | |
| 604 | yield* discardBody(uploadResponse); |
| 605 | if (!uploadResponse.ok) { |
| 606 | return yield* new ToolFileUploadError({ |
| 607 | message: `Failed to upload file to S3: ${uploadResponse.statusText}`, |
| 608 | reason: 'upload', |
| 609 | status: uploadResponse.status, |
| 610 | }); |
| 611 | } |
| 612 | |
| 613 | return { |
| 614 | name: fileData.fileName, |
| 615 | mimetype: fileData.mimeType, |
| 616 | s3key: presigned.key, |
| 617 | }; |
| 618 | }); |
| 619 | |
| 620 | // Uploads every upload site and puts the uploaded file's reference in place of |
| 621 | // its source. |
| 622 | const hydrateFileUploads = ( |
| 623 | arguments_: Record<string, unknown>, |
| 624 | schema: JsonSchema, |
| 625 | ctx: Omit<Parameters<typeof uploadFile>[0], 'file'> |
| 626 | ): Effect.Effect<Record<string, unknown>, ToolInputUploadError> => |
| 627 | Effect.forEach( |
| 628 | findUploadSites(arguments_, schema), |
| 629 | site => |
| 630 | uploadFile({ ...ctx, file: site.source }).pipe( |
| 631 | Effect.map(uploaded => [site.argumentPath, uploaded] as const) |
| 632 | ), |
| 633 | { concurrency: 'unbounded' } |
| 634 | ).pipe( |
| 635 | Effect.map(uploads => |
| 636 | uploads.reduce( |
| 637 | (args, [argumentPath, uploaded]) => setArgumentAt(args, argumentPath, uploaded), |
| 638 | arguments_ |
| 639 | ) |
| 640 | ) |
| 641 | ); |
| 642 | |
| 643 | export const uploadToolInputFiles = (params: { |
| 644 | readonly fs: FileSystem.FileSystem; |
| 645 | readonly path: Path.Path; |
| 646 | readonly toolSlug: string; |
| 647 | readonly arguments_: Record<string, unknown>; |
| 648 | readonly inputSchema: JsonSchema; |
| 649 | readonly client: ComposioClientShape; |
| 650 | readonly toolkitSlug?: string; |
| 651 | /** Local path -> name and MIME type its caller staged it under. */ |
| 652 | readonly stagedFiles?: StagedFiles; |
| 653 | }): Effect.Effect<Record<string, unknown>, ToolInputUploadError> => |
| 654 | Effect.gen(function* () { |
| 655 | yield* rejectLocalFilesWithoutUpload(params); |
| 656 | |
| 657 | return yield* hydrateFileUploads(params.arguments_, params.inputSchema, { |
| 658 | fs: params.fs, |
| 659 | path: params.path, |
| 660 | toolSlug: params.toolSlug, |
| 661 | toolkitSlug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug) ?? 'unknown', |
| 662 | client: params.client, |
| 663 | stagedFiles: params.stagedFiles ?? new Map(), |
| 664 | }); |
| 665 | }); |