import dns from 'node:dns' import http from 'node:http' import https from 'node:https' import net from 'node:net' import { Readable, Transform } from 'node:stream' import { isPublicAddress } from './publicAddress.ts' const MAX_REDIRECTS = 5 const REDIRECTS = new Set([301, 302, 303, 307, 308]) const NO_BODY = new Set([204, 205, 304]) const TIMEOUT_MS = 60_000 const IDLE_TIMEOUT_MS = 30_000 const MAX_BYTES = 50 * 1024 * 1024 export type PublicFetchOptions = { /** * The addresses to refuse. Defaults to the ranges {@link isPublicAddress} refuses. */ blocked?: net.BlockList } class NotPublicAddressError extends Error { override name = 'NotPublicAddressError' constructor(host: string) { super(`${host} is not a public address, so Kubb does not fetch from it`) } } /** * Whether `error`, or an error on its `cause` chain, is a {@link createPublicFetch} refusal of a host that is not public. * It checks the `name`, since each package bundles its own copy of this module. */ export function isNotPublicAddressError(error: unknown): boolean { let current = error for (let depth = 0; depth < 16 && typeof current === 'object' && current !== null; depth++) { if ((current as { name?: unknown }).name === 'NotPublicAddressError') return true current = (current as { cause?: unknown }).cause } return false } function createLookup(blocked?: net.BlockList): net.LookupFunction { return (hostname, options, callback) => { dns.lookup(hostname, { ...options, all: true }, (error, addresses) => { if (error) return callback(error, '', 0) const found = addresses as Array // One private answer is enough to refuse, so a name cannot mix a public and a private record. if (!found.length || found.some(({ address }) => !isPublicAddress(address, blocked))) return callback(new NotPublicAddressError(hostname), '', 0) return options.all ? callback(null, found) : callback(null, found[0]!.address, found[0]!.family) }) } } class Download { readonly #url: URL readonly #blocked: net.BlockList | undefined readonly #signal: AbortSignal #req: http.ClientRequest | undefined #body: Transform | undefined constructor({ url, blocked, signal }: { url: URL; blocked?: net.BlockList; signal: AbortSignal }) { this.#url = url this.#blocked = blocked this.#signal = signal } // After the headers, `req.destroy` and the `signal` option drop the body silently, so a cut body would read as complete. #fail(error: Error): void { const target = this.#body ?? this.#req target?.destroy(error) } readonly #abort = (): void => this.#fail(this.#signal.reason) start(): Promise { const url = this.#url const signal = this.#signal if (url.protocol !== 'http:' && url.protocol !== 'https:') return Promise.reject(new Error(`Only http and https URLs are fetched, not ${url.protocol}`)) const host = url.hostname.replace(/^\[|\]$/g, '') if (net.isIP(host) && !isPublicAddress(host, this.#blocked)) return Promise.reject(new NotPublicAddressError(host)) if (signal.aborted) return Promise.reject(signal.reason) return new Promise((resolve, reject) => { signal.addEventListener('abort', this.#abort, { once: true }) const settle = (error: Error) => { signal.removeEventListener('abort', this.#abort) reject(error) } const send = url.protocol === 'https:' ? https.request : http.request // The lookup runs for the connection itself, so a host cannot switch to a private address after a check. // `agent: false` keeps an env proxy (NODE_USE_ENV_PROXY) from connecting instead and skipping the lookup. const req = send(url, { method: 'GET', agent: false, lookup: createLookup(this.#blocked), headers: { 'accept-encoding': 'identity' } }, (res) => { const status = res.statusCode ?? 0 // `new Response` throws for these, outside this promise. if (status < 200 || status > 599) { res.destroy() return settle(new Error(`${url.host} answered with HTTP ${status}, which the public-only fetch does not support`)) } resolve(this.#respond(res)) }) this.#req = req req.setTimeout(IDLE_TIMEOUT_MS, () => this.#fail(new Error(`${url.host} sent nothing for ${IDLE_TIMEOUT_MS / 1000} seconds`))) req.on('upgrade', (_res, socket) => { socket.destroy() settle(new Error(`${url.host} switched protocols, which the public-only fetch does not support`)) }) req.on('error', settle) // Without it, a connection that closes before a response never settles. req.on('close', () => { if (!this.#body) settle(new Error(`${url.host} closed the connection before it answered`)) }) req.end() }) } #respond(res: http.IncomingMessage): Response { const headers = new Headers() for (const [key, value] of Object.entries(res.headers)) { for (const item of [value].flat()) if (item !== undefined) headers.append(key, item) } let total = 0 const limit = new Transform({ transform(chunk: Buffer, _encoding, done) { total += chunk.length done(total > MAX_BYTES ? new Error('The response is larger than 50 MB') : null, chunk) }, }) this.#body = limit res.on('error', (error) => limit.destroy(error)) limit.on('close', () => { this.#signal.removeEventListener('abort', this.#abort) res.destroy() }) const init = { status: res.statusCode, statusText: res.statusMessage, headers } if (NO_BODY.has(res.statusCode ?? 0)) { limit.destroy() return new Response(null, init) } res.pipe(limit) return new Response(Readable.toWeb(limit) as unknown as ReadableStream, init) } } class PublicFetch { readonly #blocked: net.BlockList | undefined constructor({ blocked }: PublicFetchOptions = {}) { this.#blocked = blocked } readonly fetch = async (input: Parameters[0], init?: RequestInit): Promise => { let url = toGetUrl({ input, init }) const signal = withDeadline(init?.signal) for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { const response = await new Download({ url, blocked: this.#blocked, signal }).start() const next = redirectOf({ response, url }) if (!next) return response await response.body?.cancel() assertNoDowngrade({ url, next }) url = next } throw new Error(`Stopped after ${MAX_REDIRECTS} redirects from ${String(input)}`) } } function toGetUrl({ input, init }: { input: Parameters[0]; init?: RequestInit }): URL { if (typeof input !== 'string' && !(input instanceof URL)) throw new TypeError('The public-only fetch takes a URL, not a Request') if (init?.method && init.method.toUpperCase() !== 'GET') throw new TypeError('The public-only fetch only sends GET requests') return new URL(input) } function withDeadline(signal: AbortSignal | null | undefined): AbortSignal { const timeout = AbortSignal.timeout(TIMEOUT_MS) return signal ? AbortSignal.any([signal, timeout]) : timeout } function redirectOf({ response, url }: { response: Response; url: URL }): URL | undefined { const location = response.headers.get('location') return REDIRECTS.has(response.status) && location ? new URL(location, url) : undefined } function assertNoDowngrade({ url, next }: { url: URL; next: URL }): void { if (url.protocol === 'https:' && next.protocol === 'http:') throw new Error(`Refused a redirect from https to http: ${next.href}`) } /** * Builds a GET-only `fetch` that reaches public addresses only, checked on every connection and * redirect. It stops after 60 seconds, 30 seconds without data, or 50 MB, and refuses an https to * http redirect. It connects directly and does not use HTTP_PROXY or HTTPS_PROXY. * * @example * ```ts * const response = await createPublicFetch()('https://petstore3.swagger.io/api/v3/openapi.json') * ``` */ export function createPublicFetch(options: PublicFetchOptions = {}): typeof fetch { return new PublicFetch(options).fetch as typeof fetch }