@composio/core 0.17.0 → 1.0.0-beta.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.
- package/dist/{CustomTool-Uip-fhPw.d.mts → CustomTool-CwpeQhz2.d.mts} +1 -1
- package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
- package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-DK1uAWnD.mjs} +1 -1
- package/dist/{cancellation-NVtGf3St.mjs → cancellation-C-qy8rcj.mjs} +1 -1
- package/dist/{composio-B27X6i6A.d.mts → composio-XjF7EMEe.d.mts} +256 -250
- package/dist/{customTool.types-B2Ava_j5.d.mts → customTool.types-DpJbYY5m.d.mts} +167 -167
- package/dist/experimental/index.d.mts +2 -2
- package/dist/{fileUtils.node-B1Wn848p.mjs → fileUtils.node-BwpUOF0s.mjs} +2 -2
- package/dist/index.d.mts +6 -5
- package/dist/index.mjs +58 -24
- package/dist/models/Files.node.mjs +2 -2
- package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-B0w8dqpv.mjs} +23 -6
- package/dist/ssrfGuard.node-DlxO8uzr.mjs +307 -0
- package/dist/{types-DdZJuMm2.d.mts → types-C9kJAurw.d.mts} +2 -2
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.mjs +56 -100
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
- package/dist/utils/ssrfGuard.node.d.mts +14 -5
- package/dist/utils/ssrfGuard.node.mjs +1 -161
- package/package.json +7 -3
- package/src/models/ToolRouterSession.ts +36 -8
- package/src/models/Tools.ts +102 -39
- package/src/utils/modifiers/FileToolModifier.node.ts +85 -181
- package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +199 -0
- package/src/utils/pinnedDispatcher.node.ts +118 -0
- package/src/utils/sensitiveFileUploadPaths.ts +36 -9
- package/src/utils/ssrfGuard.node.ts +89 -11
- package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
|
@@ -116,6 +116,20 @@ export const schemaHasFileProperty = (
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
// Check `$ref` targets. Composio toolkits routinely express file flags
|
|
120
|
+
// through a `$ref`/`$defs` indirection (e.g. GMAIL_GET_ATTACHMENT), and
|
|
121
|
+
// this predicate is the cheap gate that decides whether a schema is worth
|
|
122
|
+
// dereferencing at all — without this it answers `false` for every
|
|
123
|
+
// ref-based schema. Callers walk the *dereferenced* schema, where
|
|
124
|
+
// `dereferenceJsonSchema` has already stripped these blocks, so an unused
|
|
125
|
+
// `$defs` entry can only cost a redundant walk, never a wrong upload.
|
|
126
|
+
for (const definitions of [schema.$defs, schema.definitions]) {
|
|
127
|
+
if (!definitions) continue;
|
|
128
|
+
for (const definition of Object.values(definitions)) {
|
|
129
|
+
if (schemaHasFileProperty(definition, property)) return true;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
119
133
|
return false;
|
|
120
134
|
};
|
|
121
135
|
|
|
@@ -132,3 +146,188 @@ export const schemaHasFileUploadable = (schema: JSONSchemaProperty | undefined):
|
|
|
132
146
|
export const schemaHasFileDownloadable = (schema: JSONSchemaProperty | undefined): boolean => {
|
|
133
147
|
return schemaHasFileProperty(schema, 'file_downloadable');
|
|
134
148
|
};
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Sentinel a leaf handler returns to have {@link walkFileUploadableLeaves}
|
|
152
|
+
* omit that key/item from its parent container. `''` and `null` are legal
|
|
153
|
+
* payload values, so neither can double as "remove this".
|
|
154
|
+
*/
|
|
155
|
+
export const DELETE_VALUE: unique symbol = Symbol('composio.delete-value');
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* `''` at a `file_uploadable` leaf means "no file": it is never a staged
|
|
159
|
+
* `{ name, mimetype, s3key }` descriptor, so the backend rejects it with a
|
|
160
|
+
* validation error, while callers (and the playground UI) mean "absent". The
|
|
161
|
+
* walker omits the key instead. `null` is left alone — schemas with a `null`
|
|
162
|
+
* variant accept it, and the backend reports the mismatch otherwise.
|
|
163
|
+
*/
|
|
164
|
+
export const isEmptyFileValue = (value: unknown): boolean => value === '';
|
|
165
|
+
|
|
166
|
+
export const getSchemaVariants = (schema: JSONSchemaProperty | undefined): JSONSchemaProperty[] => [
|
|
167
|
+
...(schema?.anyOf ?? []),
|
|
168
|
+
...(schema?.oneOf ?? []),
|
|
169
|
+
...(schema?.allOf ?? []),
|
|
170
|
+
];
|
|
171
|
+
|
|
172
|
+
/** Best-effort runtime shape match for selecting composed schema variants. */
|
|
173
|
+
export const jsonSchemaTypeMatchesValue = (schema: JSONSchemaProperty, value: unknown): boolean => {
|
|
174
|
+
const schemaType = schema.type;
|
|
175
|
+
|
|
176
|
+
if (Array.isArray(schemaType)) {
|
|
177
|
+
return schemaType.some(type => jsonSchemaTypeMatchesValue({ ...schema, type }, value));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (schemaType === undefined) {
|
|
181
|
+
if (schema.properties) return isPlainObject(value);
|
|
182
|
+
if (schema.items) return Array.isArray(value);
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
switch (schemaType) {
|
|
187
|
+
case 'array':
|
|
188
|
+
return Array.isArray(value);
|
|
189
|
+
case 'object':
|
|
190
|
+
return isPlainObject(value);
|
|
191
|
+
case 'string':
|
|
192
|
+
return typeof value === 'string';
|
|
193
|
+
case 'integer':
|
|
194
|
+
return Number.isInteger(value);
|
|
195
|
+
case 'number':
|
|
196
|
+
return typeof value === 'number';
|
|
197
|
+
case 'boolean':
|
|
198
|
+
return typeof value === 'boolean';
|
|
199
|
+
case 'null':
|
|
200
|
+
return value === null;
|
|
201
|
+
default:
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/** Mirrors the array-shape inference used by {@link jsonSchemaTypeMatchesValue}. */
|
|
207
|
+
const isArrayShapedSchema = (schema: JSONSchemaProperty | undefined): boolean => {
|
|
208
|
+
if (!schema) return false;
|
|
209
|
+
if (Array.isArray(schema.type)) return schema.type.includes('array');
|
|
210
|
+
return schema.type === 'array' || (schema.type === undefined && schema.items !== undefined);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/** Mirrors the object-shape inference used by {@link jsonSchemaTypeMatchesValue}. */
|
|
214
|
+
const isObjectShapedSchema = (schema: JSONSchemaProperty | undefined): boolean => {
|
|
215
|
+
if (!schema) return false;
|
|
216
|
+
if (Array.isArray(schema.type)) return schema.type.includes('object');
|
|
217
|
+
return schema.type === 'object' || (schema.type === undefined && schema.properties !== undefined);
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Picks the file-bearing `anyOf`/`oneOf`/`allOf` variant whose JSON Schema
|
|
222
|
+
* shape matches the runtime value, falling back to the first file-bearing
|
|
223
|
+
* variant to preserve historical behavior.
|
|
224
|
+
*/
|
|
225
|
+
export const findSchemaVariantWithFileProperty = (
|
|
226
|
+
schema: JSONSchemaProperty | undefined,
|
|
227
|
+
property: 'file_uploadable' | 'file_downloadable',
|
|
228
|
+
value: unknown
|
|
229
|
+
): JSONSchemaProperty | undefined => {
|
|
230
|
+
const candidates = getSchemaVariants(schema).filter(variant =>
|
|
231
|
+
schemaHasFileProperty(variant, property)
|
|
232
|
+
);
|
|
233
|
+
|
|
234
|
+
return (
|
|
235
|
+
candidates.find(candidate => jsonSchemaTypeMatchesValue(candidate, value)) ?? candidates[0]
|
|
236
|
+
);
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Recursively walks a runtime value alongside its (already dereferenced)
|
|
241
|
+
* JSON-Schema node and passes every value sitting at a `file_uploadable`
|
|
242
|
+
* node through `leaf`. A leaf returning {@link DELETE_VALUE} is omitted from
|
|
243
|
+
* its parent object/array. Returns a **new** value; nothing is mutated.
|
|
244
|
+
*
|
|
245
|
+
* Composed schemas are resolved to the single file-bearing variant whose
|
|
246
|
+
* shape matches the value: with `oneOf`, exactly one variant should apply at
|
|
247
|
+
* runtime, and applying several would stage the same file once per variant.
|
|
248
|
+
*/
|
|
249
|
+
export const walkFileUploadableLeaves = async (
|
|
250
|
+
value: unknown,
|
|
251
|
+
schema: JSONSchemaProperty | undefined,
|
|
252
|
+
leaf: (value: unknown) => Promise<unknown>
|
|
253
|
+
): Promise<unknown> => {
|
|
254
|
+
if (schema?.file_uploadable) {
|
|
255
|
+
return leaf(value);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const uploadableVariant = findSchemaVariantWithFileProperty(schema, 'file_uploadable', value);
|
|
259
|
+
if (uploadableVariant) {
|
|
260
|
+
// A scalar empty string cannot match an array-only file input, but callers
|
|
261
|
+
// use it to mean "no files". Route it through the leaf handler so it is
|
|
262
|
+
// omitted, unless another non-file variant explicitly accepts strings.
|
|
263
|
+
const matchingNonFileVariant = getSchemaVariants(schema).some(
|
|
264
|
+
variant =>
|
|
265
|
+
!schemaHasFileProperty(variant, 'file_uploadable') &&
|
|
266
|
+
jsonSchemaTypeMatchesValue(variant, value)
|
|
267
|
+
);
|
|
268
|
+
if (
|
|
269
|
+
isEmptyFileValue(value) &&
|
|
270
|
+
isArrayShapedSchema(uploadableVariant) &&
|
|
271
|
+
!matchingNonFileVariant
|
|
272
|
+
) {
|
|
273
|
+
return leaf(value);
|
|
274
|
+
}
|
|
275
|
+
return walkFileUploadableLeaves(value, uploadableVariant, leaf);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (
|
|
279
|
+
isEmptyFileValue(value) &&
|
|
280
|
+
isArrayShapedSchema(schema) &&
|
|
281
|
+
schemaHasFileProperty(schema, 'file_uploadable')
|
|
282
|
+
) {
|
|
283
|
+
return leaf(value);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (isObjectShapedSchema(schema) && schema?.properties && isPlainObject(value)) {
|
|
287
|
+
const transformed: Record<string, unknown> = {};
|
|
288
|
+
for (const [k, v] of Object.entries(value)) {
|
|
289
|
+
const propertySchema = Object.hasOwn(schema.properties, k) ? schema.properties[k] : undefined;
|
|
290
|
+
const walked = await walkFileUploadableLeaves(v, propertySchema, leaf);
|
|
291
|
+
if (walked !== DELETE_VALUE) {
|
|
292
|
+
// Define every key as an own data property so reserved JSON keys such
|
|
293
|
+
// as `__proto__` remain enumerable without invoking its inherited
|
|
294
|
+
// setter and changing this ordinary object's prototype.
|
|
295
|
+
Object.defineProperty(transformed, k, {
|
|
296
|
+
configurable: true,
|
|
297
|
+
enumerable: true,
|
|
298
|
+
value: walked,
|
|
299
|
+
writable: true,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return transformed;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (isArrayShapedSchema(schema) && schema?.items && Array.isArray(value)) {
|
|
307
|
+
// `items` can be a single schema or an array of schemas; we handle both.
|
|
308
|
+
const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;
|
|
309
|
+
const walked = await Promise.all(
|
|
310
|
+
value.map(item => walkFileUploadableLeaves(item, itemSchema as JSONSchemaProperty, leaf))
|
|
311
|
+
);
|
|
312
|
+
return walked.filter(item => item !== DELETE_VALUE);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
return value;
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Omits `''` at `file_uploadable` leaves of `args` without uploading
|
|
320
|
+
* anything. This is the schema-aware half of the upload modifier that needs
|
|
321
|
+
* no filesystem access, so it also runs when automatic upload is disabled:
|
|
322
|
+
* an empty file value is never a valid staged descriptor and the backend
|
|
323
|
+
* would reject it (https://github.com/ComposioHQ/composio/issues/4233).
|
|
324
|
+
* Any other value — a local path, a staged descriptor, a list — is
|
|
325
|
+
* forwarded untouched.
|
|
326
|
+
*/
|
|
327
|
+
export const dropEmptyFileUploads = (
|
|
328
|
+
args: Record<string, unknown>,
|
|
329
|
+
schema: JSONSchemaProperty | undefined
|
|
330
|
+
): Promise<unknown> =>
|
|
331
|
+
walkFileUploadableLeaves(args, schema, async value =>
|
|
332
|
+
isEmptyFileValue(value) ? DELETE_VALUE : value
|
|
333
|
+
);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
import type { Agent } from 'undici';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The `globalThis` symbols that hold the process-wide dispatcher `fetch` falls
|
|
6
|
+
* back to. Every undici in the process shares them — including the one inside
|
|
7
|
+
* the Node runtime — and `setGlobalDispatcher` writes both, so reading them
|
|
8
|
+
* directly sees the same dispatcher the runtime's own `fetch` would use.
|
|
9
|
+
*
|
|
10
|
+
* Read rather than imported: importing `undici` installs a dispatcher of its
|
|
11
|
+
* own as an import side effect (see {@link loadUndici}), which is exactly what
|
|
12
|
+
* this module must not do at load time.
|
|
13
|
+
*/
|
|
14
|
+
const GLOBAL_DISPATCHER_SYMBOLS = [
|
|
15
|
+
Symbol.for('undici.globalDispatcher.1'),
|
|
16
|
+
Symbol.for('undici.globalDispatcher.2'),
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `undici`, imported on first use rather than at module load.
|
|
21
|
+
*
|
|
22
|
+
* Importing it runs `if (getGlobalDispatcher() === undefined) setGlobalDispatcher(new Agent())`
|
|
23
|
+
* as a side effect, which would hand every unrelated `fetch` in the host
|
|
24
|
+
* application this package's undici instead of the runtime's own — a global
|
|
25
|
+
* change no caller asked for by importing `@composio/core`. Deferring the
|
|
26
|
+
* import to the first pinned request keeps that side effect on the code path
|
|
27
|
+
* that actually needs undici, and behind the `hasCustomGlobalDispatcher` check
|
|
28
|
+
* that reads the slot's true, pre-import state.
|
|
29
|
+
*
|
|
30
|
+
* A process that does make a pinned request still ends up on this package's
|
|
31
|
+
* `Agent` if nothing had claimed the slot yet. That much is not reversible:
|
|
32
|
+
* undici defines the slot non-configurable and writable, so it cannot be
|
|
33
|
+
* cleared back to empty — assigning `undefined` leaves the runtime's own
|
|
34
|
+
* `fetch` asserting on a missing dispatcher.
|
|
35
|
+
*/
|
|
36
|
+
let undici: Promise<typeof import('undici')> | undefined;
|
|
37
|
+
const loadUndici = (): Promise<typeof import('undici')> => (undici ??= import('undici'));
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A `fetch` dispatcher that connects to `addresses` instead of resolving the
|
|
41
|
+
* hostname again.
|
|
42
|
+
*
|
|
43
|
+
* The SSRF guard resolves a hostname to decide whether a URL is safe to fetch.
|
|
44
|
+
* `fetch` would then resolve that hostname a second time when it opens the
|
|
45
|
+
* socket, and the two answers need not match: a short-TTL record can answer
|
|
46
|
+
* with a public address for the check and an internal one for the connect
|
|
47
|
+
* (DNS rebinding). Pinning the connect to the address that was validated
|
|
48
|
+
* removes the second lookup, so there is nothing left to rebind.
|
|
49
|
+
*
|
|
50
|
+
* Only the connect target is replaced. The request still carries the original
|
|
51
|
+
* hostname in `Host` and offers it as TLS SNI, so certificate verification is
|
|
52
|
+
* unchanged — connecting by IP with the IP as SNI would fail against every
|
|
53
|
+
* origin whose certificate names a hostname.
|
|
54
|
+
*
|
|
55
|
+
* The dispatcher is handed to the runtime's own `fetch`, so callers that stub
|
|
56
|
+
* `globalThis.fetch` keep working. That does tie the `undici` major to the one
|
|
57
|
+
* Node's `fetch` speaks — undici 8 dispatchers are rejected by the Node
|
|
58
|
+
* versions this package supports — which is why the dependency is pinned to
|
|
59
|
+
* `^7`, and why `pinnedDispatcher.node.test.ts` exercises a real socket on
|
|
60
|
+
* every Node version in CI rather than mocking the transport.
|
|
61
|
+
*/
|
|
62
|
+
export const createPinnedDispatcher = async (addresses: ReadonlyArray<string>): Promise<Agent> => {
|
|
63
|
+
const { Agent } = await loadUndici();
|
|
64
|
+
|
|
65
|
+
return new Agent({
|
|
66
|
+
connect: {
|
|
67
|
+
lookup: (_hostname, options, callback) => {
|
|
68
|
+
// Node calls a lookup in one of two shapes and picks between them at
|
|
69
|
+
// connect time: `(err, addresses)` when it is doing Happy Eyeballs,
|
|
70
|
+
// and `(err, address, family)` otherwise — when `autoSelectFamily` is
|
|
71
|
+
// off, or a `family`/`localAddress` was requested. Answering in the
|
|
72
|
+
// wrong shape is rejected as an invalid address, which would fail
|
|
73
|
+
// every pinned fetch in such a process.
|
|
74
|
+
if (options.all) {
|
|
75
|
+
// All of them, in resolver order: handing over a single address of a
|
|
76
|
+
// dual-stack host would strand callers whose network cannot reach
|
|
77
|
+
// that family, where the runtime would otherwise have fallen back.
|
|
78
|
+
callback(
|
|
79
|
+
null,
|
|
80
|
+
addresses.map(address => ({ address, family: isIP(address) }))
|
|
81
|
+
);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const [address] = addresses;
|
|
86
|
+
callback(null, address, isIP(address));
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Whether the process-wide dispatcher `fetch` falls back to (when a request
|
|
94
|
+
* carries no `dispatcher` of its own) is something other than a stock `Agent`.
|
|
95
|
+
*
|
|
96
|
+
* A `ProxyAgent`, `EnvHttpProxyAgent`, or custom dispatcher installed through
|
|
97
|
+
* `setGlobalDispatcher` is visible here, and pinning stands down for it: the
|
|
98
|
+
* connect would dial the validated origin instead of that route's next hop.
|
|
99
|
+
*
|
|
100
|
+
* Nothing installed yet is *not* custom. The dispatcher slot is empty until
|
|
101
|
+
* either the runtime's `fetch` or an undici import fills it, so an absent
|
|
102
|
+
* dispatcher means no caller has configured a route — treating it as custom
|
|
103
|
+
* would disable pinning for every process that had not yet made a request.
|
|
104
|
+
*
|
|
105
|
+
* Stock-ness is compared by constructor *name*, deliberately not with
|
|
106
|
+
* `instanceof Agent`: an `Agent` created by the runtime's internal undici is a
|
|
107
|
+
* different class from this package's `Agent`, so once the runtime's own
|
|
108
|
+
* `fetch` has initialized its default dispatcher, an `instanceof` check would
|
|
109
|
+
* report a stock setup as custom and silently disable pinning.
|
|
110
|
+
*/
|
|
111
|
+
export const hasCustomGlobalDispatcher = (): boolean => {
|
|
112
|
+
const slots = globalThis as unknown as Record<symbol, { constructor?: { name?: string } }>;
|
|
113
|
+
const dispatcher = GLOBAL_DISPATCHER_SYMBOLS.map(symbol => slots[symbol]).find(
|
|
114
|
+
installed => installed !== undefined
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
return dispatcher !== undefined && dispatcher.constructor?.name !== 'Agent';
|
|
118
|
+
};
|
|
@@ -31,10 +31,29 @@ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
|
|
|
31
31
|
/** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
|
|
32
32
|
const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
|
|
33
33
|
|
|
34
|
+
const splitSegments = (aPath: string): string[] => aPath.split(/[/\\]+/).filter(Boolean);
|
|
35
|
+
|
|
34
36
|
/**
|
|
35
37
|
* Returns normalized path segments, resolving symlinks when the path exists.
|
|
38
|
+
*
|
|
39
|
+
* Both the written path and the symlink-resolved one are returned, because a
|
|
40
|
+
* denied segment can be hidden by a symlink in either direction:
|
|
41
|
+
*
|
|
42
|
+
* - `~/innocent-name` -> `~/nested/.aws/creds` hides `.aws` from the written
|
|
43
|
+
* path, so the denylist has to see the resolved one.
|
|
44
|
+
* - `~/.claude` -> `/state/claude` hides `.claude` from the *resolved* path,
|
|
45
|
+
* so the denylist also has to see the written one. Dotfile managers
|
|
46
|
+
* (chezmoi, stow, yadm) and containerised home directories produce exactly
|
|
47
|
+
* this layout.
|
|
48
|
+
*
|
|
49
|
+
* Matching only the resolved path silently turns the denylist off for the
|
|
50
|
+
* second case.
|
|
36
51
|
*/
|
|
37
|
-
function normalizePath(filePath: string): {
|
|
52
|
+
function normalizePath(filePath: string): {
|
|
53
|
+
resolvedPath: string;
|
|
54
|
+
segments: string[];
|
|
55
|
+
writtenSegments: string[];
|
|
56
|
+
} {
|
|
38
57
|
const absolute = platform.resolvePath(filePath);
|
|
39
58
|
let resolved = absolute;
|
|
40
59
|
try {
|
|
@@ -46,7 +65,8 @@ function normalizePath(filePath: string): { resolvedPath: string; segments: stri
|
|
|
46
65
|
}
|
|
47
66
|
return {
|
|
48
67
|
resolvedPath: resolved,
|
|
49
|
-
segments: resolved
|
|
68
|
+
segments: splitSegments(resolved),
|
|
69
|
+
writtenSegments: splitSegments(absolute),
|
|
50
70
|
};
|
|
51
71
|
}
|
|
52
72
|
|
|
@@ -65,7 +85,7 @@ function getSensitiveFileUploadPathBlockReason(
|
|
|
65
85
|
filePath: string,
|
|
66
86
|
additionalDenySegments?: string[]
|
|
67
87
|
): string | null {
|
|
68
|
-
const { resolvedPath, segments } = normalizePath(filePath);
|
|
88
|
+
const { resolvedPath, segments, writtenSegments } = normalizePath(filePath);
|
|
69
89
|
const isCaseSensitive = platform.isFileSystemCaseSensitive?.(resolvedPath) ?? true;
|
|
70
90
|
const normalizeSegment = (segment: string) => (isCaseSensitive ? segment : segment.toLowerCase());
|
|
71
91
|
const deny = new Set(
|
|
@@ -75,15 +95,22 @@ function getSensitiveFileUploadPathBlockReason(
|
|
|
75
95
|
].map(normalizeSegment)
|
|
76
96
|
);
|
|
77
97
|
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
98
|
+
for (const candidate of [segments, writtenSegments]) {
|
|
99
|
+
const segmentsForMatch = isCaseSensitive ? candidate : candidate.map(normalizeSegment);
|
|
100
|
+
for (let i = 0; i < candidate.length; i++) {
|
|
101
|
+
if (deny.has(segmentsForMatch[i]!)) {
|
|
102
|
+
return `path segment "${candidate[i]}" is in the sensitive file upload denylist`;
|
|
103
|
+
}
|
|
82
104
|
}
|
|
83
105
|
}
|
|
84
106
|
|
|
85
|
-
|
|
86
|
-
|
|
107
|
+
// Same two directions as the segment scan: `~/.env -> /state/config` hides a
|
|
108
|
+
// denied basename from the resolved path, and a symlink pointing *at* a
|
|
109
|
+
// credential file hides it from the written one.
|
|
110
|
+
const basenames = [segments.at(-1), writtenSegments.at(-1)].filter(
|
|
111
|
+
(name): name is string => !!name
|
|
112
|
+
);
|
|
113
|
+
for (const basename of basenames) {
|
|
87
114
|
if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) {
|
|
88
115
|
return `file name "${basename}" looks like a credential, env, or private key file`;
|
|
89
116
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
|
|
2
2
|
import { isIP } from 'node:net';
|
|
3
3
|
import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
4
|
+
import { createPinnedDispatcher, hasCustomGlobalDispatcher } from './pinnedDispatcher.node';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* SSRF guard for user-supplied URL file inputs.
|
|
@@ -16,14 +17,43 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
|
16
17
|
* which defeats decimal/octal/hex IP obfuscation) before every fetch, and
|
|
17
18
|
* follows redirects manually so each hop is re-validated.
|
|
18
19
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* The address that was validated is also the address connected to: `fetch` gets
|
|
21
|
+
* a dispatcher pinned to it (see {@link createPinnedDispatcher}), so the
|
|
22
|
+
* hostname is never resolved a second time. Without that, a name could resolve
|
|
23
|
+
* to a public address during validation and rebind to an internal one before
|
|
24
|
+
* the connect — a TOCTOU window the Python guard closes the same way.
|
|
25
|
+
*
|
|
26
|
+
* Residual: a hop whose effective dispatcher is a configured route — a
|
|
27
|
+
* caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
|
|
28
|
+
* `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
|
|
29
|
+
* the runtime's env-proxy mode (`NODE_USE_ENV_PROXY`) — keeps only the
|
|
30
|
+
* pre-flight validation. Pinning would dial the validated address instead of
|
|
31
|
+
* the proxy, and the proxy resolves the hostname itself where the SDK cannot
|
|
32
|
+
* see or pin that resolution. The Python guard carries the same residual for
|
|
33
|
+
* the same reason (`_proxy_applies`).
|
|
23
34
|
*/
|
|
24
35
|
|
|
25
36
|
const MAX_REDIRECTS = 5;
|
|
26
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Whether the runtime would route `url` through an env proxy the SDK cannot
|
|
40
|
+
* see into. Only meaningful when `NODE_USE_ENV_PROXY` opts the built-in
|
|
41
|
+
* `fetch` into env proxies (Node >= 24); without that flag the runtime's
|
|
42
|
+
* `fetch` ignores `HTTP_PROXY`/`HTTPS_PROXY` entirely, so mirroring Python's
|
|
43
|
+
* bare env-var check would drop pinning for users whose fetch never proxied.
|
|
44
|
+
*
|
|
45
|
+
* `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
|
|
46
|
+
* pinning is safe again); per-host `NO_PROXY` entries are treated
|
|
47
|
+
* conservatively as proxied rather than parsed.
|
|
48
|
+
*/
|
|
49
|
+
const envProxyApplies = (url: URL): boolean => {
|
|
50
|
+
const useEnvProxy = ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
|
|
51
|
+
if (!useEnvProxy) return false;
|
|
52
|
+
if ((process.env.NO_PROXY ?? process.env.no_proxy ?? '') === '*') return false;
|
|
53
|
+
const schemeVar = url.protocol === 'https:' ? 'HTTPS_PROXY' : 'HTTP_PROXY';
|
|
54
|
+
return Boolean(process.env[schemeVar] ?? process.env[schemeVar.toLowerCase()]);
|
|
55
|
+
};
|
|
56
|
+
|
|
27
57
|
const ipv4ToLong = (ip: string): number => {
|
|
28
58
|
const [a, b, c, d] = ip.split('.').map(Number);
|
|
29
59
|
return (((a << 24) >>> 0) | (b << 16) | (c << 8) | d) >>> 0;
|
|
@@ -133,8 +163,12 @@ export const isBlockedIp = (ip: string): boolean => {
|
|
|
133
163
|
* Validate a single URL: it must be http(s), its host must resolve, and every
|
|
134
164
|
* resolved address must be publicly routable. Throws
|
|
135
165
|
* {@link ComposioBlockedInternalUrlError} otherwise.
|
|
166
|
+
*
|
|
167
|
+
* @returns the validated addresses to connect to, in resolver order. Callers
|
|
168
|
+
* must connect to *those* rather than let the client resolve the hostname
|
|
169
|
+
* again; see {@link ssrfSafeFetch}.
|
|
136
170
|
*/
|
|
137
|
-
export const assertSafeFetchTarget = async (rawUrl: string): Promise<
|
|
171
|
+
export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> => {
|
|
138
172
|
let url: URL;
|
|
139
173
|
try {
|
|
140
174
|
url = new URL(rawUrl);
|
|
@@ -158,6 +192,10 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
|
158
192
|
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
159
193
|
}
|
|
160
194
|
|
|
195
|
+
if (resolved.length === 0) {
|
|
196
|
+
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
197
|
+
}
|
|
198
|
+
|
|
161
199
|
for (const { address } of resolved) {
|
|
162
200
|
if (isBlockedIp(address)) {
|
|
163
201
|
throw new ComposioBlockedInternalUrlError(
|
|
@@ -166,13 +204,22 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
|
166
204
|
);
|
|
167
205
|
}
|
|
168
206
|
}
|
|
207
|
+
|
|
208
|
+
// Every answer was validated, so all of them are safe to connect to, and
|
|
209
|
+
// resolver order is the system's own address preference.
|
|
210
|
+
return resolved.map(({ address }) => address);
|
|
169
211
|
};
|
|
170
212
|
|
|
171
213
|
/**
|
|
172
|
-
* Drop-in replacement for `fetch` that blocks SSRF. Validates the target
|
|
173
|
-
*
|
|
174
|
-
* manually up to {@link MAX_REDIRECTS}).
|
|
175
|
-
* cancelled; non-redirect responses are
|
|
214
|
+
* Drop-in replacement for `fetch` that blocks SSRF. Validates the target, then
|
|
215
|
+
* connects to the address it validated, and re-validates and re-pins every
|
|
216
|
+
* redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
|
|
217
|
+
* Intermediate redirect bodies are cancelled; non-redirect responses are
|
|
218
|
+
* returned unchanged.
|
|
219
|
+
*
|
|
220
|
+
* A hop whose effective dispatcher is a configured route (caller-supplied
|
|
221
|
+
* `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
|
|
222
|
+
* pinned — see the module residual above.
|
|
176
223
|
*/
|
|
177
224
|
export const ssrfSafeFetch = async (
|
|
178
225
|
rawUrl: string,
|
|
@@ -182,9 +229,40 @@ export const ssrfSafeFetch = async (
|
|
|
182
229
|
let currentUrl = rawUrl;
|
|
183
230
|
|
|
184
231
|
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
185
|
-
await assertSafeFetchTarget(currentUrl);
|
|
232
|
+
const addresses = await assertSafeFetchTarget(currentUrl);
|
|
233
|
+
|
|
234
|
+
// Pinning replaces the connect target; through a configured route that
|
|
235
|
+
// would dial the validated origin instead of the route's next hop (the
|
|
236
|
+
// proxy), so those hops keep the pre-flight check only.
|
|
237
|
+
const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
|
|
238
|
+
const respectConfiguredRoute =
|
|
239
|
+
callerDispatcher !== undefined ||
|
|
240
|
+
envProxyApplies(new URL(currentUrl)) ||
|
|
241
|
+
hasCustomGlobalDispatcher();
|
|
242
|
+
|
|
243
|
+
const dispatcher = respectConfiguredRoute ? undefined : await createPinnedDispatcher(addresses);
|
|
186
244
|
|
|
187
|
-
|
|
245
|
+
let response: Response;
|
|
246
|
+
try {
|
|
247
|
+
// `dispatcher` is a Node-only extension to `RequestInit`.
|
|
248
|
+
response = await fetch(
|
|
249
|
+
currentUrl,
|
|
250
|
+
(dispatcher === undefined
|
|
251
|
+
? { ...init, redirect: 'manual' }
|
|
252
|
+
: { ...init, redirect: 'manual', dispatcher }) as RequestInit
|
|
253
|
+
);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (dispatcher !== undefined) {
|
|
256
|
+
await dispatcher.close().catch(() => undefined);
|
|
257
|
+
}
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// `close()` is graceful: it waits for the in-flight request — including a
|
|
262
|
+
// body still being streamed to the caller — before releasing the socket.
|
|
263
|
+
if (dispatcher !== undefined) {
|
|
264
|
+
void dispatcher.close().catch(() => undefined);
|
|
265
|
+
}
|
|
188
266
|
|
|
189
267
|
const isRedirect =
|
|
190
268
|
response.status >= 300 && response.status < 400 && response.headers.has('location');
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
//#region src/utils/modifiers/FileToolModifier.utils.neutral.ts
|
|
2
|
-
function isPlainObject(val) {
|
|
3
|
-
return typeof val === "object" && val !== null && !Array.isArray(val);
|
|
4
|
-
}
|
|
5
|
-
/**
|
|
6
|
-
* Transforms a single JSON schema property, recursively handling nested properties,
|
|
7
|
-
* anyOf, oneOf, and allOf.
|
|
8
|
-
*/
|
|
9
|
-
const transformSchema = (property) => {
|
|
10
|
-
if (property.file_uploadable) return {
|
|
11
|
-
title: property.title,
|
|
12
|
-
description: property.description,
|
|
13
|
-
format: "path",
|
|
14
|
-
type: "string",
|
|
15
|
-
file_uploadable: true
|
|
16
|
-
};
|
|
17
|
-
const newProperty = { ...property };
|
|
18
|
-
if (property.type === "object" && property.properties) newProperty.properties = transformProperties(property.properties);
|
|
19
|
-
if (property.anyOf) newProperty.anyOf = property.anyOf.map(transformSchema);
|
|
20
|
-
if (property.oneOf) newProperty.oneOf = property.oneOf.map(transformSchema);
|
|
21
|
-
if (property.allOf) newProperty.allOf = property.allOf.map(transformSchema);
|
|
22
|
-
if (property.items) if (Array.isArray(property.items)) newProperty.items = property.items.map(transformSchema);
|
|
23
|
-
else newProperty.items = transformSchema(property.items);
|
|
24
|
-
return newProperty;
|
|
25
|
-
};
|
|
26
|
-
/**
|
|
27
|
-
* Transforms the properties of the tool schema to include the file upload URL.
|
|
28
|
-
*
|
|
29
|
-
* Attaches the format: 'path' to the properties that are file uploadable for agents.
|
|
30
|
-
*
|
|
31
|
-
* @param properties - The properties of the tool schema.
|
|
32
|
-
* @returns The transformed properties.
|
|
33
|
-
*/
|
|
34
|
-
const transformProperties = (properties) => {
|
|
35
|
-
const newProperties = {};
|
|
36
|
-
for (const [key, property] of Object.entries(properties)) newProperties[key] = transformSchema(property);
|
|
37
|
-
return newProperties;
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* Recursively checks if a schema (or any of its variants) contains a specific file property.
|
|
41
|
-
*/
|
|
42
|
-
const schemaHasFileProperty = (schema, property) => {
|
|
43
|
-
if (!schema) return false;
|
|
44
|
-
if (schema[property]) return true;
|
|
45
|
-
if (schema.properties) {
|
|
46
|
-
for (const prop of Object.values(schema.properties)) if (schemaHasFileProperty(prop, property)) return true;
|
|
47
|
-
}
|
|
48
|
-
if (schema.anyOf) {
|
|
49
|
-
for (const variant of schema.anyOf) if (schemaHasFileProperty(variant, property)) return true;
|
|
50
|
-
}
|
|
51
|
-
if (schema.oneOf) {
|
|
52
|
-
for (const variant of schema.oneOf) if (schemaHasFileProperty(variant, property)) return true;
|
|
53
|
-
}
|
|
54
|
-
if (schema.allOf) {
|
|
55
|
-
for (const variant of schema.allOf) if (schemaHasFileProperty(variant, property)) return true;
|
|
56
|
-
}
|
|
57
|
-
if (schema.items) {
|
|
58
|
-
if (Array.isArray(schema.items)) {
|
|
59
|
-
for (const item of schema.items) if (schemaHasFileProperty(item, property)) return true;
|
|
60
|
-
} else if (schemaHasFileProperty(schema.items, property)) return true;
|
|
61
|
-
}
|
|
62
|
-
return false;
|
|
63
|
-
};
|
|
64
|
-
/**
|
|
65
|
-
* Recursively checks if a schema (or any of its variants) contains file_uploadable properties.
|
|
66
|
-
*/
|
|
67
|
-
const schemaHasFileUploadable = (schema) => {
|
|
68
|
-
return schemaHasFileProperty(schema, "file_uploadable");
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
//#endregion
|
|
72
|
-
export { transformProperties as i, schemaHasFileProperty as n, schemaHasFileUploadable as r, isPlainObject as t };
|