@composio/core 0.13.1 → 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.
- package/README.md +62 -247
- package/dist/BaseProvider-Dc5yKZhk.d.mts +29394 -0
- package/dist/{CustomTool-DLf7JeKt.d.mts → CustomTool-4nVuwLzO.d.mts} +1 -2
- package/dist/{CustomTool-D9qwyMrv.mjs → CustomTool-l-j5HtEf.mjs} +17 -15
- package/dist/FileModifierErrors-B8V8_3VE.mjs +97 -0
- package/dist/{FileModifierErrors-3fSwIWoa.mjs → SsrfErrors-DNJt57GL.mjs} +24 -85
- package/dist/{Telemetry-DhGI_J4G.mjs → Telemetry-CF0rNHu2.mjs} +40 -8
- package/dist/{jsonSchema-CFKdONpP.mjs → cancellation-BbJ-UQ__.mjs} +64 -19
- package/dist/{composio-BHSQwOUz.d.mts → composio-ChU3eD9F.d.mts} +1083 -1061
- package/dist/{customTool.types-9yFqPjdw.d.mts → customTool.types-CX2-LbfI.d.mts} +634 -601
- package/dist/docs/reference/sdk-reference/typescript/index.mdx +1 -22
- package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +2 -0
- package/dist/{errors-DSIlYfl5.mjs → errors-BcEUHZbq.mjs} +75 -74
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/{fileUtils.node-BiO1JQsJ.mjs → fileUtils.node-DOkW4PBg.mjs} +36 -70
- package/dist/index.d.mts +2446 -1563
- package/dist/index.mjs +1415 -1381
- package/dist/models/Files.node.d.mts +2 -11
- package/dist/models/Files.node.mjs +2 -2
- package/dist/models/Files.workerd.d.mts +0 -1
- package/dist/platform/node.d.mts +1 -2
- package/dist/platform/node.mjs +3 -0
- package/dist/platform/workerd.d.mts +1 -2
- package/dist/platform/workerd.mjs +30 -3
- package/dist/sensitiveFileUploadPaths-C43dHP7S.mjs +164 -0
- package/dist/{types-BJLCRj9q.d.mts → types-D5N60gUD.d.mts} +2 -3
- package/dist/{types-DdoCRzLj.d.mts → types-DY1r-kN9.d.mts} +9 -0
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -2
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -2
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -2
- package/dist/utils/modifiers/FileToolModifier.node.mjs +6 -5
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -2
- package/dist/utils/ssrfGuard.node.d.mts +22 -0
- package/dist/utils/ssrfGuard.node.mjs +152 -0
- package/dist/utils/ssrfGuard.workerd.d.mts +9 -0
- package/dist/utils/ssrfGuard.workerd.mjs +17 -0
- package/package.json +20 -15
- package/src/errors/SsrfErrors.ts +48 -0
- package/src/errors/index.ts +3 -0
- package/src/index.ts +10 -0
- package/src/models/CustomTool.ts +1 -3
- package/src/models/ToolRouterSession.ts +38 -16
- package/src/models/ToolRouterSessionFileMount.ts +7 -3
- package/src/models/Tools.ts +32 -2
- package/src/models/Triggers.ts +16 -76
- package/src/platform/node.ts +4 -0
- package/src/platform/types.ts +10 -0
- package/src/platform/workerd.ts +36 -3
- package/src/provider/OpenAIProvider.ts +19 -14
- package/src/telemetry/Telemetry.ts +9 -6
- package/src/telemetry/redact.ts +40 -0
- package/src/types/tool.types.ts +36 -32
- package/src/utils/fileUtils.node.ts +29 -6
- package/src/utils/jsonSchema.ts +58 -0
- package/src/utils/modifiers/FileToolModifier.node.ts +2 -1
- package/src/utils/readResponseBody.ts +63 -0
- package/src/utils/sdk.ts +5 -4
- package/src/utils/{sensitiveFileUploadPaths.node.ts → sensitiveFileUploadPaths.ts} +29 -13
- package/src/utils/ssrfGuard.node.ts +202 -0
- package/src/utils/ssrfGuard.workerd.ts +19 -0
- package/src/utils/toolkitVersion.ts +21 -2
- package/dist/BaseProvider-Brb3o86-.d.mts +0 -29425
- package/dist/CustomTool-NpHpqdnU.d.mts +0 -74
- package/dist/buffer-PcbMMsgm.mjs +0 -33
- package/dist/composio-DfPD7BAi.d.mts +0 -5666
- package/dist/customTool.types-D-6YqFdW.d.mts +0 -2826
- package/dist/types-CCh8qvui.d.mts +0 -12
package/src/types/tool.types.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod/v3';
|
|
2
2
|
import { CustomConnectionDataSchema } from './connectedAccountAuthStates.types';
|
|
3
3
|
import { TransformToolSchemaModifier } from './modifiers.types';
|
|
4
|
+
import { deduplicateJsonSchemaRequiredArrays } from '../utils/jsonSchema';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Toolkit is the collection of tools,
|
|
@@ -86,38 +87,41 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
|
|
|
86
87
|
export type JSONSchemaProperty = z.infer<typeof JSONSchemaPropertySchema>;
|
|
87
88
|
|
|
88
89
|
// Schema for parameters (input/output)
|
|
89
|
-
const ParametersSchema = z.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
.
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
90
|
+
const ParametersSchema = z.preprocess(
|
|
91
|
+
deduplicateJsonSchemaRequiredArrays,
|
|
92
|
+
z.object({
|
|
93
|
+
type: z.literal('object'),
|
|
94
|
+
anyOf: z.array(JSONSchemaPropertySchema).optional(),
|
|
95
|
+
oneOf: z.array(JSONSchemaPropertySchema).optional(),
|
|
96
|
+
allOf: z.array(JSONSchemaPropertySchema).optional(),
|
|
97
|
+
not: JSONSchemaPropertySchema.optional(),
|
|
98
|
+
properties: z.record(z.string(), JSONSchemaPropertySchema),
|
|
99
|
+
required: z.array(z.string()).optional(),
|
|
100
|
+
title: z.string().optional(),
|
|
101
|
+
default: z.any().optional(),
|
|
102
|
+
nullable: z.boolean().optional(),
|
|
103
|
+
description: z.string().optional(),
|
|
104
|
+
additionalProperties: z.boolean().default(false).optional(),
|
|
105
|
+
// Definition blocks targeted by `$ref` pointers. The Composio API ships
|
|
106
|
+
// these at the parameters root (e.g. `data` → `$ref` → `#/$defs/...`), but
|
|
107
|
+
// because `z.object` strips unknown keys they were being dropped on parse —
|
|
108
|
+
// leaving every nested `$ref` dangling and unresolvable downstream
|
|
109
|
+
// (providers, file modifiers). `JSONSchemaPropertySchema` already accepts
|
|
110
|
+
// both keywords; the parameters root must too.
|
|
111
|
+
$defs: z
|
|
112
|
+
.record(
|
|
113
|
+
z.string(),
|
|
114
|
+
z.lazy(() => JSONSchemaPropertySchema)
|
|
115
|
+
)
|
|
116
|
+
.optional(),
|
|
117
|
+
definitions: z
|
|
118
|
+
.record(
|
|
119
|
+
z.string(),
|
|
120
|
+
z.lazy(() => JSONSchemaPropertySchema)
|
|
121
|
+
)
|
|
122
|
+
.optional(),
|
|
123
|
+
})
|
|
124
|
+
);
|
|
121
125
|
|
|
122
126
|
/**
|
|
123
127
|
* Tool is a single action that can be performed by a toolkit.
|
|
@@ -7,8 +7,10 @@ import logger from './logger';
|
|
|
7
7
|
import { getRandomShortId } from './uuid';
|
|
8
8
|
import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';
|
|
9
9
|
import type { FileDownloadData, FileUploadData } from '../types/files.types';
|
|
10
|
-
import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths
|
|
10
|
+
import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';
|
|
11
11
|
import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
|
|
12
|
+
import { ssrfSafeFetch } from './ssrfGuard.node';
|
|
13
|
+
import { readResponseBodyWithLimit } from './readResponseBody';
|
|
12
14
|
|
|
13
15
|
/**
|
|
14
16
|
* Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
|
|
@@ -39,6 +41,25 @@ export type GetFileDataAfterUploadingToS3Options = {
|
|
|
39
41
|
signal?: AbortSignal;
|
|
40
42
|
};
|
|
41
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Checks whether `value` is an absolute http(s) URL rather than a local path.
|
|
46
|
+
*
|
|
47
|
+
* A bare `startsWith('http')` check also matches local paths like
|
|
48
|
+
* `http_export/report.csv` or `httpdocs/.env`, which routes them into the URL
|
|
49
|
+
* fetch branch and skips the allowlist/denylist checks in
|
|
50
|
+
* {@link getFileDataAfterUploadingToS3}. `new URL()` requires a real scheme
|
|
51
|
+
* (`http:` or `https:`) followed by `//`, so relative-looking paths correctly
|
|
52
|
+
* fail to parse and are treated as local.
|
|
53
|
+
*/
|
|
54
|
+
export const isHttpUrl = (value: string): boolean => {
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(value);
|
|
57
|
+
return url.protocol === 'http:' || url.protocol === 'https:';
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
42
63
|
// Helper function to get file extension from MIME type
|
|
43
64
|
const getExtensionFromMimeType = (mimeType: string): string => {
|
|
44
65
|
const mimeToExt: Record<string, string> = {
|
|
@@ -150,12 +171,14 @@ const readFileContentFromURL = async (
|
|
|
150
171
|
path: string,
|
|
151
172
|
signal?: AbortSignal
|
|
152
173
|
): Promise<{ fileName: string; content: string; mimeType: string }> => {
|
|
153
|
-
|
|
174
|
+
// SSRF guard: `path` is user-supplied (and can come from an LLM-produced tool
|
|
175
|
+
// argument), so it must not be allowed to reach internal/private addresses or
|
|
176
|
+
// redirect into them. See ssrfGuard.node.ts.
|
|
177
|
+
const response = await ssrfSafeFetch(path, { signal });
|
|
154
178
|
if (!response.ok) {
|
|
155
179
|
throw new Error(`Failed to fetch file: ${response.statusText}`);
|
|
156
180
|
}
|
|
157
|
-
const
|
|
158
|
-
const content = new Uint8Array(arrayBuffer);
|
|
181
|
+
const content = await readResponseBodyWithLimit(response);
|
|
159
182
|
const mimeType = response.headers.get('content-type') || 'application/octet-stream';
|
|
160
183
|
|
|
161
184
|
// Extract clean filename from URL, removing query parameters
|
|
@@ -248,7 +271,7 @@ const readFile = async (
|
|
|
248
271
|
mimeType: file.type,
|
|
249
272
|
};
|
|
250
273
|
} else if (typeof file === 'string') {
|
|
251
|
-
if (file
|
|
274
|
+
if (isHttpUrl(file)) {
|
|
252
275
|
return await readFileContentFromURL(file, signal);
|
|
253
276
|
} else {
|
|
254
277
|
return await readFileContent(file);
|
|
@@ -273,7 +296,7 @@ export const getFileDataAfterUploadingToS3 = async (
|
|
|
273
296
|
throw new Error('Either path or blob must be provided');
|
|
274
297
|
}
|
|
275
298
|
|
|
276
|
-
const isLocalPath = typeof file === 'string' && !file
|
|
299
|
+
const isLocalPath = typeof file === 'string' && !isHttpUrl(file);
|
|
277
300
|
|
|
278
301
|
if (isLocalPath && fileUploadAllowlist !== undefined) {
|
|
279
302
|
assertPathInsideUploadDirs(file as string, fileUploadAllowlist);
|
package/src/utils/jsonSchema.ts
CHANGED
|
@@ -258,6 +258,64 @@ export function dereferenceJsonSchema<T = unknown>(
|
|
|
258
258
|
return out as T;
|
|
259
259
|
}
|
|
260
260
|
|
|
261
|
+
/**
|
|
262
|
+
* Returns a deep-cloned JSON Schema whose `required` arrays contain each entry
|
|
263
|
+
* at most once. Duplicate entries are invalid in JSON Schema 2020-12 but do
|
|
264
|
+
* not change the schema's meaning, so preserving the first occurrence is safe.
|
|
265
|
+
*
|
|
266
|
+
* Tool schemas originate both from the Composio API and direct provider calls.
|
|
267
|
+
* Keeping this normalization provider-agnostic lets every SDK provider receive
|
|
268
|
+
* canonical API schemas, while providers that further transform a schema can
|
|
269
|
+
* reapply it at their own emission boundary.
|
|
270
|
+
*/
|
|
271
|
+
export function deduplicateJsonSchemaRequiredArrays<T = unknown>(schema: T): T {
|
|
272
|
+
const seenSchemaValues = new WeakMap<object, unknown>();
|
|
273
|
+
const seenInstanceValues = new WeakMap<object, unknown>();
|
|
274
|
+
const instanceValueKeywords = new Set(['const', 'default', 'enum', 'examples']);
|
|
275
|
+
|
|
276
|
+
function walk(value: unknown, isSchema: boolean, depth = 0): unknown {
|
|
277
|
+
if (depth > MAX_NODE_DEPTH) {
|
|
278
|
+
throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const seen = isSchema ? seenSchemaValues : seenInstanceValues;
|
|
282
|
+
|
|
283
|
+
if (Array.isArray(value)) {
|
|
284
|
+
const existing = seen.get(value);
|
|
285
|
+
if (existing) return existing;
|
|
286
|
+
|
|
287
|
+
const clone: unknown[] = [];
|
|
288
|
+
seen.set(value, clone);
|
|
289
|
+
for (const item of value) {
|
|
290
|
+
clone.push(walk(item, isSchema, depth + 1));
|
|
291
|
+
}
|
|
292
|
+
return clone;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (!isPlainObject(value)) return value;
|
|
296
|
+
|
|
297
|
+
const existing = seen.get(value);
|
|
298
|
+
if (existing) return existing;
|
|
299
|
+
|
|
300
|
+
const clone: Record<string, unknown> = {};
|
|
301
|
+
seen.set(value, clone);
|
|
302
|
+
for (const [key, child] of Object.entries(value)) {
|
|
303
|
+
Object.defineProperty(clone, key, {
|
|
304
|
+
configurable: true,
|
|
305
|
+
enumerable: true,
|
|
306
|
+
value:
|
|
307
|
+
isSchema && key === 'required' && Array.isArray(child)
|
|
308
|
+
? [...new Set(walk(child, false, depth + 1) as unknown[])]
|
|
309
|
+
: walk(child, isSchema && !instanceValueKeywords.has(key), depth + 1),
|
|
310
|
+
writable: true,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
return clone;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return walk(schema, true) as T;
|
|
317
|
+
}
|
|
318
|
+
|
|
261
319
|
/**
|
|
262
320
|
* Removes all non-required properties from the schema
|
|
263
321
|
*
|
|
@@ -18,6 +18,7 @@ import type { beforeFileUploadModifier } from '../../types/modifiers.types';
|
|
|
18
18
|
import {
|
|
19
19
|
downloadFileFromS3,
|
|
20
20
|
getFileDataAfterUploadingToS3,
|
|
21
|
+
isHttpUrl,
|
|
21
22
|
type GetFileDataAfterUploadingToS3Options,
|
|
22
23
|
} from '../fileUtils.node';
|
|
23
24
|
import {
|
|
@@ -150,7 +151,7 @@ const hydrateFiles = async (
|
|
|
150
151
|
if (typeof value === 'string') {
|
|
151
152
|
// Match the URL/local-path split used downstream in
|
|
152
153
|
// getFileDataAfterUploadingToS3 so the hook sees the same categorisation.
|
|
153
|
-
const source = value
|
|
154
|
+
const source = isHttpUrl(value) ? 'url' : 'path';
|
|
154
155
|
const pathOrUrl = await runBeforeFileUpload(value, source);
|
|
155
156
|
logger.debug(`Uploading file "${pathOrUrl}"`);
|
|
156
157
|
return getFileDataAfterUploadingToS3(pathOrUrl, {
|
|
@@ -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
|
@@ -4,6 +4,7 @@ import { getEnvsWithPrefix, getEnvVariable } from './env';
|
|
|
4
4
|
import logger from './logger';
|
|
5
5
|
import { ComposioError } from '../errors/ComposioError';
|
|
6
6
|
import { ToolkitVersion, ToolkitVersionParam, ToolkitVersions } from '../types/tool.types';
|
|
7
|
+
import { normalizeToolkitSlug } from './toolkitVersion';
|
|
7
8
|
import { platform } from '#platform';
|
|
8
9
|
|
|
9
10
|
// File path helpers
|
|
@@ -82,16 +83,16 @@ export function getToolkitVersionsFromEnv(
|
|
|
82
83
|
const envPrefixedVersions = getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`);
|
|
83
84
|
const toolkitVersionsFromEnv = Object.entries(envPrefixedVersions).reduce((acc, [key, value]) => {
|
|
84
85
|
const toolkitName = key.replace('COMPOSIO_TOOLKIT_VERSION_', '');
|
|
85
|
-
acc[toolkitName
|
|
86
|
+
acc[normalizeToolkitSlug(toolkitName)] = value as ToolkitVersion;
|
|
86
87
|
return acc;
|
|
87
88
|
}, {} as ToolkitVersions);
|
|
88
89
|
|
|
89
|
-
//
|
|
90
|
-
//
|
|
90
|
+
// normalize keys via normalizeToolkitSlug (the same helper the lookup uses);
|
|
91
|
+
// user provided values act as overrides
|
|
91
92
|
let userProvidedToolkitVersions = {};
|
|
92
93
|
if (defaultVersions && typeof defaultVersions === 'object') {
|
|
93
94
|
userProvidedToolkitVersions = Object.fromEntries(
|
|
94
|
-
Object.entries(defaultVersions).map(([key, value]) => [key
|
|
95
|
+
Object.entries(defaultVersions).map(([key, value]) => [normalizeToolkitSlug(key), value])
|
|
95
96
|
);
|
|
96
97
|
}
|
|
97
98
|
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Blocks accidental upload of local files from well-known secret/credential locations
|
|
3
3
|
* during auto file upload (and {@link getFileDataAfterUploadingToS3}).
|
|
4
|
+
*
|
|
5
|
+
* This is the single canonical guard shared by the core SDK and downstream
|
|
6
|
+
* packages (e.g. `@composio/cli`). Filesystem access goes through the `#platform`
|
|
7
|
+
* abstraction so this module stays free of static `node:*` imports and is safe to
|
|
8
|
+
* re-export from the package root (edge/workerd builds included).
|
|
4
9
|
*/
|
|
5
|
-
import
|
|
6
|
-
import fs from 'node:fs';
|
|
10
|
+
import { platform } from '#platform';
|
|
7
11
|
import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';
|
|
8
12
|
|
|
9
13
|
/**
|
|
@@ -26,15 +30,17 @@ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
|
|
|
26
30
|
/** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
|
|
27
31
|
const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
|
|
28
32
|
|
|
33
|
+
const isWindows = typeof process !== 'undefined' && process.platform === 'win32';
|
|
34
|
+
|
|
29
35
|
/**
|
|
30
36
|
* Returns normalized path segments, resolving symlinks when the path exists.
|
|
31
37
|
*/
|
|
32
38
|
function normalizePathSegments(filePath: string): string[] {
|
|
33
|
-
const absolute =
|
|
39
|
+
const absolute = platform.resolvePath(filePath);
|
|
34
40
|
let resolved = absolute;
|
|
35
41
|
try {
|
|
36
|
-
if (
|
|
37
|
-
resolved =
|
|
42
|
+
if (platform.existsSync(absolute)) {
|
|
43
|
+
resolved = platform.realpathSync(absolute);
|
|
38
44
|
}
|
|
39
45
|
} catch {
|
|
40
46
|
// If realpath fails (e.g. race), use resolved path
|
|
@@ -58,16 +64,15 @@ function getSensitiveFileUploadPathBlockReason(
|
|
|
58
64
|
additionalDenySegments?: string[]
|
|
59
65
|
): string | null {
|
|
60
66
|
const segments = normalizePathSegments(filePath);
|
|
61
|
-
const isWin = process.platform === 'win32';
|
|
62
67
|
const deny = new Set(
|
|
63
68
|
[
|
|
64
69
|
...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
|
|
65
70
|
...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),
|
|
66
|
-
].map(s => (
|
|
71
|
+
].map(s => (isWindows ? s.toLowerCase() : s))
|
|
67
72
|
);
|
|
68
73
|
|
|
69
74
|
// Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.
|
|
70
|
-
const segmentsForMatch =
|
|
75
|
+
const segmentsForMatch = isWindows ? segments.map(s => s.toLowerCase()) : segments;
|
|
71
76
|
for (let i = 0; i < segments.length; i++) {
|
|
72
77
|
if (deny.has(segmentsForMatch[i]!)) {
|
|
73
78
|
return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
|
|
@@ -86,20 +91,31 @@ function getSensitiveFileUploadPathBlockReason(
|
|
|
86
91
|
return null;
|
|
87
92
|
}
|
|
88
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Default remediation hint appended to the block message. Assumes an SDK caller
|
|
96
|
+
* that exposes `sensitiveFileUploadProtection`. Callers without such an opt-out
|
|
97
|
+
* (e.g. `@composio/cli`) should pass their own `remediation` so the message does
|
|
98
|
+
* not advertise an option the caller cannot honor.
|
|
99
|
+
*/
|
|
100
|
+
const DEFAULT_REMEDIATION =
|
|
101
|
+
`To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` +
|
|
102
|
+
`(not recommended) or use a copy outside sensitive locations.`;
|
|
103
|
+
|
|
89
104
|
/**
|
|
90
105
|
* @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
|
|
91
106
|
*/
|
|
92
107
|
export function assertSafeFileUploadPath(
|
|
93
108
|
filePath: string,
|
|
94
|
-
options?: { additionalDenySegments?: string[] }
|
|
109
|
+
options?: { additionalDenySegments?: string[]; remediation?: string }
|
|
95
110
|
): void {
|
|
96
111
|
const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
|
|
97
112
|
if (reason) {
|
|
113
|
+
const remediation = options?.remediation ?? DEFAULT_REMEDIATION;
|
|
98
114
|
throw new ComposioSensitiveFilePathBlockedError(
|
|
99
|
-
`Refusing to upload: ${reason}.
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
115
|
+
`Refusing to upload: ${reason}. ${remediation}`,
|
|
116
|
+
{
|
|
117
|
+
meta: { filePath, reason },
|
|
118
|
+
}
|
|
103
119
|
);
|
|
104
120
|
}
|
|
105
121
|
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
|
|
2
|
+
import { isIP } from 'node:net';
|
|
3
|
+
import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* SSRF guard for user-supplied URL file inputs.
|
|
7
|
+
*
|
|
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
|
+
*
|
|
15
|
+
* This module validates the *resolved* address (not just the hostname string,
|
|
16
|
+
* which defeats decimal/octal/hex IP obfuscation) before every fetch, and
|
|
17
|
+
* follows redirects manually so each hop is re-validated.
|
|
18
|
+
*
|
|
19
|
+
* Known residual: a DNS name could resolve to a public address here and rebind
|
|
20
|
+
* to an internal one before the underlying `fetch` connects (a TOCTOU / DNS
|
|
21
|
+
* rebinding window). Closing that fully requires pinning the validated IP at
|
|
22
|
+
* connect time (a custom dispatcher), which is out of scope for this guard.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const MAX_REDIRECTS = 5;
|
|
26
|
+
|
|
27
|
+
const ipv4ToLong = (ip: string): number => {
|
|
28
|
+
const [a, b, c, d] = ip.split('.').map(Number);
|
|
29
|
+
return (((a << 24) >>> 0) | (b << 16) | (c << 8) | d) >>> 0;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// Address blocks that must never be reachable from a user-supplied URL.
|
|
33
|
+
// (RFC1918 private, loopback, link-local, CGNAT, TEST-NET, benchmarking,
|
|
34
|
+
// multicast, and reserved ranges.)
|
|
35
|
+
const IPV4_BLOCKED_CIDRS: ReadonlyArray<readonly [string, number]> = [
|
|
36
|
+
['0.0.0.0', 8], // "this" network / unspecified
|
|
37
|
+
['10.0.0.0', 8], // private
|
|
38
|
+
['100.64.0.0', 10], // carrier-grade NAT
|
|
39
|
+
['127.0.0.0', 8], // loopback
|
|
40
|
+
['169.254.0.0', 16], // link-local (incl. cloud metadata 169.254.169.254)
|
|
41
|
+
['172.16.0.0', 12], // private
|
|
42
|
+
['192.0.0.0', 24], // IETF protocol assignments
|
|
43
|
+
['192.0.2.0', 24], // TEST-NET-1
|
|
44
|
+
['192.168.0.0', 16], // private
|
|
45
|
+
['198.18.0.0', 15], // benchmarking
|
|
46
|
+
['198.51.100.0', 24], // TEST-NET-2
|
|
47
|
+
['203.0.113.0', 24], // TEST-NET-3
|
|
48
|
+
['224.0.0.0', 4], // multicast
|
|
49
|
+
['240.0.0.0', 4], // reserved (incl. 255.255.255.255 broadcast)
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
const isBlockedIpv4Long = (long: number): boolean =>
|
|
53
|
+
IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
|
|
54
|
+
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
|
55
|
+
return (long & mask) === (ipv4ToLong(base) & mask);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Expand an IPv6 string into its 8 16-bit groups, converting any trailing
|
|
60
|
+
* dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
|
|
61
|
+
* the input cannot be parsed.
|
|
62
|
+
*/
|
|
63
|
+
const expandIpv6 = (ip: string): number[] | null => {
|
|
64
|
+
let addr = ip;
|
|
65
|
+
const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
|
|
66
|
+
if (v4Match) {
|
|
67
|
+
const long = ipv4ToLong(v4Match[2]);
|
|
68
|
+
addr = `${v4Match[1]}${((long >>> 16) & 0xffff).toString(16)}:${(long & 0xffff).toString(16)}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const halves = addr.split('::');
|
|
72
|
+
if (halves.length > 2) return null;
|
|
73
|
+
|
|
74
|
+
const head = halves[0] ? halves[0].split(':') : [];
|
|
75
|
+
const tail = halves.length === 2 ? (halves[1] ? halves[1].split(':') : []) : [];
|
|
76
|
+
|
|
77
|
+
let groups: string[];
|
|
78
|
+
if (halves.length === 2) {
|
|
79
|
+
const missing = 8 - head.length - tail.length;
|
|
80
|
+
if (missing < 0) return null;
|
|
81
|
+
groups = [...head, ...Array(missing).fill('0'), ...tail];
|
|
82
|
+
} else {
|
|
83
|
+
groups = head;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (groups.length !== 8) return null;
|
|
87
|
+
return groups.map(g => parseInt(g || '0', 16));
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const isBlockedIpv6 = (ip: string): boolean => {
|
|
91
|
+
const h = expandIpv6(ip);
|
|
92
|
+
if (!h) return true; // fail closed on anything we cannot parse
|
|
93
|
+
|
|
94
|
+
// :: (unspecified) and ::1 (loopback)
|
|
95
|
+
if (h.every(x => x === 0)) return true;
|
|
96
|
+
if (h.slice(0, 7).every(x => x === 0) && h[7] === 1) return true;
|
|
97
|
+
|
|
98
|
+
// Addresses that embed an IPv4 address in their low 32 bits must be validated
|
|
99
|
+
// against the IPv4 blocklist, otherwise `::127.0.0.1` / `::169.254.169.254`
|
|
100
|
+
// (and mapped/NAT64 forms) would pass as "public" IPv6 and reach internal
|
|
101
|
+
// targets. Covers:
|
|
102
|
+
// - IPv4-mapped ::ffff:0:0/96 (h[5] === 0xffff)
|
|
103
|
+
// - IPv4-compatible ::/96 (deprecated, h[5] === 0) — incl. ::a.b.c.d
|
|
104
|
+
// - NAT64 64:ff9b::/96
|
|
105
|
+
const highBitsZero = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
|
|
106
|
+
const isMappedOrCompat = highBitsZero && (h[5] === 0xffff || h[5] === 0);
|
|
107
|
+
const isNat64 =
|
|
108
|
+
h[0] === 0x0064 && h[1] === 0xff9b && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
|
|
109
|
+
if (isMappedOrCompat || isNat64) {
|
|
110
|
+
return isBlockedIpv4Long((((h[6] << 16) >>> 0) | h[7]) >>> 0);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
|
|
114
|
+
if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
|
|
115
|
+
if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8
|
|
116
|
+
|
|
117
|
+
return false;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* True when `ip` is a private, loopback, link-local, or otherwise
|
|
122
|
+
* non-publicly-routable address. Fails closed (returns `true`) for anything that
|
|
123
|
+
* is not a valid IPv4/IPv6 literal.
|
|
124
|
+
*/
|
|
125
|
+
export const isBlockedIp = (ip: string): boolean => {
|
|
126
|
+
const family = isIP(ip);
|
|
127
|
+
if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
|
|
128
|
+
if (family === 6) return isBlockedIpv6(ip);
|
|
129
|
+
return true;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Validate a single URL: it must be http(s), its host must resolve, and every
|
|
134
|
+
* resolved address must be publicly routable. Throws
|
|
135
|
+
* {@link ComposioBlockedInternalUrlError} otherwise.
|
|
136
|
+
*/
|
|
137
|
+
export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
138
|
+
let url: URL;
|
|
139
|
+
try {
|
|
140
|
+
url = new URL(rawUrl);
|
|
141
|
+
} catch {
|
|
142
|
+
throw new ComposioBlockedInternalUrlError('Refusing to fetch a malformed URL', { url: rawUrl });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
146
|
+
throw new ComposioBlockedInternalUrlError(
|
|
147
|
+
`Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`,
|
|
148
|
+
{ url: rawUrl }
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
153
|
+
|
|
154
|
+
let resolved: Array<{ address: string }>;
|
|
155
|
+
try {
|
|
156
|
+
resolved = await lookup(host, { all: true, verbatim: true });
|
|
157
|
+
} catch {
|
|
158
|
+
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
for (const { address } of resolved) {
|
|
162
|
+
if (isBlockedIp(address)) {
|
|
163
|
+
throw new ComposioBlockedInternalUrlError(
|
|
164
|
+
`Refusing to fetch "${host}" — it resolves to a private, loopback, or link-local address`,
|
|
165
|
+
{ url: rawUrl, resolvedIp: address }
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
|
|
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.
|
|
176
|
+
*/
|
|
177
|
+
export const ssrfSafeFetch = async (
|
|
178
|
+
rawUrl: string,
|
|
179
|
+
init: RequestInit = {},
|
|
180
|
+
maxRedirects: number = MAX_REDIRECTS
|
|
181
|
+
): Promise<Response> => {
|
|
182
|
+
let currentUrl = rawUrl;
|
|
183
|
+
|
|
184
|
+
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
185
|
+
await assertSafeFetchTarget(currentUrl);
|
|
186
|
+
|
|
187
|
+
const response = await fetch(currentUrl, { ...init, redirect: 'manual' });
|
|
188
|
+
|
|
189
|
+
const isRedirect =
|
|
190
|
+
response.status >= 300 && response.status < 400 && response.headers.has('location');
|
|
191
|
+
if (!isRedirect) {
|
|
192
|
+
return response;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
throw new ComposioBlockedInternalUrlError(
|
|
199
|
+
`Refusing to fetch: too many redirects (max ${maxRedirects})`,
|
|
200
|
+
{ url: rawUrl }
|
|
201
|
+
);
|
|
202
|
+
};
|
|
@@ -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
|
+
};
|