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.
@@ -0,0 +1,163 @@
1
+ import {
2
+ FetchLimitError,
3
+ SsrfError,
4
+ checkUrl
5
+ } from "./chunk-5WDHI7VU.js";
6
+
7
+ // src/shared.ts
8
+ var DEFAULT_MAX_REDIRECTS = 5;
9
+ var DEFAULT_TIMEOUT = 3e4;
10
+ var DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
11
+ function assertSafeUrl(input, options, context) {
12
+ const result = checkUrl(input, options);
13
+ if (!result.safe || !result.url) {
14
+ const where = context ? `${context}: ` : "";
15
+ const details = {
16
+ rule: result.rule ?? "invalid-url",
17
+ url: result.url?.href ?? String(input)
18
+ };
19
+ if (result.host !== void 0) details.host = result.host;
20
+ if (result.ip !== void 0) details.ip = result.ip;
21
+ throw new SsrfError(`Blocked ${where}${result.reason ?? "unsafe URL"}`, details);
22
+ }
23
+ return result.url;
24
+ }
25
+ function isRedirectStatus(status) {
26
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
27
+ }
28
+ var BODY_HEADERS = ["content-type", "content-length", "content-encoding", "content-language", "content-location"];
29
+ var CREDENTIAL_HEADERS = ["authorization", "cookie", "proxy-authorization"];
30
+ function planRedirect(state, status, location, options) {
31
+ let next;
32
+ try {
33
+ next = new URL(location, state.url);
34
+ } catch {
35
+ throw new SsrfError(`Blocked redirect: the Location header is not a valid URL`, {
36
+ rule: "invalid-url",
37
+ url: location
38
+ });
39
+ }
40
+ if (state.url.protocol === "https:" && next.protocol === "http:" && !options.allowDowngrade) {
41
+ throw new SsrfError(`Blocked redirect from https to http (${next.href})`, {
42
+ rule: "downgrade",
43
+ url: next.href,
44
+ host: next.hostname
45
+ });
46
+ }
47
+ const url = assertSafeUrl(next, options, "redirect");
48
+ let method = state.method;
49
+ let body = state.body;
50
+ const headers = new Headers(state.headers);
51
+ const upper = method.toUpperCase();
52
+ if ((status === 301 || status === 302) && upper === "POST" || status === 303 && upper !== "GET" && upper !== "HEAD") {
53
+ method = "GET";
54
+ body = null;
55
+ for (const h of BODY_HEADERS) headers.delete(h);
56
+ } else if (body !== null && state.streamed) {
57
+ throw new TypeError(`Can't follow a ${status} redirect: the request body is a stream and can't be sent again`);
58
+ }
59
+ if (url.origin !== state.url.origin) {
60
+ for (const h of CREDENTIAL_HEADERS) headers.delete(h);
61
+ }
62
+ return { url, method, headers, body, streamed: state.streamed && body !== null };
63
+ }
64
+ function tooManyRedirects(max, url) {
65
+ return new FetchLimitError(`Too many redirects (more than ${max})`, "ERR_MAX_REDIRECTS", url.href);
66
+ }
67
+ function tooLarge(max, url) {
68
+ return new FetchLimitError(`The response is larger than ${max} bytes`, "ERR_MAX_BYTES", url.href);
69
+ }
70
+ function createDeadline(timeout, userSignal) {
71
+ const controller = new AbortController();
72
+ let timer;
73
+ const onAbort = () => controller.abort(userSignal?.reason);
74
+ if (userSignal) {
75
+ if (userSignal.aborted) controller.abort(userSignal.reason);
76
+ else userSignal.addEventListener("abort", onAbort, { once: true });
77
+ }
78
+ if (timeout > 0 && Number.isFinite(timeout) && !controller.signal.aborted) {
79
+ timer = setTimeout(() => {
80
+ controller.abort(new FetchLimitError(`The request took longer than ${timeout} ms`, "ERR_TIMEOUT"));
81
+ }, timeout);
82
+ }
83
+ let finished = false;
84
+ return {
85
+ signal: controller.signal,
86
+ done() {
87
+ if (finished) return;
88
+ finished = true;
89
+ if (timer !== void 0) clearTimeout(timer);
90
+ userSignal?.removeEventListener("abort", onAbort);
91
+ },
92
+ reason() {
93
+ const r = controller.signal.reason;
94
+ return r ?? new DOMException("This operation was aborted", "AbortError");
95
+ }
96
+ };
97
+ }
98
+ function limitBody(source, maxBytes, url, deadline, onEnd) {
99
+ const reader = source.getReader();
100
+ let total = 0;
101
+ return new ReadableStream({
102
+ async pull(controller) {
103
+ try {
104
+ const { value, done } = await reader.read();
105
+ if (done) {
106
+ onEnd();
107
+ controller.close();
108
+ return;
109
+ }
110
+ total += value.byteLength;
111
+ if (total > maxBytes) {
112
+ const err = tooLarge(maxBytes, url);
113
+ reader.cancel(err).catch(() => {
114
+ });
115
+ onEnd();
116
+ controller.error(err);
117
+ return;
118
+ }
119
+ controller.enqueue(value);
120
+ } catch (err) {
121
+ onEnd();
122
+ controller.error(deadline.signal.aborted ? deadline.reason() : err);
123
+ }
124
+ },
125
+ cancel(reason) {
126
+ onEnd();
127
+ return reader.cancel(reason);
128
+ }
129
+ });
130
+ }
131
+ function buildResponse(body, init, url, redirected) {
132
+ const res = new Response(body, init);
133
+ Object.defineProperty(res, "url", { value: url.href, enumerable: true });
134
+ Object.defineProperty(res, "redirected", { value: redirected, enumerable: true });
135
+ return res;
136
+ }
137
+ function isNullBodyStatus(status) {
138
+ return status === 204 || status === 205 || status === 304;
139
+ }
140
+ function isReadableStream(value) {
141
+ return typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
142
+ }
143
+ function resolveLimits(options) {
144
+ return {
145
+ maxRedirects: options.maxRedirects ?? DEFAULT_MAX_REDIRECTS,
146
+ timeout: options.timeout ?? DEFAULT_TIMEOUT,
147
+ maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES
148
+ };
149
+ }
150
+
151
+ export {
152
+ assertSafeUrl,
153
+ isRedirectStatus,
154
+ planRedirect,
155
+ tooManyRedirects,
156
+ tooLarge,
157
+ createDeadline,
158
+ limitBody,
159
+ buildResponse,
160
+ isNullBodyStatus,
161
+ isReadableStream,
162
+ resolveLimits
163
+ };
package/dist/fetch.cjs ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+ var _chunkEDSDB6GKcjs = require('./chunk-EDSDB6GK.cjs');
14
+
15
+
16
+
17
+ var _chunk4CL2OZUYcjs = require('./chunk-4CL2OZUY.cjs');
18
+
19
+ // src/fetch.ts
20
+ async function safeFetch(input, init = {}, options = {}) {
21
+ const fetchImpl = _nullishCoalesce(options.fetch, () => ( globalThis.fetch));
22
+ if (typeof fetchImpl !== "function") throw new TypeError("No fetch implementation is available");
23
+ const limits = _chunkEDSDB6GKcjs.resolveLimits.call(void 0, options);
24
+ const mode = _nullishCoalesce(init.redirect, () => ( "follow"));
25
+ let state = {
26
+ url: _chunkEDSDB6GKcjs.assertSafeUrl.call(void 0, input, options),
27
+ method: _nullishCoalesce(init.method, () => ( "GET")),
28
+ headers: new Headers(init.headers),
29
+ body: _nullishCoalesce(init.body, () => ( null)),
30
+ streamed: _chunkEDSDB6GKcjs.isReadableStream.call(void 0, init.body)
31
+ };
32
+ const deadline = _chunkEDSDB6GKcjs.createDeadline.call(void 0, limits.timeout, init.signal);
33
+ let redirects = 0;
34
+ try {
35
+ for (; ; ) {
36
+ const requestInit = {
37
+ ...init,
38
+ method: state.method,
39
+ headers: state.headers,
40
+ body: state.body,
41
+ redirect: "manual",
42
+ signal: deadline.signal
43
+ };
44
+ if (state.streamed) requestInit.duplex = "half";
45
+ const res = await fetchImpl(state.url.href, requestInit);
46
+ if (res.type === "opaqueredirect") {
47
+ throw new (0, _chunk4CL2OZUYcjs.SsrfError)(
48
+ "Blocked redirect: this runtime hides redirect targets (browsers do), so the redirect can't be checked",
49
+ { rule: "redirect", url: state.url.href }
50
+ );
51
+ }
52
+ const location = res.headers.get("location");
53
+ if (mode !== "manual" && _chunkEDSDB6GKcjs.isRedirectStatus.call(void 0, res.status) && location !== null) {
54
+ await _optionalChain([res, 'access', _ => _.body, 'optionalAccess', _2 => _2.cancel, 'call', _3 => _3(), 'access', _4 => _4.catch, 'call', _5 => _5(() => {
55
+ })]);
56
+ if (mode === "error") throw new TypeError(`Unexpected redirect to ${location} (redirect: "error")`);
57
+ if (redirects >= limits.maxRedirects) throw _chunkEDSDB6GKcjs.tooManyRedirects.call(void 0, limits.maxRedirects, state.url);
58
+ state = _chunkEDSDB6GKcjs.planRedirect.call(void 0, state, res.status, location, options);
59
+ redirects++;
60
+ continue;
61
+ }
62
+ const length = Number(res.headers.get("content-length"));
63
+ if (res.body && !res.headers.has("content-encoding") && length > limits.maxBytes) {
64
+ await res.body.cancel().catch(() => {
65
+ });
66
+ throw _chunkEDSDB6GKcjs.tooLarge.call(void 0, limits.maxBytes, state.url);
67
+ }
68
+ const hasBody = res.body !== null && !_chunkEDSDB6GKcjs.isNullBodyStatus.call(void 0, res.status);
69
+ if (!hasBody) {
70
+ await _optionalChain([res, 'access', _6 => _6.body, 'optionalAccess', _7 => _7.cancel, 'call', _8 => _8(), 'access', _9 => _9.catch, 'call', _10 => _10(() => {
71
+ })]);
72
+ deadline.done();
73
+ }
74
+ const body = hasBody ? _chunkEDSDB6GKcjs.limitBody.call(void 0, res.body, limits.maxBytes, state.url, deadline, deadline.done) : null;
75
+ return _chunkEDSDB6GKcjs.buildResponse.call(void 0,
76
+ body,
77
+ { status: res.status, statusText: res.statusText, headers: res.headers },
78
+ state.url,
79
+ redirects > 0
80
+ );
81
+ }
82
+ } catch (err) {
83
+ deadline.done();
84
+ throw deadline.signal.aborted ? deadline.reason() : err;
85
+ }
86
+ }
87
+
88
+
89
+
90
+
91
+ exports.FetchLimitError = _chunk4CL2OZUYcjs.FetchLimitError; exports.SsrfError = _chunk4CL2OZUYcjs.SsrfError; exports.safeFetch = safeFetch;
@@ -0,0 +1,25 @@
1
+ import { CheckOptions } from './index.cjs';
2
+ export { FetchLimitError, SsrfError } from './index.cjs';
3
+ import { F as FetchLimits } from './shared-BGmNa6ne.cjs';
4
+
5
+ /**
6
+ * ssrf-safe/fetch: a `fetch` wrapper for any runtime that has `fetch`
7
+ * (Node.js 18+, Deno, Bun, Cloudflare Workers, Vercel Edge, browsers).
8
+ *
9
+ * It checks the URL and every redirect target, but it has no DNS: a public
10
+ * hostname that resolves to a private address (DNS rebinding) gets through.
11
+ * In Node.js, use `ssrf-safe/node`, which checks resolved addresses too.
12
+ */
13
+
14
+ interface SafeFetchOptions extends CheckOptions, FetchLimits {
15
+ /** The fetch implementation to use. Default `globalThis.fetch`. */
16
+ fetch?: typeof fetch;
17
+ }
18
+ /**
19
+ * Fetches a URL after checking it, and follows redirects itself so that every
20
+ * hop is checked too. Throws `SsrfError` when a URL or redirect is blocked and
21
+ * `FetchLimitError` on the timeout, size or redirect limits.
22
+ */
23
+ declare function safeFetch(input: string | URL, init?: RequestInit, options?: SafeFetchOptions): Promise<Response>;
24
+
25
+ export { CheckOptions, FetchLimits, type SafeFetchOptions, safeFetch };
@@ -0,0 +1,25 @@
1
+ import { CheckOptions } from './index.js';
2
+ export { FetchLimitError, SsrfError } from './index.js';
3
+ import { F as FetchLimits } from './shared-BGmNa6ne.js';
4
+
5
+ /**
6
+ * ssrf-safe/fetch: a `fetch` wrapper for any runtime that has `fetch`
7
+ * (Node.js 18+, Deno, Bun, Cloudflare Workers, Vercel Edge, browsers).
8
+ *
9
+ * It checks the URL and every redirect target, but it has no DNS: a public
10
+ * hostname that resolves to a private address (DNS rebinding) gets through.
11
+ * In Node.js, use `ssrf-safe/node`, which checks resolved addresses too.
12
+ */
13
+
14
+ interface SafeFetchOptions extends CheckOptions, FetchLimits {
15
+ /** The fetch implementation to use. Default `globalThis.fetch`. */
16
+ fetch?: typeof fetch;
17
+ }
18
+ /**
19
+ * Fetches a URL after checking it, and follows redirects itself so that every
20
+ * hop is checked too. Throws `SsrfError` when a URL or redirect is blocked and
21
+ * `FetchLimitError` on the timeout, size or redirect limits.
22
+ */
23
+ declare function safeFetch(input: string | URL, init?: RequestInit, options?: SafeFetchOptions): Promise<Response>;
24
+
25
+ export { CheckOptions, FetchLimits, type SafeFetchOptions, safeFetch };
package/dist/fetch.js ADDED
@@ -0,0 +1,91 @@
1
+ import {
2
+ assertSafeUrl,
3
+ buildResponse,
4
+ createDeadline,
5
+ isNullBodyStatus,
6
+ isReadableStream,
7
+ isRedirectStatus,
8
+ limitBody,
9
+ planRedirect,
10
+ resolveLimits,
11
+ tooLarge,
12
+ tooManyRedirects
13
+ } from "./chunk-LI4OVIRR.js";
14
+ import {
15
+ FetchLimitError,
16
+ SsrfError
17
+ } from "./chunk-5WDHI7VU.js";
18
+
19
+ // src/fetch.ts
20
+ async function safeFetch(input, init = {}, options = {}) {
21
+ const fetchImpl = options.fetch ?? globalThis.fetch;
22
+ if (typeof fetchImpl !== "function") throw new TypeError("No fetch implementation is available");
23
+ const limits = resolveLimits(options);
24
+ const mode = init.redirect ?? "follow";
25
+ let state = {
26
+ url: assertSafeUrl(input, options),
27
+ method: init.method ?? "GET",
28
+ headers: new Headers(init.headers),
29
+ body: init.body ?? null,
30
+ streamed: isReadableStream(init.body)
31
+ };
32
+ const deadline = createDeadline(limits.timeout, init.signal);
33
+ let redirects = 0;
34
+ try {
35
+ for (; ; ) {
36
+ const requestInit = {
37
+ ...init,
38
+ method: state.method,
39
+ headers: state.headers,
40
+ body: state.body,
41
+ redirect: "manual",
42
+ signal: deadline.signal
43
+ };
44
+ if (state.streamed) requestInit.duplex = "half";
45
+ const res = await fetchImpl(state.url.href, requestInit);
46
+ if (res.type === "opaqueredirect") {
47
+ throw new SsrfError(
48
+ "Blocked redirect: this runtime hides redirect targets (browsers do), so the redirect can't be checked",
49
+ { rule: "redirect", url: state.url.href }
50
+ );
51
+ }
52
+ const location = res.headers.get("location");
53
+ if (mode !== "manual" && isRedirectStatus(res.status) && location !== null) {
54
+ await res.body?.cancel().catch(() => {
55
+ });
56
+ if (mode === "error") throw new TypeError(`Unexpected redirect to ${location} (redirect: "error")`);
57
+ if (redirects >= limits.maxRedirects) throw tooManyRedirects(limits.maxRedirects, state.url);
58
+ state = planRedirect(state, res.status, location, options);
59
+ redirects++;
60
+ continue;
61
+ }
62
+ const length = Number(res.headers.get("content-length"));
63
+ if (res.body && !res.headers.has("content-encoding") && length > limits.maxBytes) {
64
+ await res.body.cancel().catch(() => {
65
+ });
66
+ throw tooLarge(limits.maxBytes, state.url);
67
+ }
68
+ const hasBody = res.body !== null && !isNullBodyStatus(res.status);
69
+ if (!hasBody) {
70
+ await res.body?.cancel().catch(() => {
71
+ });
72
+ deadline.done();
73
+ }
74
+ const body = hasBody ? limitBody(res.body, limits.maxBytes, state.url, deadline, deadline.done) : null;
75
+ return buildResponse(
76
+ body,
77
+ { status: res.status, statusText: res.statusText, headers: res.headers },
78
+ state.url,
79
+ redirects > 0
80
+ );
81
+ }
82
+ } catch (err) {
83
+ deadline.done();
84
+ throw deadline.signal.aborted ? deadline.reason() : err;
85
+ }
86
+ }
87
+ export {
88
+ FetchLimitError,
89
+ SsrfError,
90
+ safeFetch
91
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+ var _chunk4CL2OZUYcjs = require('./chunk-4CL2OZUY.cjs');
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ exports.DEFAULT_BLOCKED_HOSTS = _chunk4CL2OZUYcjs.DEFAULT_BLOCKED_HOSTS; exports.FetchLimitError = _chunk4CL2OZUYcjs.FetchLimitError; exports.SsrfError = _chunk4CL2OZUYcjs.SsrfError; exports.checkUrl = _chunk4CL2OZUYcjs.checkUrl; exports.classifyIp = _chunk4CL2OZUYcjs.classifyIp; exports.isPrivateIp = _chunk4CL2OZUYcjs.isPrivateIp; exports.isSafeUrl = _chunk4CL2OZUYcjs.isSafeUrl; exports.normalizeIp = _chunk4CL2OZUYcjs.normalizeIp;
@@ -0,0 +1,113 @@
1
+ /** Why a URL, host or address was blocked. */
2
+ type BlockRule = "invalid-url" | "too-long" | "protocol" | "credentials" | "port" | "private-ip" | "blocked-host" | "single-label" | "dns" | "downgrade" | "redirect";
3
+ /** Thrown when a request is blocked: the URL, a redirect, or a resolved address isn't allowed. */
4
+ declare class SsrfError extends Error {
5
+ name: string;
6
+ readonly code = "ERR_SSRF_BLOCKED";
7
+ readonly rule: BlockRule;
8
+ readonly url?: string;
9
+ readonly host?: string;
10
+ readonly ip?: string;
11
+ constructor(reason: string, details: {
12
+ rule: BlockRule;
13
+ url?: string;
14
+ host?: string;
15
+ ip?: string;
16
+ });
17
+ }
18
+ type LimitCode = "ERR_TIMEOUT" | "ERR_MAX_BYTES" | "ERR_MAX_REDIRECTS";
19
+ /** Thrown when a request goes over the timeout, the size limit or the redirect limit. */
20
+ declare class FetchLimitError extends Error {
21
+ name: string;
22
+ readonly code: LimitCode;
23
+ readonly url?: string;
24
+ constructor(message: string, code: LimitCode, url?: string);
25
+ }
26
+
27
+ /**
28
+ * IP address parsing and classification. No dependencies and no runtime APIs,
29
+ * so it works in Node.js, browsers, edge runtimes, Deno and Bun.
30
+ */
31
+ /** The special-purpose range an address belongs to, or "public". */
32
+ type IpRange = "public" | "unspecified" | "this-network" | "loopback" | "private" | "carrier-grade-nat" | "link-local" | "cloud-metadata" | "reserved" | "documentation" | "benchmarking" | "multicast" | "broadcast" | "unique-local" | "site-local" | "discard" | "ipv4-mapped" | "ipv4-compatible" | "nat64" | "6to4" | "teredo" | "invalid";
33
+ /**
34
+ * Returns the special-purpose range an IP address belongs to ("loopback",
35
+ * "private", "cloud-metadata"...), "public" for ordinary internet addresses,
36
+ * or "invalid" when the input isn't an IP address.
37
+ *
38
+ * Accepts IPv4 in every form inet_aton accepts (decimal, octal, hex, shortened)
39
+ * and IPv6 with or without brackets and zone IDs.
40
+ */
41
+ declare function classifyIp(ip: string): IpRange;
42
+ /**
43
+ * True for any address that isn't a public internet address: private,
44
+ * loopback, link-local, cloud metadata, reserved and the rest. Also true when
45
+ * the input isn't an IP address at all, so a mistake fails closed.
46
+ */
47
+ declare function isPrivateIp(ip: string): boolean;
48
+ /** The canonical form of an IP address, or undefined when the input isn't one. */
49
+ declare function normalizeIp(ip: string): string | undefined;
50
+
51
+ /**
52
+ * URL and hostname checks without DNS. Shared by every entry.
53
+ */
54
+
55
+ interface CheckOptions {
56
+ /** URL schemes to allow, without the colon. Default `["http", "https"]`. */
57
+ protocols?: string[];
58
+ /** Allow `user:password@` in URLs. Default `false`. */
59
+ allowCredentials?: boolean;
60
+ /** Only allow these ports (the scheme's default port counts, e.g. 443 for https). Default: any port. */
61
+ ports?: number[];
62
+ /** Block these ports. Default: none. */
63
+ blockPorts?: number[];
64
+ /**
65
+ * Hosts that are always allowed, skipping the private-address and blocked-host
66
+ * checks: `"api.internal.example"`, `"*.corp.example"` for subdomains,
67
+ * an IP address, or a CIDR range such as `"10.1.2.0/24"`. A hostname listed here
68
+ * may resolve to private addresses, but not to cloud metadata ones unless that
69
+ * address is listed too.
70
+ */
71
+ allowHosts?: string[];
72
+ /** Extra hosts to block, in the same forms as `allowHosts`. Wins over `allowHosts`. */
73
+ blockHosts?: string[];
74
+ /**
75
+ * Allow private, loopback and other internal addresses, `localhost` and
76
+ * single-label hosts. For development. Cloud metadata addresses and
77
+ * hostnames stay blocked; list them in `allowHosts` if you really need them.
78
+ */
79
+ allowPrivate?: boolean;
80
+ /** Longest URL to accept, in characters. Default 8192. */
81
+ maxLength?: number;
82
+ }
83
+ interface CheckResult {
84
+ /** True when the URL may be fetched. */
85
+ safe: boolean;
86
+ /** Which check blocked it. */
87
+ rule?: BlockRule;
88
+ /** Why it was blocked, in plain English. */
89
+ reason?: string;
90
+ /** The parsed URL, when it could be parsed. */
91
+ url?: URL;
92
+ /** The hostname as the URL parser normalised it, e.g. "127.0.0.1" for "http://0x7f.1/". */
93
+ host?: string;
94
+ /** The IP address, when the host is an IP literal. */
95
+ ip?: string;
96
+ /** The address range, when the host is an IP literal. */
97
+ range?: IpRange;
98
+ }
99
+ /** Every hostname blocked by default. */
100
+ declare const DEFAULT_BLOCKED_HOSTS: readonly string[];
101
+ /**
102
+ * Checks a URL before you fetch it. Synchronous and DNS-free, so it works in
103
+ * every runtime. It catches private and internal IP addresses in every
104
+ * encoding, blocked hostnames, disallowed schemes, ports and credentials.
105
+ *
106
+ * It can't see what a hostname resolves to. In Node.js, use `ssrf-safe/node`,
107
+ * which also checks the resolved addresses and pins the connection to them.
108
+ */
109
+ declare function checkUrl(input: string | URL, options?: CheckOptions): CheckResult;
110
+ /** `checkUrl(url, options).safe`. */
111
+ declare function isSafeUrl(input: string | URL, options?: CheckOptions): boolean;
112
+
113
+ export { type BlockRule, type CheckOptions, type CheckResult, DEFAULT_BLOCKED_HOSTS, FetchLimitError, type IpRange, type LimitCode, SsrfError, checkUrl, classifyIp, isPrivateIp, isSafeUrl, normalizeIp };
@@ -0,0 +1,113 @@
1
+ /** Why a URL, host or address was blocked. */
2
+ type BlockRule = "invalid-url" | "too-long" | "protocol" | "credentials" | "port" | "private-ip" | "blocked-host" | "single-label" | "dns" | "downgrade" | "redirect";
3
+ /** Thrown when a request is blocked: the URL, a redirect, or a resolved address isn't allowed. */
4
+ declare class SsrfError extends Error {
5
+ name: string;
6
+ readonly code = "ERR_SSRF_BLOCKED";
7
+ readonly rule: BlockRule;
8
+ readonly url?: string;
9
+ readonly host?: string;
10
+ readonly ip?: string;
11
+ constructor(reason: string, details: {
12
+ rule: BlockRule;
13
+ url?: string;
14
+ host?: string;
15
+ ip?: string;
16
+ });
17
+ }
18
+ type LimitCode = "ERR_TIMEOUT" | "ERR_MAX_BYTES" | "ERR_MAX_REDIRECTS";
19
+ /** Thrown when a request goes over the timeout, the size limit or the redirect limit. */
20
+ declare class FetchLimitError extends Error {
21
+ name: string;
22
+ readonly code: LimitCode;
23
+ readonly url?: string;
24
+ constructor(message: string, code: LimitCode, url?: string);
25
+ }
26
+
27
+ /**
28
+ * IP address parsing and classification. No dependencies and no runtime APIs,
29
+ * so it works in Node.js, browsers, edge runtimes, Deno and Bun.
30
+ */
31
+ /** The special-purpose range an address belongs to, or "public". */
32
+ type IpRange = "public" | "unspecified" | "this-network" | "loopback" | "private" | "carrier-grade-nat" | "link-local" | "cloud-metadata" | "reserved" | "documentation" | "benchmarking" | "multicast" | "broadcast" | "unique-local" | "site-local" | "discard" | "ipv4-mapped" | "ipv4-compatible" | "nat64" | "6to4" | "teredo" | "invalid";
33
+ /**
34
+ * Returns the special-purpose range an IP address belongs to ("loopback",
35
+ * "private", "cloud-metadata"...), "public" for ordinary internet addresses,
36
+ * or "invalid" when the input isn't an IP address.
37
+ *
38
+ * Accepts IPv4 in every form inet_aton accepts (decimal, octal, hex, shortened)
39
+ * and IPv6 with or without brackets and zone IDs.
40
+ */
41
+ declare function classifyIp(ip: string): IpRange;
42
+ /**
43
+ * True for any address that isn't a public internet address: private,
44
+ * loopback, link-local, cloud metadata, reserved and the rest. Also true when
45
+ * the input isn't an IP address at all, so a mistake fails closed.
46
+ */
47
+ declare function isPrivateIp(ip: string): boolean;
48
+ /** The canonical form of an IP address, or undefined when the input isn't one. */
49
+ declare function normalizeIp(ip: string): string | undefined;
50
+
51
+ /**
52
+ * URL and hostname checks without DNS. Shared by every entry.
53
+ */
54
+
55
+ interface CheckOptions {
56
+ /** URL schemes to allow, without the colon. Default `["http", "https"]`. */
57
+ protocols?: string[];
58
+ /** Allow `user:password@` in URLs. Default `false`. */
59
+ allowCredentials?: boolean;
60
+ /** Only allow these ports (the scheme's default port counts, e.g. 443 for https). Default: any port. */
61
+ ports?: number[];
62
+ /** Block these ports. Default: none. */
63
+ blockPorts?: number[];
64
+ /**
65
+ * Hosts that are always allowed, skipping the private-address and blocked-host
66
+ * checks: `"api.internal.example"`, `"*.corp.example"` for subdomains,
67
+ * an IP address, or a CIDR range such as `"10.1.2.0/24"`. A hostname listed here
68
+ * may resolve to private addresses, but not to cloud metadata ones unless that
69
+ * address is listed too.
70
+ */
71
+ allowHosts?: string[];
72
+ /** Extra hosts to block, in the same forms as `allowHosts`. Wins over `allowHosts`. */
73
+ blockHosts?: string[];
74
+ /**
75
+ * Allow private, loopback and other internal addresses, `localhost` and
76
+ * single-label hosts. For development. Cloud metadata addresses and
77
+ * hostnames stay blocked; list them in `allowHosts` if you really need them.
78
+ */
79
+ allowPrivate?: boolean;
80
+ /** Longest URL to accept, in characters. Default 8192. */
81
+ maxLength?: number;
82
+ }
83
+ interface CheckResult {
84
+ /** True when the URL may be fetched. */
85
+ safe: boolean;
86
+ /** Which check blocked it. */
87
+ rule?: BlockRule;
88
+ /** Why it was blocked, in plain English. */
89
+ reason?: string;
90
+ /** The parsed URL, when it could be parsed. */
91
+ url?: URL;
92
+ /** The hostname as the URL parser normalised it, e.g. "127.0.0.1" for "http://0x7f.1/". */
93
+ host?: string;
94
+ /** The IP address, when the host is an IP literal. */
95
+ ip?: string;
96
+ /** The address range, when the host is an IP literal. */
97
+ range?: IpRange;
98
+ }
99
+ /** Every hostname blocked by default. */
100
+ declare const DEFAULT_BLOCKED_HOSTS: readonly string[];
101
+ /**
102
+ * Checks a URL before you fetch it. Synchronous and DNS-free, so it works in
103
+ * every runtime. It catches private and internal IP addresses in every
104
+ * encoding, blocked hostnames, disallowed schemes, ports and credentials.
105
+ *
106
+ * It can't see what a hostname resolves to. In Node.js, use `ssrf-safe/node`,
107
+ * which also checks the resolved addresses and pins the connection to them.
108
+ */
109
+ declare function checkUrl(input: string | URL, options?: CheckOptions): CheckResult;
110
+ /** `checkUrl(url, options).safe`. */
111
+ declare function isSafeUrl(input: string | URL, options?: CheckOptions): boolean;
112
+
113
+ export { type BlockRule, type CheckOptions, type CheckResult, DEFAULT_BLOCKED_HOSTS, FetchLimitError, type IpRange, type LimitCode, SsrfError, checkUrl, classifyIp, isPrivateIp, isSafeUrl, normalizeIp };
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ import {
2
+ DEFAULT_BLOCKED_HOSTS,
3
+ FetchLimitError,
4
+ SsrfError,
5
+ checkUrl,
6
+ classifyIp,
7
+ isPrivateIp,
8
+ isSafeUrl,
9
+ normalizeIp
10
+ } from "./chunk-5WDHI7VU.js";
11
+ export {
12
+ DEFAULT_BLOCKED_HOSTS,
13
+ FetchLimitError,
14
+ SsrfError,
15
+ checkUrl,
16
+ classifyIp,
17
+ isPrivateIp,
18
+ isSafeUrl,
19
+ normalizeIp
20
+ };