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)` and automatic file upload during tool execution
9
+ * fetch arbitrary user-provided URLs. Without a guard, a caller (or a tool
10
+ * argument produced by an LLM) can point the SDK at internal infrastructure —
11
+ * loopback, RFC1918 ranges, link-local cloud-metadata endpoints
12
+ * (`169.254.169.254`), or a public URL that 3xx-redirects into internal space —
13
+ * turning the SDK into a server-side request forgery probe.
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
+};