api/src/lib/page.ts

131 lines · 4573 bytes

13 symbols in this file
  1/**
  2 * Fetches the HTML of a public web page, for enrich routes that inspect websites.
  3 * Unlike fetchJson the host is arbitrary, so IPs, local names, custom ports and
  4 * hosts resolving to private addresses are refused, each redirect hop is
  5 * re-checked, and the body is capped in size.
  6 */
  7
  8import { ApiError } from '@/lib/errors'
  9import { log } from '@/lib/log'
 10
 11const MAX_BYTES = 2_000_000
 12const MAX_REDIRECTS = 5
 13const TIMEOUT_MS = 10000
 14const USER_AGENT =
 15  'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0'
 16const LOCAL_SUFFIXES = ['.localhost', '.local', '.internal', '.lan', '.home.arpa']
 17
 18export interface Page {
 19  // Where the page ended up, after any redirects
 20  url: string
 21  html: string
 22}
 23
 24// Only plain http(s) on public hostnames and default ports, never IPs or local names
 25export const isPublicUrl = (url: URL) => {
 26  const host = url.hostname.toLowerCase().replace(/\.$/, '')
 27  return (
 28    ['http:', 'https:'].includes(url.protocol) &&
 29    !url.port &&
 30    !url.username &&
 31    !url.password &&
 32    host.includes('.') &&
 33    !/^[\d.]+$/.test(host) &&
 34    !host.startsWith('[') &&
 35    !LOCAL_SUFFIXES.some((suffix) => host.endsWith(suffix))
 36  )
 37}
 38
 39// IPv4 blocks that are never public (RFC 6890): private, loopback, link-local,
 40// shared CGNAT, benchmarking, multicast and reserved ranges
 41const PRIVATE_V4: [string, number][] = [
 42  ['0.0.0.0', 8],
 43  ['10.0.0.0', 8],
 44  ['100.64.0.0', 10],
 45  ['127.0.0.0', 8],
 46  ['169.254.0.0', 16],
 47  ['172.16.0.0', 12],
 48  ['192.0.0.0', 24],
 49  ['192.168.0.0', 16],
 50  ['198.18.0.0', 15],
 51  ['224.0.0.0', 3],
 52]
 53
 54const v4ToInt = (ip: string) =>
 55  ip.split('.').reduce((n, part) => n * 256 + Number(part), 0)
 56
 57// Special IPv6 (anything under ::, unique-local, link-local, NAT64) or private IPv4
 58export const isPrivateIp = (ip: string) => {
 59  const addr = ip.toLowerCase()
 60  if (addr.includes(':')) return /^(::|fc|fd|fe[89a-f]|64:ff9b:)/.test(addr)
 61  return PRIVATE_V4.some(
 62    ([base, bits]) => v4ToInt(addr) >>> (32 - bits) === v4ToInt(base) >>> (32 - bits),
 63  )
 64}
 65
 66// Workers can't reach private networks, elsewhere refuse hosts that resolve to them.
 67// Fetch resolves again, so this blocks static records (like localtest.me), not fast rebinding.
 68const resolvesPrivate = async (host: string) => {
 69  if (globalThis.navigator?.userAgent === 'Cloudflare-Workers') return false
 70  const { lookup } = await import('node:dns/promises')
 71  const addresses = await lookup(host, { all: true })
 72  return addresses.some(({ address }) => isPrivateIp(address))
 73}
 74
 75// Read at most MAX_BYTES of the body, then stop downloading
 76const readCapped = async (res: Response) => {
 77  const reader = res.body?.getReader()
 78  if (!reader) return ''
 79  const decoder = new TextDecoder()
 80  let html = ''
 81  let size = 0
 82  while (size < MAX_BYTES) {
 83    const { done, value } = await reader.read()
 84    if (done) break
 85    const chunk = value.subarray(0, MAX_BYTES - size)
 86    size += chunk.byteLength
 87    html += decoder.decode(chunk, { stream: true })
 88  }
 89  await reader.cancel()
 90  return html
 91}
 92
 93export const fetchPage = async (target: string): Promise<Page> => {
 94  const signal = AbortSignal.timeout(TIMEOUT_MS)
 95  let url = new URL(target)
 96  try {
 97    for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
 98      if (!isPublicUrl(url) || (await resolvesPrivate(url.hostname))) {
 99        throw new ApiError('BAD_REQUEST', `URL not allowed: ${url.hostname}`, 400)
100      }
101      const res = await fetch(url, {
102        headers: { 'User-Agent': USER_AGENT, Accept: 'text/html' },
103        redirect: 'manual',
104        signal,
105      })
106      const location = res.headers.get('location')
107      if (res.status >= 300 && res.status < 400 && location) {
108        await res.body?.cancel()
109        url = new URL(location, url)
110        continue
111      }
112      // Only a 200 is the page itself, other 2xx are interstitials
113      if (res.status !== 200) {
114        throw new ApiError(
115          'UPSTREAM_ERROR',
116          `${url.hostname} returned ${res.status}`,
117          502,
118        )
119      }
120      if (!res.headers.get('content-type')?.includes('html')) {
121        throw new ApiError('UPSTREAM_ERROR', `${url.hostname} did not return HTML`, 502)
122      }
123      return { url: url.href, html: await readCapped(res) }
124    }
125    throw new ApiError('UPSTREAM_ERROR', `Too many redirects from ${target}`, 502)
126  } catch (caught) {
127    if (caught instanceof ApiError) throw caught
128    log.warn('page_fetch_failed', { host: url.hostname, err: (caught as Error).message })
129    throw new ApiError('UPSTREAM_ERROR', `Could not fetch ${url.hostname}`, 502)
130  }
131}