@composio/core 0.17.0 → 0.18.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/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-Bz0f52QR.mjs} +16 -6
- package/dist/{CustomTool-Uip-fhPw.d.mts → CustomTool-VRfWzMix.d.mts} +1 -1
- package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-CwB-Inm9.mjs} +1 -1
- package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
- package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-xhdVE4yw.mjs} +123 -3
- package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-Dw9W5RSp.mjs} +28 -44
- package/dist/cancellation-P5YUlcfz.mjs +704 -0
- package/dist/{composio-B27X6i6A.d.mts → composio-Cb3d1jFe.d.mts} +250 -244
- package/dist/{customTool.types-B2Ava_j5.d.mts → customTool.types-B6ej_8XZ.d.mts} +146 -144
- package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
- package/dist/docs/reference/sdk-reference/typescript/session.mdx +4 -3
- package/dist/{errors-BcEUHZbq.mjs → errors-Ue9wMrPK.mjs} +5 -2
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/{fileUtils.node-B1Wn848p.mjs → fileUtils.node-KE5Fa-af.mjs} +7 -7
- package/dist/index.d.mts +108 -8
- package/dist/index.mjs +109 -55
- package/dist/models/Files.node.mjs +2 -2
- package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-QN7w4n8v.mjs} +24 -7
- package/dist/ssrfGuard.node-BLX6b-Rf.mjs +384 -0
- package/dist/{types-DdZJuMm2.d.mts → types-CGdgK442.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 +59 -103
- 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/dist/utils/ssrfGuard.workerd.d.mts +1 -1
- package/dist/utils/ssrfGuard.workerd.mjs +2 -2
- package/package.json +25 -3
- package/src/errors/ToolErrors.ts +1 -0
- package/src/errors/ValidationErrors.ts +2 -0
- package/src/index.ts +6 -0
- package/src/models/CustomTool.ts +41 -6
- package/src/models/RemoteFile.ts +54 -36
- package/src/models/ToolRouterSession.ts +45 -12
- package/src/models/Tools.ts +102 -39
- package/src/models/Triggers.ts +15 -0
- package/src/services/telemetry/TelemetryService.ts +27 -12
- package/src/telemetry/redact.ts +133 -6
- package/src/utils/fileUtils.node.ts +10 -2
- package/src/utils/jsonSchema.ts +505 -27
- package/src/utils/logger.ts +6 -6
- 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 +214 -0
- package/src/utils/sdk.ts +1 -1
- package/src/utils/sensitiveFileUploadPaths.ts +36 -9
- package/src/utils/ssrfGuard.node.ts +101 -11
- package/src/utils/ssrfGuard.workerd.ts +5 -1
- package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
- package/dist/cancellation-NVtGf3St.mjs +0 -364
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { request as httpsRequest } from 'node:https';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import type { Agent } from 'undici';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The `globalThis` symbols that hold the process-wide dispatcher `fetch` falls
|
|
9
|
+
* back to. Every undici in the process shares them — including the one inside
|
|
10
|
+
* the Node runtime — and `setGlobalDispatcher` writes both, so reading them
|
|
11
|
+
* directly sees the same dispatcher the runtime's own `fetch` would use.
|
|
12
|
+
*
|
|
13
|
+
* Read rather than imported: importing `undici` installs a dispatcher of its
|
|
14
|
+
* own as an import side effect (see {@link loadUndici}), which is exactly what
|
|
15
|
+
* this module must not do at load time.
|
|
16
|
+
*/
|
|
17
|
+
const GLOBAL_DISPATCHER_SYMBOLS = [
|
|
18
|
+
Symbol.for('undici.globalDispatcher.1'),
|
|
19
|
+
Symbol.for('undici.globalDispatcher.2'),
|
|
20
|
+
] as const;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `undici`, imported on first use rather than at module load.
|
|
24
|
+
*
|
|
25
|
+
* Importing it runs `if (getGlobalDispatcher() === undefined) setGlobalDispatcher(new Agent())`
|
|
26
|
+
* as a side effect, which would hand every unrelated `fetch` in the host
|
|
27
|
+
* application this package's undici instead of the runtime's own — a global
|
|
28
|
+
* change no caller asked for by importing `@composio/core`. Deferring the
|
|
29
|
+
* import to the first pinned request keeps that side effect on the code path
|
|
30
|
+
* that actually needs undici, and behind the `hasCustomGlobalDispatcher` check
|
|
31
|
+
* that reads the slot's true, pre-import state.
|
|
32
|
+
*
|
|
33
|
+
* A process that does make a pinned request still ends up on this package's
|
|
34
|
+
* `Agent` if nothing had claimed the slot yet. That much is not reversible:
|
|
35
|
+
* undici defines the slot non-configurable and writable, so it cannot be
|
|
36
|
+
* cleared back to empty — assigning `undefined` leaves the runtime's own
|
|
37
|
+
* `fetch` asserting on a missing dispatcher.
|
|
38
|
+
*/
|
|
39
|
+
let undici: Promise<typeof import('undici')> | undefined;
|
|
40
|
+
const loadUndici = (): Promise<typeof import('undici')> => (undici ??= import('undici'));
|
|
41
|
+
|
|
42
|
+
const lookupPinnedAddresses = (
|
|
43
|
+
addresses: ReadonlyArray<string>,
|
|
44
|
+
options: { all?: boolean },
|
|
45
|
+
callback: (
|
|
46
|
+
error: NodeJS.ErrnoException | null,
|
|
47
|
+
address: string | Array<{ address: string; family: number }>,
|
|
48
|
+
family?: number
|
|
49
|
+
) => void
|
|
50
|
+
) => {
|
|
51
|
+
if (options.all) {
|
|
52
|
+
callback(
|
|
53
|
+
null,
|
|
54
|
+
addresses.map(address => ({ address, family: isIP(address) }))
|
|
55
|
+
);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const [address] = addresses;
|
|
60
|
+
callback(null, address, isIP(address));
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const knownBodyLength = (body: BodyInit | null | undefined): number | undefined => {
|
|
64
|
+
if (body === null || body === undefined) return undefined;
|
|
65
|
+
if (typeof body === 'string') return new TextEncoder().encode(body).byteLength;
|
|
66
|
+
if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
|
|
67
|
+
if (body instanceof ArrayBuffer) return body.byteLength;
|
|
68
|
+
if (ArrayBuffer.isView(body)) return body.byteLength;
|
|
69
|
+
if (body instanceof Blob) return body.size;
|
|
70
|
+
return undefined;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A `fetch` dispatcher that connects to `addresses` instead of resolving the
|
|
75
|
+
* hostname again.
|
|
76
|
+
*
|
|
77
|
+
* The SSRF guard resolves a hostname to decide whether a URL is safe to fetch.
|
|
78
|
+
* `fetch` would then resolve that hostname a second time when it opens the
|
|
79
|
+
* socket, and the two answers need not match: a short-TTL record can answer
|
|
80
|
+
* with a public address for the check and an internal one for the connect
|
|
81
|
+
* (DNS rebinding). Pinning the connect to the address that was validated
|
|
82
|
+
* removes the second lookup, so there is nothing left to rebind.
|
|
83
|
+
*
|
|
84
|
+
* Only the connect target is replaced. The request still carries the original
|
|
85
|
+
* hostname in `Host` and offers it as TLS SNI, so certificate verification is
|
|
86
|
+
* unchanged — connecting by IP with the IP as SNI would fail against every
|
|
87
|
+
* origin whose certificate names a hostname.
|
|
88
|
+
*
|
|
89
|
+
* The dispatcher is handed to the runtime's own `fetch`, so callers that stub
|
|
90
|
+
* `globalThis.fetch` keep working. That does tie the `undici` major to the one
|
|
91
|
+
* Node's `fetch` speaks — undici 8 dispatchers are rejected by the Node
|
|
92
|
+
* versions this package supports — which is why the dependency is pinned to
|
|
93
|
+
* `^7`, and why `pinnedDispatcher.node.test.ts` exercises a real socket on
|
|
94
|
+
* every Node version in CI rather than mocking the transport.
|
|
95
|
+
*/
|
|
96
|
+
export const createPinnedDispatcher = async (addresses: ReadonlyArray<string>): Promise<Agent> => {
|
|
97
|
+
const { Agent } = await loadUndici();
|
|
98
|
+
|
|
99
|
+
return new Agent({
|
|
100
|
+
connect: {
|
|
101
|
+
lookup: (_hostname, options, callback) => {
|
|
102
|
+
// Node calls a lookup in one of two shapes and picks between them at
|
|
103
|
+
// connect time: `(err, addresses)` when it is doing Happy Eyeballs,
|
|
104
|
+
// and `(err, address, family)` otherwise — when `autoSelectFamily` is
|
|
105
|
+
// off, or a `family`/`localAddress` was requested. Answering in the
|
|
106
|
+
// wrong shape is rejected as an invalid address, which would fail
|
|
107
|
+
// every pinned fetch in such a process.
|
|
108
|
+
lookupPinnedAddresses(addresses, options, callback);
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Fetch through the Node-compatible HTTP client while pinning DNS resolution.
|
|
116
|
+
*
|
|
117
|
+
* Bun implements the Node HTTP client and its `lookup` hook, but its native
|
|
118
|
+
* `fetch` ignores undici's `dispatcher` option. This transport preserves the
|
|
119
|
+
* original hostname for Host and TLS SNI while making the socket use an
|
|
120
|
+
* address that the SSRF guard already validated.
|
|
121
|
+
*/
|
|
122
|
+
export const pinnedHttpFetch = async (
|
|
123
|
+
rawUrl: string,
|
|
124
|
+
init: RequestInit,
|
|
125
|
+
addresses: ReadonlyArray<string>
|
|
126
|
+
): Promise<Response> => {
|
|
127
|
+
const normalized = new Request(rawUrl, init);
|
|
128
|
+
const url = new URL(rawUrl);
|
|
129
|
+
const request = url.protocol === 'https:' ? httpsRequest : httpRequest;
|
|
130
|
+
const headers = new Headers(normalized.headers);
|
|
131
|
+
const bodyLength = knownBodyLength(init.body);
|
|
132
|
+
if (bodyLength !== undefined && !headers.has('content-length')) {
|
|
133
|
+
headers.set('content-length', String(bodyLength));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return new Promise<Response>((resolve, reject) => {
|
|
137
|
+
const outgoing = request(
|
|
138
|
+
url,
|
|
139
|
+
{
|
|
140
|
+
method: normalized.method,
|
|
141
|
+
headers: Object.fromEntries(headers.entries()),
|
|
142
|
+
signal: normalized.signal,
|
|
143
|
+
lookup: (_hostname, options, callback) =>
|
|
144
|
+
lookupPinnedAddresses(addresses, options, callback),
|
|
145
|
+
},
|
|
146
|
+
incoming => {
|
|
147
|
+
const headers = new Headers();
|
|
148
|
+
for (let index = 0; index < incoming.rawHeaders.length; index += 2) {
|
|
149
|
+
headers.append(incoming.rawHeaders[index], incoming.rawHeaders[index + 1]);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const status = incoming.statusCode ?? 500;
|
|
153
|
+
const body = [101, 103, 204, 205, 304].includes(status)
|
|
154
|
+
? null
|
|
155
|
+
: (Readable.toWeb(incoming) as ReadableStream<Uint8Array>);
|
|
156
|
+
resolve(
|
|
157
|
+
new Response(body, {
|
|
158
|
+
status,
|
|
159
|
+
statusText: incoming.statusMessage,
|
|
160
|
+
headers,
|
|
161
|
+
})
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
outgoing.once('error', reject);
|
|
167
|
+
|
|
168
|
+
void (async () => {
|
|
169
|
+
try {
|
|
170
|
+
if (normalized.body) {
|
|
171
|
+
const reader = normalized.body.getReader();
|
|
172
|
+
while (true) {
|
|
173
|
+
const { done, value } = await reader.read();
|
|
174
|
+
if (done) break;
|
|
175
|
+
if (!outgoing.write(value)) {
|
|
176
|
+
await new Promise<void>(resolveDrain => outgoing.once('drain', resolveDrain));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
outgoing.end();
|
|
181
|
+
} catch (error) {
|
|
182
|
+
outgoing.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
183
|
+
}
|
|
184
|
+
})();
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether the process-wide dispatcher `fetch` falls back to (when a request
|
|
190
|
+
* carries no `dispatcher` of its own) is something other than a stock `Agent`.
|
|
191
|
+
*
|
|
192
|
+
* A `ProxyAgent`, `EnvHttpProxyAgent`, or custom dispatcher installed through
|
|
193
|
+
* `setGlobalDispatcher` is visible here, and pinning stands down for it: the
|
|
194
|
+
* connect would dial the validated origin instead of that route's next hop.
|
|
195
|
+
*
|
|
196
|
+
* Nothing installed yet is *not* custom. The dispatcher slot is empty until
|
|
197
|
+
* either the runtime's `fetch` or an undici import fills it, so an absent
|
|
198
|
+
* dispatcher means no caller has configured a route — treating it as custom
|
|
199
|
+
* would disable pinning for every process that had not yet made a request.
|
|
200
|
+
*
|
|
201
|
+
* Stock-ness is compared by constructor *name*, deliberately not with
|
|
202
|
+
* `instanceof Agent`: an `Agent` created by the runtime's internal undici is a
|
|
203
|
+
* different class from this package's `Agent`, so once the runtime's own
|
|
204
|
+
* `fetch` has initialized its default dispatcher, an `instanceof` check would
|
|
205
|
+
* report a stock setup as custom and silently disable pinning.
|
|
206
|
+
*/
|
|
207
|
+
export const hasCustomGlobalDispatcher = (): boolean => {
|
|
208
|
+
const slots = globalThis as unknown as Record<symbol, { constructor?: { name?: string } }>;
|
|
209
|
+
const dispatcher = GLOBAL_DISPATCHER_SYMBOLS.map(symbol => slots[symbol]).find(
|
|
210
|
+
installed => installed !== undefined
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
return dispatcher !== undefined && dispatcher.constructor?.name !== 'Agent';
|
|
214
|
+
};
|
package/src/utils/sdk.ts
CHANGED
|
@@ -53,7 +53,7 @@ export function getSDKConfig(baseUrl?: string | null, apiKey?: string | null) {
|
|
|
53
53
|
ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
logger.debug('Environment',
|
|
56
|
+
logger.debug('Environment', 'API Key: [REDACTED]');
|
|
57
57
|
logger.debug('Environment', `Base URL: ${baseURLParsed}`);
|
|
58
58
|
|
|
59
59
|
return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
|
|
@@ -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,11 @@
|
|
|
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 {
|
|
5
|
+
createPinnedDispatcher,
|
|
6
|
+
hasCustomGlobalDispatcher,
|
|
7
|
+
pinnedHttpFetch,
|
|
8
|
+
} from './pinnedDispatcher.node';
|
|
4
9
|
|
|
5
10
|
/**
|
|
6
11
|
* SSRF guard for user-supplied URL file inputs.
|
|
@@ -16,14 +21,45 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
|
16
21
|
* which defeats decimal/octal/hex IP obfuscation) before every fetch, and
|
|
17
22
|
* follows redirects manually so each hop is re-validated.
|
|
18
23
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
24
|
+
* The address that was validated is also the address connected to: `fetch` gets
|
|
25
|
+
* a dispatcher pinned to it (see {@link createPinnedDispatcher}), so the
|
|
26
|
+
* hostname is never resolved a second time. Without that, a name could resolve
|
|
27
|
+
* to a public address during validation and rebind to an internal one before
|
|
28
|
+
* the connect — a TOCTOU window the Python guard closes the same way.
|
|
29
|
+
*
|
|
30
|
+
* Residual: a hop whose effective dispatcher is a configured route — a
|
|
31
|
+
* caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
|
|
32
|
+
* `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
|
|
33
|
+
* the runtime's env-proxy mode (automatic on Bun, opt-in via
|
|
34
|
+
* `NODE_USE_ENV_PROXY` on Node) — keeps only the
|
|
35
|
+
* pre-flight validation. Pinning would dial the validated address instead of
|
|
36
|
+
* the proxy, and the proxy resolves the hostname itself where the SDK cannot
|
|
37
|
+
* see or pin that resolution. The Python guard carries the same residual for
|
|
38
|
+
* the same reason (`_proxy_applies`).
|
|
23
39
|
*/
|
|
24
40
|
|
|
25
41
|
const MAX_REDIRECTS = 5;
|
|
26
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Whether the runtime would route `url` through an env proxy the SDK cannot
|
|
45
|
+
* see into. Bun honors proxy environment variables automatically. Node's
|
|
46
|
+
* built-in `fetch` requires the `NODE_USE_ENV_PROXY` opt-in (Node >= 24), so
|
|
47
|
+
* a bare env-var check on Node would drop pinning for users whose fetch never
|
|
48
|
+
* proxied.
|
|
49
|
+
*
|
|
50
|
+
* `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
|
|
51
|
+
* pinning is safe again); per-host `NO_PROXY` entries are treated
|
|
52
|
+
* conservatively as proxied rather than parsed.
|
|
53
|
+
*/
|
|
54
|
+
const envProxyApplies = (url: URL, isBun: boolean): boolean => {
|
|
55
|
+
const useEnvProxy =
|
|
56
|
+
isBun || ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
|
|
57
|
+
if (!useEnvProxy) return false;
|
|
58
|
+
if ((process.env.NO_PROXY ?? process.env.no_proxy ?? '') === '*') return false;
|
|
59
|
+
const schemeVar = url.protocol === 'https:' ? 'HTTPS_PROXY' : 'HTTP_PROXY';
|
|
60
|
+
return Boolean(process.env[schemeVar] ?? process.env[schemeVar.toLowerCase()]);
|
|
61
|
+
};
|
|
62
|
+
|
|
27
63
|
const ipv4ToLong = (ip: string): number => {
|
|
28
64
|
const [a, b, c, d] = ip.split('.').map(Number);
|
|
29
65
|
return (((a << 24) >>> 0) | (b << 16) | (c << 8) | d) >>> 0;
|
|
@@ -133,8 +169,12 @@ export const isBlockedIp = (ip: string): boolean => {
|
|
|
133
169
|
* Validate a single URL: it must be http(s), its host must resolve, and every
|
|
134
170
|
* resolved address must be publicly routable. Throws
|
|
135
171
|
* {@link ComposioBlockedInternalUrlError} otherwise.
|
|
172
|
+
*
|
|
173
|
+
* @returns the validated addresses to connect to, in resolver order. Callers
|
|
174
|
+
* must connect to *those* rather than let the client resolve the hostname
|
|
175
|
+
* again; see {@link ssrfSafeFetch}.
|
|
136
176
|
*/
|
|
137
|
-
export const assertSafeFetchTarget = async (rawUrl: string): Promise<
|
|
177
|
+
export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> => {
|
|
138
178
|
let url: URL;
|
|
139
179
|
try {
|
|
140
180
|
url = new URL(rawUrl);
|
|
@@ -158,6 +198,10 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
|
158
198
|
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
159
199
|
}
|
|
160
200
|
|
|
201
|
+
if (resolved.length === 0) {
|
|
202
|
+
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
203
|
+
}
|
|
204
|
+
|
|
161
205
|
for (const { address } of resolved) {
|
|
162
206
|
if (isBlockedIp(address)) {
|
|
163
207
|
throw new ComposioBlockedInternalUrlError(
|
|
@@ -166,13 +210,22 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
|
166
210
|
);
|
|
167
211
|
}
|
|
168
212
|
}
|
|
213
|
+
|
|
214
|
+
// Every answer was validated, so all of them are safe to connect to, and
|
|
215
|
+
// resolver order is the system's own address preference.
|
|
216
|
+
return resolved.map(({ address }) => address);
|
|
169
217
|
};
|
|
170
218
|
|
|
171
219
|
/**
|
|
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
|
|
220
|
+
* Drop-in replacement for `fetch` that blocks SSRF. Validates the target, then
|
|
221
|
+
* connects to the address it validated, and re-validates and re-pins every
|
|
222
|
+
* redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
|
|
223
|
+
* Intermediate redirect bodies are cancelled; non-redirect responses are
|
|
224
|
+
* returned unchanged.
|
|
225
|
+
*
|
|
226
|
+
* A hop whose effective dispatcher is a configured route (caller-supplied
|
|
227
|
+
* `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
|
|
228
|
+
* pinned — see the module residual above.
|
|
176
229
|
*/
|
|
177
230
|
export const ssrfSafeFetch = async (
|
|
178
231
|
rawUrl: string,
|
|
@@ -182,9 +235,46 @@ export const ssrfSafeFetch = async (
|
|
|
182
235
|
let currentUrl = rawUrl;
|
|
183
236
|
|
|
184
237
|
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
185
|
-
await assertSafeFetchTarget(currentUrl);
|
|
238
|
+
const addresses = await assertSafeFetchTarget(currentUrl);
|
|
239
|
+
const isBun = typeof process.versions.bun === 'string';
|
|
240
|
+
|
|
241
|
+
// Pinning replaces the connect target; through a configured route that
|
|
242
|
+
// would dial the validated origin instead of the route's next hop (the
|
|
243
|
+
// proxy), so those hops keep the pre-flight check only.
|
|
244
|
+
const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
|
|
245
|
+
const respectConfiguredRoute =
|
|
246
|
+
callerDispatcher !== undefined ||
|
|
247
|
+
envProxyApplies(new URL(currentUrl), isBun) ||
|
|
248
|
+
hasCustomGlobalDispatcher();
|
|
186
249
|
|
|
187
|
-
const
|
|
250
|
+
const dispatcher =
|
|
251
|
+
respectConfiguredRoute || isBun ? undefined : await createPinnedDispatcher(addresses);
|
|
252
|
+
|
|
253
|
+
let response: Response;
|
|
254
|
+
try {
|
|
255
|
+
if (isBun && !respectConfiguredRoute) {
|
|
256
|
+
response = await pinnedHttpFetch(currentUrl, { ...init, redirect: 'manual' }, addresses);
|
|
257
|
+
} else {
|
|
258
|
+
// `dispatcher` is a Node-only extension to `RequestInit`.
|
|
259
|
+
response = await fetch(
|
|
260
|
+
currentUrl,
|
|
261
|
+
(dispatcher === undefined
|
|
262
|
+
? { ...init, redirect: 'manual' }
|
|
263
|
+
: { ...init, redirect: 'manual', dispatcher }) as RequestInit
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (dispatcher !== undefined) {
|
|
268
|
+
await dispatcher.close().catch(() => undefined);
|
|
269
|
+
}
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// `close()` is graceful: it waits for the in-flight request — including a
|
|
274
|
+
// body still being streamed to the caller — before releasing the socket.
|
|
275
|
+
if (dispatcher !== undefined) {
|
|
276
|
+
void dispatcher.close().catch(() => undefined);
|
|
277
|
+
}
|
|
188
278
|
|
|
189
279
|
const isRedirect =
|
|
190
280
|
response.status >= 300 && response.status < 400 && response.headers.has('location');
|
|
@@ -5,7 +5,11 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
|
5
5
|
* hostname is publicly routable before connecting. Fail closed instead of
|
|
6
6
|
* falling back to an unguarded fetch.
|
|
7
7
|
*/
|
|
8
|
-
export const ssrfSafeFetch = async (
|
|
8
|
+
export const ssrfSafeFetch = async (
|
|
9
|
+
rawUrl: string,
|
|
10
|
+
_init: RequestInit = {},
|
|
11
|
+
_maxRedirects?: number
|
|
12
|
+
): Promise<Response> => {
|
|
9
13
|
throw new ComposioBlockedInternalUrlError(
|
|
10
14
|
'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',
|
|
11
15
|
{
|
|
@@ -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 };
|