// WEB FETCH — one web page as readable text, through the pacer (release 27 // D7). Read only, and fenced: // - http and https only; // - never a private, loopback, link-local or unspecified host — by name // (`localhost`, `*.local`, `*.internal`) or by address, the name resolved // first so a public name pointing inside is refused too; every redirect hop // is checked the same way (at most WEB_FETCH_MAX_REDIRECTS). A test opens // the fence with `allowPrivate`; // - text only (HTML, plain text, JSON, XML); a PDF, an image or a video is // refused, not downloaded; // - the body read up to WEB_FETCH_MAX_BYTES, the text cut at `maxChars`. // // A page is context for a model, never evidence: nothing here cites it. import { lookup } from "node:dns/promises"; import { isIP } from "node:net"; import { decodeEntities } from "../../social/htmlReader"; import { webPacer, WebRequestError, type WebPacer } from "./pacer"; export const WEB_FETCH_DEFAULT_CHARS = 12_000; export const WEB_FETCH_MAX_CHARS = 60_000; export const WEB_FETCH_MAX_BYTES = 2_000_000; export const WEB_FETCH_MAX_REDIRECTS = 5; export type WebPage = { url: string; // Where the last redirect landed. finalUrl: string; status: number; contentType: string; title?: string; text: string; truncated: boolean; }; export type WebFetchOptions = { maxChars?: number; pacer?: WebPacer; signal?: AbortSignal; // Tests only: let a loopback fake server through the fence. allowPrivate?: boolean; // Name → addresses (default: the system resolver). resolve?: (host: string) => Promise; }; // ─── the fence ─── function ipv4Private(ip: string): boolean { const p = ip.split(".").map(Number); if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true; const [a, b] = p as [number, number, number, number]; return ( a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0 && p[2] === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224 ); } function ipv6Private(ip: string): boolean { const s = ip.toLowerCase().replace(/^\[|\]$/g, ""); if (s === "::" || s === "::1") return true; const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(s); if (mapped) return ipv4Private(mapped[1]!); return /^(fc|fd|fe[89ab])/.test(s) || s.startsWith("ff"); } // An address no web fetch may reach. export function isPrivateAddress(ip: string): boolean { const v = isIP(ip.replace(/^\[|\]$/g, "")); if (v === 4) return ipv4Private(ip); if (v === 6) return ipv6Private(ip); return true; } const PRIVATE_NAME = /(^|\.)(localhost|local|internal|lan|home|localdomain)$/i; const defaultResolve = async (host: string) => (await lookup(host, { all: true, verbatim: true })).map((a) => a.address); // The reason `url` may not be fetched, or null. export async function fetchRefusal( url: string, opts: Pick = {}, ): Promise { let u: URL; try { u = new URL(url); } catch { return `"${url}" is not a URL`; } if (u.protocol !== "http:" && u.protocol !== "https:") return `only http and https pages are read (not ${u.protocol})`; if (u.username || u.password) return "a URL with credentials in it is not read"; if (opts.allowPrivate) return null; const host = u.hostname.replace(/^\[|\]$/g, ""); if (PRIVATE_NAME.test(host)) return `${host} is a private host`; if (isIP(host)) return isPrivateAddress(host) ? `${host} is a private address` : null; let addrs: string[]; try { addrs = await (opts.resolve ?? defaultResolve)(host); } catch (e) { return `${host} does not resolve (${(e as Error).message})`; } if (addrs.length === 0) return `${host} does not resolve`; const inside = addrs.find(isPrivateAddress); return inside ? `${host} resolves to a private address (${inside})` : null; } // ─── the page as text ─── const TEXT_TYPES = /^(text\/|application\/(json|xml|xhtml\+xml|rss\+xml|atom\+xml|ld\+json))/i; export function htmlToReadableText(html: string): { title?: string; text: string } { const titleM = /]*>([\s\S]*?)<\/title>/i.exec(html); const title = titleM ? decodeEntities(titleM[1]!.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim() : undefined; let body = html .replace(//g, " ") .replace(/<(script|style|noscript|svg|template|iframe|head|title)\b[^>]*>[\s\S]*?<\/\1>/gi, " ") .replace(/<(nav|footer)\b[^>]*>[\s\S]*?<\/\1>/gi, " "); body = body .replace(//gi, "\n") .replace(/<\/(p|div|li|h[1-6]|blockquote|tr|section|article|header|pre|table|ul|ol|dd|dt)>/gi, "\n") .replace(/]*>/gi, "- ") .replace(/<[^>]+>/g, " "); const text = decodeEntities(body) .replace(/ /g, " ") .split("\n") .map((l) => l.replace(/[ \t\r\f\v]+/g, " ").trim()) .join("\n") .replace(/\n{3,}/g, "\n\n") .trim(); return { ...(title ? { title } : {}), text }; } async function readCapped(res: Response, maxBytes: number): Promise { if (!res.body) return ""; const reader = res.body.getReader(); const chunks: Uint8Array[] = []; let n = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.byteLength; if (n >= maxBytes) { await reader.cancel().catch(() => {}); break; } } return new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes)); } export async function webFetch(url: string, opts: WebFetchOptions = {}): Promise { const maxChars = Math.min(WEB_FETCH_MAX_CHARS, Math.max(200, Math.floor(opts.maxChars ?? WEB_FETCH_DEFAULT_CHARS))); const pacer = opts.pacer ?? webPacer; let at = url.trim(); for (let hop = 0; ; hop++) { const refusal = await fetchRefusal(at, opts); if (refusal) throw new WebRequestError(refusal, null); const step = await pacer.request( at, { method: "GET", redirect: "manual", headers: { accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5" }, ...(opts.signal ? { signal: opts.signal } : {}), }, async (res): Promise<{ redirect: string } | { page: WebPage }> => { if (res.status >= 300 && res.status < 400 && res.headers.get("location")) { await res.body?.cancel().catch(() => {}); return { redirect: new URL(res.headers.get("location")!, at).toString() }; } if (!res.ok) { await res.body?.cancel().catch(() => {}); throw new WebRequestError(`${new URL(at).host} answered HTTP ${res.status}`, res.status); } const contentType = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase(); if (contentType && !TEXT_TYPES.test(contentType)) { await res.body?.cancel().catch(() => {}); throw new WebRequestError(`not a text page (${contentType}) — only pages are read here`, res.status); } const raw = await readCapped(res, WEB_FETCH_MAX_BYTES); const html = /html|xml/.test(contentType) || (!contentType && /^\s* maxChars; return { page: { url, finalUrl: at, status: res.status, contentType: contentType || (html ? "text/html" : "text/plain"), ...(read.title ? { title: read.title } : {}), text: truncated ? read.text.slice(0, maxChars) : read.text, truncated, }, }; }, ); if ("page" in step) return step.page; if (hop + 1 > WEB_FETCH_MAX_REDIRECTS) { throw new WebRequestError(`more than ${WEB_FETCH_MAX_REDIRECTS} redirects from ${url}`, null); } at = step.redirect; } } export function formatPage(p: WebPage): string { return ( `${p.title ? `# ${p.title}\n` : ""}${p.finalUrl}\n\n${p.text}` + (p.truncated ? `\n\n(cut at ${p.text.length} characters)` : "") ); }