/* ═══════════════════════════════════════════════════════════════ LINK PREVIEW Reads a page's title, description and preview image (og:, then twitter:, then ) for the featured card editor's "Fetch preview" button. The image is downloaded and put through the media library like any upload, so the card never hotlinks someone else's server. This makes the server request a URL an editor typed, so it is careful about where it goes: · http and https only, on ports 80 and 443 · the host is resolved first, and refused if any address is private, loopback, link-local, carrier-grade NAT, multicast or unspecified (so no 127.0.0.1, no 10.x, no metadata endpoint at 169.254.169.254) · the connection goes to the address that was checked, not a fresh lookup, so DNS can't change its answer in between · redirects are followed by hand, at most MAX_REDIRECTS, and every hop is checked again · TIMEOUT_MS per request, and at most MAX_HTML_BYTES of page or MAX_UPLOAD_BYTES of image is read Editors and up only (routes/media.js). feeds.js reads RSS through the same safeGet. ═══════════════════════════════════════════════════════════════ */ import { lookup } from "node:dns/promises"; import http from "node:http"; import https from "node:https"; import net from "node:net"; import { MAX_UPLOAD_BYTES, MediaError } from "./media.js"; const TIMEOUT_MS = 8000; const MAX_REDIRECTS = 4; const MAX_HTML_BYTES = 1024 * 1024; const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)"; /* ── Address checks ────────────────────────────────────────── */ function ipv4Blocked(ip) { const [a, b] = ip.split(".").map(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) || (a === 198 && (b === 18 || b === 19)) || a >= 224 ); } function ipBlocked(ip) { if (net.isIPv4(ip)) return ipv4Blocked(ip); const lower = ip.toLowerCase(); // An IPv4 address written as IPv6 is judged as the IPv4 it is. const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); if (mapped) return ipv4Blocked(mapped[1]); return ( lower === "::" || lower === "::1" || /^f[cd]/.test(lower) || // fc00::/7 unique local /^fe[89ab]/.test(lower) || // fe80::/10 link-local /^ff/.test(lower) // multicast ); } async function vet(raw) { let url; try { url = new URL(raw); } catch { throw new MediaError(400, "That isn't a valid link."); } if (url.protocol !== "http:" && url.protocol !== "https:") { throw new MediaError(400, "Only http and https links can be previewed."); } if (url.port && url.port !== "80" && url.port !== "443") { throw new MediaError(400, "Only links on the standard ports can be previewed."); } if (url.username || url.password) { throw new MediaError(400, "Links with a username or password can't be previewed."); } const host = url.hostname.replace(/^\[|\]$/g, ""); let addresses; try { addresses = net.isIP(host) ? [{ address: host, family: net.isIP(host) }] : await lookup(host, { all: true }); } catch { throw new MediaError(400, "That site couldn't be found."); } if (addresses.length === 0 || addresses.some(({ address }) => ipBlocked(address))) { throw new MediaError(400, "That address can't be previewed."); } return { url, address: addresses[0] }; } /* ── One request, pinned to the vetted address ─────────────── */ function requestOnce({ url, address }, { maxBytes, accept, truncate = false }) { const client = url.protocol === "https:" ? https : http; return new Promise((resolve, reject) => { const req = client.request( url, { method: "GET", headers: { "User-Agent": USER_AGENT, Accept: accept }, timeout: TIMEOUT_MS, // Hand back the address we already checked instead of // resolving again. TLS still verifies against the hostname. lookup: (_host, options, callback) => { if (options?.all) callback(null, [address]); else callback(null, address.address, address.family); }, }, (res) => { const status = res.statusCode ?? 0; if (status >= 300 && status < 400 && res.headers.location) { res.resume(); resolve({ redirect: new URL(res.headers.location, url).toString() }); return; } if (status < 200 || status >= 300) { res.resume(); reject(new MediaError(400, `The page answered ${status}.`)); return; } const chunks = []; let size = 0; res.on("data", (chunk) => { size += chunk.length; if (size > maxBytes) { // A page's head is at the top; stop reading and use what // arrived. An image that's too big is refused outright. res.destroy(); if (truncate) { resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" }); } else { reject(new MediaError(413, "The preview image is too large.")); } return; } chunks.push(chunk); }); res.on("end", () => resolve({ body: Buffer.concat(chunks), type: res.headers["content-type"] ?? "" }), ); res.on("error", reject); }, ); req.on("timeout", () => req.destroy(new MediaError(504, "The site took too long to answer."))); req.on("error", (err) => reject(err instanceof MediaError ? err : new MediaError(400, "That site couldn't be reached.")), ); req.end(); }); } /* Also used by feeds.js, so feeds get the same address checks. */ export async function safeGet(raw, options) { let next = raw; for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { const target = await vet(next); const result = await requestOnce(target, options); if (!result.redirect) return { ...result, url: target.url }; next = result.redirect; } throw new MediaError(400, "The link redirects too many times."); } /* ── Reading the page ──────────────────────────────────────── */ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " }; export function decodeEntities(text) { return text .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16))) .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))) .replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole) .replace(/\s+/g, " ") .trim(); } function attr(tag, name) { const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i")); return match ? (match[1] ?? match[2] ?? match[3] ?? "") : null; } function readMeta(html) { const meta = {}; for (const tag of html.match(/<meta\b[^>]*>/gi) ?? []) { const key = (attr(tag, "property") ?? attr(tag, "name") ?? "").toLowerCase(); const content = attr(tag, "content"); if (key && content != null && !(key in meta)) meta[key] = decodeEntities(content); } const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]; return { title: meta["og:title"] || meta["twitter:title"] || (title ? decodeEntities(title) : null) || null, description: meta["og:description"] || meta["twitter:description"] || meta.description || null, image: meta["og:image:secure_url"] || meta["og:image"] || meta["twitter:image"] || null, }; } /* The page's title, description and image URL. */ export async function previewLink(raw) { const page = await safeGet(raw, { maxBytes: MAX_HTML_BYTES, truncate: true, accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1", }); if (!/html/i.test(page.type)) { throw new MediaError(400, "That link isn't a web page."); } const meta = readMeta(page.body.toString("utf8")); let image = null; if (meta.image) { try { image = new URL(meta.image, page.url).toString(); } catch { image = null; } } return { title: meta.title, description: meta.description, image }; } /* The bytes of a preview image, for media.store(). */ export async function fetchImage(raw) { const result = await safeGet(raw, { maxBytes: MAX_UPLOAD_BYTES, accept: "image/*" }); return result.body; }