ssrf-safe 0.0.0-stage → 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ First stable release. ssrf-safe stops servers and AI agents from fetching private, internal and cloud metadata addresses, with no dependencies.
6
+
7
+ - `ssrf-safe`: `checkUrl` and `isSafeUrl` check a URL without DNS, in any runtime: schemes, credentials, ports, IP addresses in every encoding (decimal, octal, hex, shortened, IPv6, IPv4-mapped, NAT64, 6to4, Teredo) and internal hostnames. `classifyIp`, `isPrivateIp` and `normalizeIp` work on single addresses.
8
+ - `ssrf-safe/fetch`: `safeFetch` on top of the runtime's `fetch`. Follows redirects itself and checks every hop, refuses https to http downgrades, and enforces a timeout and a maximum response size.
9
+ - `ssrf-safe/node`: `safeFetch` built on node:http and node:https, which also checks every address a hostname resolves to and connects to the address it checked, so DNS rebinding can't swap it. `checkHost` resolves and checks a hostname. `SafeHttpAgent`, `SafeHttpsAgent` and `createSafeAgent` bring the same protection to node:http, axios and got.
10
+ - `SsrfError` and `FetchLimitError` with stable `code` and `rule` values.
11
+
12
+ ## 0.0.1
13
+
14
+ Name reservation. No code.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CK Giri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,380 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <h1>ssrf-safe</h1>
4
+
5
+ <h3>Fetch URLs safely from servers and AI agents.</h3>
6
+
7
+ <p>
8
+ <a href="https://www.npmjs.com/package/ssrf-safe"><img src="https://img.shields.io/npm/v/ssrf-safe?color=blue" alt="npm version"></a>
9
+ <a href="https://github.com/ckgiri/ssrf-safe/actions/workflows/ci.yml"><img src="https://github.com/ckgiri/ssrf-safe/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
10
+ <a href="https://www.npmjs.com/package/ssrf-safe?activeTab=dependencies"><img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="zero dependencies"></a>
11
+ <a href="https://www.npmjs.com/package/ssrf-safe"><img src="https://img.shields.io/npm/types/ssrf-safe" alt="TypeScript types included"></a>
12
+ <a href="LICENSE"><img src="https://img.shields.io/npm/l/ssrf-safe" alt="MIT license"></a>
13
+ <a href="CONTRIBUTING.md"><img src="https://img.shields.io/badge/contributions-welcome-brightgreen" alt="contributions welcome"></a>
14
+ </p>
15
+
16
+ <p>
17
+ <a href="#installation">Installation</a> ·
18
+ <a href="#quick-start">Quick start</a> ·
19
+ <a href="#what-it-blocks">What it blocks</a> ·
20
+ <a href="#how-it-compares">How it compares</a> ·
21
+ <a href="#api">API</a> ·
22
+ <a href="#options">Options</a> ·
23
+ <a href="#limits">Limits</a> ·
24
+ <a href="#contributing">Contributing</a>
25
+ </p>
26
+
27
+ </div>
28
+
29
+ **ssrf-safe** is a lightweight, zero-dependency library that stops your server or AI agent from fetching URLs it shouldn't. It blocks private and internal IP addresses in every encoding, cloud metadata endpoints, internal hostnames, and redirects that lead to any of them. In Node.js it also checks what a hostname resolves to, and connects to the address it checked.
30
+
31
+ ```js
32
+ import { safeFetch } from "ssrf-safe/node";
33
+
34
+ await safeFetch("http://169.254.169.254/latest/meta-data/");
35
+ // SsrfError: Blocked 169.254.169.254 is a cloud metadata address
36
+
37
+ await safeFetch("http://0x7f.1:6379/");
38
+ // SsrfError: Blocked 127.0.0.1 is a loopback address
39
+
40
+ const res = await safeFetch("https://example.com/"); // a normal Response
41
+ ```
42
+
43
+ ## Why
44
+
45
+ Server-side request forgery (SSRF) happens when your server fetches a URL that someone else chose. Link previews, webhooks, "import from URL", PDF renderers and image proxies all do this. So do AI agents with a "fetch a web page" tool, and the URL might come from a prompt injection hidden in a page the agent read earlier.
46
+
47
+ The server sits inside your network, so it can reach things the attacker can't: an admin panel on `localhost`, a database on `10.0.0.5`, a Kubernetes service, or the cloud metadata endpoint. On AWS, GCP and Azure, `http://169.254.169.254/` hands out instance details and, on many setups, temporary cloud credentials. One fetch of that URL, with the response shown back to the attacker, can leak keys to your cloud account.
48
+
49
+ Checking the URL with a regex doesn't work. `127.0.0.1` can also be written `2130706433`, `0x7f.1`, `0177.0.0.1`, `127.1`, `[::ffff:7f00:1]` or `①②⑦.⓪.⓪.①`. A public URL can redirect to an internal one. A public hostname can resolve to a private address, or change its answer between your check and your request (DNS rebinding). ssrf-safe handles all of these.
50
+
51
+ ## ✨ Features
52
+
53
+ - 🔢 **Every IP encoding**: decimal, octal, hex, shortened and mixed IPv4, IPv6 with zone IDs, IPv4-mapped, NAT64, 6to4 and Teredo addresses
54
+ - ☁️ **Cloud metadata**: blocks AWS, GCP, Azure, Alibaba and Oracle metadata addresses and hostnames, even in development mode
55
+ - 🏠 **Internal hostnames**: `localhost`, `*.internal`, `*.local`, Kubernetes service names and single-label names like `redis`
56
+ - ↪️ **Safe redirects**: follows redirects itself and checks every hop, including relative ones, and refuses https to http downgrades
57
+ - 🧭 **DNS-aware in Node.js**: checks every resolved address and connects to the one it checked, so DNS rebinding can't swap it
58
+ - 🔌 **Works with your HTTP client**: safe agents for node:http, axios and got
59
+ - ⏱️ **Limits**: a timeout for the whole request and a maximum response size, decompressed bytes included
60
+ - 🌍 **Runs anywhere**: the main entry works in Node.js, browsers, Deno, Bun and edge runtimes
61
+ - 📦 **Zero dependencies**: small, typed, ESM and CommonJS
62
+
63
+ ## Installation
64
+
65
+ ```bash
66
+ npm install ssrf-safe
67
+ ```
68
+
69
+ Node.js 18 or later. Three entries:
70
+
71
+ | Import | Use it for | Runs in |
72
+ |---|---|---|
73
+ | `ssrf-safe` | `checkUrl`, `classifyIp`: check a URL or address without fetching | Anywhere |
74
+ | `ssrf-safe/fetch` | `safeFetch` on top of the runtime's `fetch`, without DNS checks | Anywhere `fetch` exists |
75
+ | `ssrf-safe/node` | `safeFetch`, `checkHost` and safe agents, with DNS checks | Node.js |
76
+
77
+ ## Quick start
78
+
79
+ ### Node.js server
80
+
81
+ Use `ssrf-safe/node` whenever you can. It's the only entry that sees DNS.
82
+
83
+ ```js
84
+ import { safeFetch, SsrfError, FetchLimitError } from "ssrf-safe/node";
85
+
86
+ app.post("/preview", async (req, res) => {
87
+ try {
88
+ const page = await safeFetch(req.body.url, {}, { timeout: 5_000, maxBytes: 1_000_000 });
89
+ res.json({ status: page.status, html: await page.text() });
90
+ } catch (err) {
91
+ if (err instanceof SsrfError) return res.status(400).json({ error: err.message });
92
+ if (err instanceof FetchLimitError) return res.status(413).json({ error: err.message });
93
+ throw err;
94
+ }
95
+ });
96
+ ```
97
+
98
+ `safeFetch` takes the same arguments as `fetch` plus an options object, and returns a standard `Response`. It exists because Node's built-in `fetch` can't use a custom `http.Agent`, so it can't pin the connection to a checked address.
99
+
100
+ ### Webhooks: check when saving, check again when sending
101
+
102
+ ```js
103
+ import { checkUrl } from "ssrf-safe";
104
+ import { safeFetch } from "ssrf-safe/node";
105
+
106
+ // When the user saves the webhook: quick feedback, no network.
107
+ const check = checkUrl(input);
108
+ if (!check.safe) throw new Error(`Webhook URL not allowed: ${check.reason}`);
109
+ await db.saveWebhook(check.url.href); // store the normalised URL
110
+
111
+ // When you send it: DNS can change at any time, so check again.
112
+ await safeFetch(webhook.url, { method: "POST", body: JSON.stringify(event), headers: { "content-type": "application/json" } });
113
+ ```
114
+
115
+ ### Edge runtimes, Deno, Bun and browsers
116
+
117
+ ```js
118
+ import { safeFetch } from "ssrf-safe/fetch";
119
+
120
+ export default {
121
+ async fetch(request) {
122
+ const target = new URL(request.url).searchParams.get("url");
123
+ const res = await safeFetch(target, {}, { timeout: 5_000, maxBytes: 2_000_000 });
124
+ return new Response(res.body, { headers: { "content-type": res.headers.get("content-type") ?? "text/plain" } });
125
+ },
126
+ };
127
+ ```
128
+
129
+ This checks the URL and every redirect, but it can't see DNS. See [Limits](#limits).
130
+
131
+ ### axios and got
132
+
133
+ The safe agents check addresses at connect time, so every request and every redirect your client follows is covered.
134
+
135
+ ```js
136
+ import axios from "axios";
137
+ import got from "got";
138
+ import { createSafeAgent } from "ssrf-safe/node";
139
+
140
+ const agents = createSafeAgent();
141
+
142
+ const client = axios.create({
143
+ httpAgent: agents.http,
144
+ httpsAgent: agents.https,
145
+ proxy: false, // a proxy does its own DNS, which the agent can't check
146
+ maxRedirects: 5,
147
+ });
148
+
149
+ const body = await got("https://example.com/", { agent: agents }).text();
150
+ ```
151
+
152
+ With node:http directly:
153
+
154
+ ```js
155
+ import http from "node:http";
156
+ import { safeHttpAgent } from "ssrf-safe/node";
157
+
158
+ http.get("http://127.0.0.1/", { agent: safeHttpAgent }).on("error", (err) => {
159
+ console.log(err.message); // Blocked 127.0.0.1 is a loopback address
160
+ });
161
+ ```
162
+
163
+ ### An AI agent's "fetch a URL" tool
164
+
165
+ The model decides which URL to fetch, and a prompt injection can decide for it. Give the tool safe defaults and return a refusal the model can read.
166
+
167
+ ```js
168
+ import { safeFetch, SsrfError, FetchLimitError } from "ssrf-safe/node";
169
+
170
+ export const fetchUrlTool = {
171
+ name: "fetch_url",
172
+ description: "Fetch a public web page and return its text.",
173
+ input_schema: {
174
+ type: "object",
175
+ properties: { url: { type: "string", description: "An http or https URL" } },
176
+ required: ["url"],
177
+ },
178
+ async run({ url }) {
179
+ try {
180
+ const res = await safeFetch(url, {}, { timeout: 10_000, maxBytes: 2_000_000 });
181
+ return `HTTP ${res.status}\n\n${(await res.text()).slice(0, 50_000)}`;
182
+ } catch (err) {
183
+ if (err instanceof SsrfError || err instanceof FetchLimitError) return `Refused: ${err.message}`;
184
+ throw err;
185
+ }
186
+ },
187
+ };
188
+ ```
189
+
190
+ ### An MCP server
191
+
192
+ ```js
193
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
194
+ import { z } from "zod";
195
+ import { safeFetch, SsrfError } from "ssrf-safe/node";
196
+
197
+ const server = new McpServer({ name: "web", version: "1.0.0" });
198
+
199
+ server.registerTool(
200
+ "fetch_url",
201
+ { description: "Fetch a public web page", inputSchema: { url: z.string() } },
202
+ async ({ url }) => {
203
+ try {
204
+ const res = await safeFetch(url, {}, { timeout: 10_000, maxBytes: 2_000_000 });
205
+ return { content: [{ type: "text", text: await res.text() }] };
206
+ } catch (err) {
207
+ if (err instanceof SsrfError) return { content: [{ type: "text", text: err.message }], isError: true };
208
+ throw err;
209
+ }
210
+ },
211
+ );
212
+ ```
213
+
214
+ ### Local development
215
+
216
+ Your app may need to call `localhost` or a container in development. Turn on `allowPrivate` there only:
217
+
218
+ ```js
219
+ const options = { allowPrivate: process.env.NODE_ENV === "development" };
220
+ await safeFetch(url, {}, options);
221
+ ```
222
+
223
+ Cloud metadata stays blocked even with `allowPrivate`, so a config mistake in production can't expose it. To reach one specific internal service in production, list it in `allowHosts` instead.
224
+
225
+ ## What it blocks
226
+
227
+ | What | Examples | Rule |
228
+ |---|---|---|
229
+ | Loopback | `127.0.0.0/8`, `::1`, `localhost`, `*.localhost` | `private-ip`, `blocked-host` |
230
+ | Private networks | `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `100.64.0.0/10` (carrier-grade NAT), `fc00::/7` | `private-ip` |
231
+ | Link-local | `169.254.0.0/16`, `fe80::/10` | `private-ip` |
232
+ | Cloud metadata | `169.254.169.254`, `169.254.170.2`, `fd00:ec2::254`, `100.100.100.200`, `192.0.0.192`, `metadata.google.internal`, `metadata.goog`, `metadata`, `instance-data` | `private-ip`, `blocked-host` |
233
+ | Unspecified and "this network" | `0.0.0.0/8`, `::` | `private-ip` |
234
+ | Special-purpose IPv4 | `192.0.0.0/24`, `192.0.2.0/24`, `192.88.99.0/24`, `198.18.0.0/15`, `198.51.100.0/24`, `203.0.113.0/24`, `224.0.0.0/4`, `240.0.0.0/4`, `255.255.255.255` | `private-ip` |
235
+ | Special-purpose IPv6 | `100::/64`, `2001::/23` (including Teredo `2001::/32`), `2001:db8::/32`, `3fff::/20`, `5f00::/16`, `fec0::/10`, `ff00::/8`, and everything outside `2000::/3` | `private-ip` |
236
+ | IPv4 inside IPv6 | `::ffff:127.0.0.1`, `::ffff:7f00:1`, `::127.0.0.1`, `64:ff9b::7f00:1` (NAT64), `64:ff9b:1::/48`, `2002:7f00:1::` (6to4) | `private-ip` |
237
+ | Odd IPv4 spellings | `2130706433`, `0x7f000001`, `0177.0.0.1`, `0x7f.1`, `127.1`, `127.000.000.001`, `127.0.0.1.`, full-width and circled digits | `private-ip` |
238
+ | Internal hostnames | `*.internal`, `*.local`, `*.localdomain`, `*.home.arpa`, `*.svc`, `*.cluster.local`, `kubernetes.default.svc` | `blocked-host` |
239
+ | Single-label hostnames | `http://redis:6379/`, `http://intranet/` | `single-label` |
240
+ | Other schemes | `file:`, `gopher:`, `dict:`, `ftp:`, `ldap:`, `data:`, `javascript:`... (only `http` and `https` by default) | `protocol` |
241
+ | Credentials in the URL | `http://user:pass@example.com/`, `http://example.com@127.0.0.1/` | `credentials` |
242
+ | Redirect downgrades | an `https` URL that redirects to `http` | `downgrade` |
243
+ | Public names that resolve to any of the above | `127.0.0.1.nip.io`, a domain the attacker points at `10.0.0.1` | `private-ip` (Node entry only) |
244
+
245
+ Address ranges come from the IANA IPv4 and IPv6 Special-Purpose Address Registries. Mapped, NAT64 and 6to4 addresses are allowed when the IPv4 address inside them is public, because that's where they route.
246
+
247
+ `checkUrl` uses the standard WHATWG URL parser, the same one `fetch` uses, so it sees the host the request would really go to. `http://example.com\@127.0.0.1` goes to `example.com` and is allowed; `http://127.0.0.1#@example.com` goes to `127.0.0.1` and is blocked. If you pass a checked URL to another HTTP client, pass `result.url.href`, the normalised form, not the original string.
248
+
249
+ ## How it compares
250
+
251
+ Other SSRF tools on npm cover one layer each: an IP check, a URL check, or a Node.js HTTP agent. ssrf-safe covers all three, and works with `fetch`.
252
+
253
+ | | **ssrf-safe** | ssrfcheck | private-ip | request-filtering-agent | ssrf-req-filter |
254
+ |---|---|---|---|---|---|
255
+ | Checks a URL (scheme, credentials, host) | ✅ | ✅ | IP only | ❌ | ❌ |
256
+ | Blocks metadata and internal hostnames (`metadata.google.internal`, `*.localhost`, `*.svc`) | ✅ | ❌ | ❌ | ❌ | ❌ |
257
+ | IPv6 forms that hide IPv4 (`::ffff:127.0.0.1`, NAT64) | ✅ | ✅ | ❌ | ✅ | ✅ |
258
+ | Checks what a hostname resolves to (stops DNS rebinding) | ✅ Node.js | ❌ | ❌ | ✅ | ✅ |
259
+ | Works with Node.js's built-in `fetch` | ✅ `safeFetch` | URL check only | IP check only | ❌ needs an `http.Agent` | ❌ needs an `http.Agent` |
260
+ | Checks every redirect | ✅ | ❌ | ❌ | through the agent | through the agent |
261
+ | Response timeout and size limit | ✅ | ❌ | ❌ | ❌ | ❌ |
262
+ | Browsers and edge runtimes | ✅ URL check and `safeFetch` | ✅ | ✅ | ❌ | ❌ |
263
+ | Agents for axios and got | ✅ | ❌ | ❌ | ✅ | ✅ |
264
+ | Runtime dependencies | 0 | 0 | 0 | 1 | 1 |
265
+
266
+ We also ran the same 22 URLs through the three URL and IP checkers: loopback in decimal, octal, hex and short form, IPv6 and IPv4-mapped forms, NAT64, 6to4, cloud metadata addresses and hostnames, `localhost` and `*.localhost`, a Kubernetes service name, `file:` and `gopher:` URLs, a userinfo trick, and one public URL that must stay allowed.
267
+
268
+ | | Correct |
269
+ |---|---|
270
+ | **ssrf-safe** 1.0.0 | **22 / 22** |
271
+ | ssrfcheck 1.4.0 | 19 / 22: allowed `metadata.google.internal`, `app.localhost` and `kubernetes.default.svc` |
272
+ | private-ip 3.0.2 (on the hostname) | 14 / 22: allowed IPv4-mapped IPv6, NAT64, `localhost` names, metadata and service hostnames, and `file:` URLs |
273
+
274
+ The agent libraries were compared by their documented features rather than this URL list, because they check addresses only when a connection is made. Tested in November 2026 with the versions shown; other tools may have improved since.
275
+
276
+ ## API
277
+
278
+ ### `ssrf-safe`
279
+
280
+ | Function | Returns | What it does |
281
+ |---|---|---|
282
+ | `checkUrl(url, options?)` | `CheckResult` | Checks a URL without DNS. Synchronous. Never throws |
283
+ | `isSafeUrl(url, options?)` | `boolean` | `checkUrl(url, options).safe` |
284
+ | `classifyIp(ip)` | `IpRange` | The range an address is in: `"loopback"`, `"private"`, `"link-local"`, `"cloud-metadata"`, `"carrier-grade-nat"`, `"unique-local"`, `"multicast"`, `"reserved"`, `"unspecified"`, `"documentation"`, `"benchmarking"`, `"ipv4-mapped"`, `"nat64"`, `"6to4"`, `"teredo"`..., `"public"`, or `"invalid"` |
285
+ | `isPrivateIp(ip)` | `boolean` | True for anything that isn't a public address, including input that isn't an IP address at all |
286
+ | `normalizeIp(ip)` | `string \| undefined` | The canonical form: `normalizeIp("0x7f.1")` is `"127.0.0.1"` |
287
+ | `DEFAULT_BLOCKED_HOSTS` | `string[]` | The hostnames blocked by default |
288
+
289
+ `CheckResult` is `{ safe, rule?, reason?, url?, host?, ip?, range? }`. `url` is the parsed, normalised URL; `host` is its hostname (`"127.0.0.1"` for `http://0x7f.1/`); `ip` and `range` are set when the host is an IP address; `rule` and `reason` say why it was blocked.
290
+
291
+ ### `ssrf-safe/fetch`
292
+
293
+ | Function | Returns | What it does |
294
+ |---|---|---|
295
+ | `safeFetch(url, init?, options?)` | `Promise<Response>` | Checks the URL, fetches it with `redirect: "manual"`, and follows redirects itself, checking each one |
296
+
297
+ ### `ssrf-safe/node`
298
+
299
+ | Function | Returns | What it does |
300
+ |---|---|---|
301
+ | `safeFetch(url, init?, options?)` | `Promise<Response>` | Like the one above, plus DNS checks, built on node:http and node:https |
302
+ | `checkHost(hostname, options?)` | `Promise<{ safe, rule?, reason?, host, addresses }>` | Resolves a hostname and checks every address. Never throws |
303
+ | `createSafeAgent(options?)` | `{ http, https }` | A pair of safe agents, in the shape got's `agent` option takes |
304
+ | `safeHttpAgent`, `safeHttpsAgent` | agents | Shared agents with the default options |
305
+ | `SafeHttpAgent`, `SafeHttpsAgent` | classes | `http.Agent` and `https.Agent` subclasses. Take the check options plus any agent options |
306
+
307
+ The Node entry also exports everything from the main entry.
308
+
309
+ ### Errors
310
+
311
+ | Error | `code` | When |
312
+ |---|---|---|
313
+ | `SsrfError` | `"ERR_SSRF_BLOCKED"` | A URL, redirect or resolved address was blocked. `err.rule` says which check, and `err.url`, `err.host` and `err.ip` say what was blocked |
314
+ | `FetchLimitError` | `"ERR_TIMEOUT"`, `"ERR_MAX_BYTES"`, `"ERR_MAX_REDIRECTS"` | A limit was reached. Size and timeout errors can also come from reading the body (`await res.text()`) |
315
+
316
+ ## Options
317
+
318
+ | Option | Default | What it does |
319
+ |---|---|---|
320
+ | `protocols` | `["http", "https"]` | URL schemes to allow |
321
+ | `allowCredentials` | `false` | Allow `user:password@` in URLs |
322
+ | `ports` | any | Only allow these ports. The scheme's default port counts: `ports: [80, 443]` allows `https://example.com/` |
323
+ | `blockPorts` | none | Block these ports |
324
+ | `allowHosts` | `[]` | Hosts that skip the private-address and blocked-host checks: `"api.example.com"`, `"*.corp.example"` (subdomains only), `"10.1.2.3"` or `"10.1.2.0/24"`. A hostname listed here may resolve to private addresses, but not to cloud metadata ones unless that address is listed too |
325
+ | `blockHosts` | `[]` | Extra hosts to block, in the same forms. Wins over `allowHosts` |
326
+ | `allowPrivate` | `false` | Allow private, loopback and link-local addresses, internal hostnames and single-label hosts. For development. Cloud metadata stays blocked |
327
+ | `maxLength` | `8192` | Longest URL to accept, in characters |
328
+
329
+ `safeFetch` (both entries) also takes:
330
+
331
+ | Option | Default | What it does |
332
+ |---|---|---|
333
+ | `maxRedirects` | `5` | Most redirects to follow. Each one is checked like the first URL |
334
+ | `timeout` | `30000` | Time limit in milliseconds for the whole request, including reading the body. `0` turns it off |
335
+ | `maxBytes` | `10485760` (10 MiB) | Largest response body, after decompression. `Infinity` turns it off |
336
+ | `allowDowngrade` | `false` | Follow redirects from https to http |
337
+ | `fetch` | `globalThis.fetch` | `ssrf-safe/fetch` only: the fetch function to use |
338
+ | `resolve` | system DNS | `ssrf-safe/node` only: `(hostname) => Promise<string[]>`, for tests or custom DNS |
339
+ | `agentOptions` | none | `ssrf-safe/node` only: extra `https.Agent` options, such as `ca`, `cert` and `key` |
340
+
341
+ `safeFetch` honours `init.redirect`: `"follow"` (the default) follows and checks redirects, `"manual"` returns the redirect response without following it, and `"error"` throws on a redirect. When a redirect goes to another origin, the `Authorization`, `Cookie` and `Proxy-Authorization` headers are dropped. A `ReadableStream` body can't be sent twice, so a 307 or 308 redirect on such a request throws.
342
+
343
+ ## Limits
344
+
345
+ ssrf-safe is one layer of defense. Know what it can't do:
346
+
347
+ - **No DNS outside Node.js.** `ssrf-safe` and `ssrf-safe/fetch` can't see what a hostname resolves to. A public name that points at `127.0.0.1`, or changes its answer after the check (DNS rebinding), gets through. Use `ssrf-safe/node` on servers. On edge runtimes, the platform usually can't reach your private network anyway, but check that it's true for yours.
348
+ - **`checkUrl` then a separate fetch is racy.** The fetch resolves the name again. Use `safeFetch` or the safe agents, which connect to the address they checked.
349
+ - **Browsers hide redirect targets.** In a browser, `ssrf-safe/fetch` can't see where a redirect goes, so it refuses to follow redirects rather than follow them unchecked.
350
+ - **Proxies do their own DNS.** If requests go through an HTTP proxy, the agent checks the proxy's address, not the target's. Turn proxies off for these requests, or enforce the rules at the proxy.
351
+ - **It's not a firewall or a WAF.** Use it together with network-level egress rules: block metadata endpoints with IMDSv2 or a firewall rule, and keep the services that fetch user URLs in a network segment that can't reach your internal ones.
352
+ - **Allowed hosts are trusted.** A host in `allowHosts` can still redirect; the redirect target is checked, but what that host does with the request is up to it.
353
+
354
+ Found a URL or address that gets through? That's a vulnerability: please report it privately, as described in [SECURITY.md](SECURITY.md).
355
+
356
+ ## Contributing
357
+
358
+ **ssrf-safe is open source and contributions are welcome.** Good places to start:
359
+
360
+ - **Bypasses**: a URL, address or hostname that should be blocked but isn't. Report these privately; see [SECURITY.md](SECURITY.md).
361
+ - **False positives**: a safe URL that ssrf-safe blocks, reported with the ["Safe URL was blocked" template](https://github.com/ckgiri/ssrf-safe/issues/new?template=false-positive.yml).
362
+ - **Recipes** for more HTTP clients, frameworks and agent toolkits.
363
+ - **New checks and options**: share the idea in [Discussions](https://github.com/ckgiri/ssrf-safe/discussions) first.
364
+
365
+ ```bash
366
+ git clone https://github.com/ckgiri/ssrf-safe.git
367
+ cd ssrf-safe
368
+ npm install
369
+ npm test
370
+ ```
371
+
372
+ [CONTRIBUTING.md](CONTRIBUTING.md) covers setup, the project layout, and the rules that keep ssrf-safe safe (fail closed, test the bypass and the near miss, no network in tests). Everyone taking part follows the [Code of Conduct](CODE_OF_CONDUCT.md).
373
+
374
+ ## Changelog
375
+
376
+ See [CHANGELOG.md](CHANGELOG.md).
377
+
378
+ ## License
379
+
380
+ [MIT](LICENSE) © CK Giri