/* ═══════════════════════════════════════════════════════════════
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;
// The whole request, however steadily the bytes trickle in.
const TOTAL_TIMEOUT_MS = 15000;
const MAX_REDIRECTS = 4;
const MAX_HTML_BYTES = 1024 * 1024;
const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
/* ── Address checks ────────────────────────────────────────── */
/* Private, loopback, link-local, shared, benchmark, multicast and
reserved ranges. BlockList also judges an IPv4-mapped IPv6 address
(::ffff:7f00:1, however it's written) by the IPv4 inside it. The
IPv6 ranges that embed an IPv4 some other way (NAT64, 6to4, the
old compatible form) are refused outright. */
const BLOCKED = new net.BlockList();
for (const [ip, bits] of [
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24],
["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24],
["224.0.0.0", 3],
]) BLOCKED.addSubnet(ip, bits, "ipv4");
for (const [ip, bits] of [
["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16],
["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8], ["2001:db8::", 32],
]) BLOCKED.addSubnet(ip, bits, "ipv6");
function ipBlocked(ip) {
return BLOCKED.check(ip, net.isIPv4(ip) ? "ipv4" : "ipv6");
}
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.")));
// `timeout` above only fires when the socket goes quiet; a server
// sending a byte every few seconds would hold the request open
// for hours. This caps the whole exchange.
const deadline = setTimeout(
() => req.destroy(new MediaError(504, "The site took too long to answer.")),
TOTAL_TIMEOUT_MS,
);
req.on("close", () => clearTimeout(deadline));
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: " " };
// A code point past U+10FFFF would make fromCodePoint throw.
const codePoint = (n) => String.fromCodePoint(n <= 0x10ffff ? n : 0xfffd);
export function decodeEntities(text) {
return text
.replace(/([0-9a-f]{1,6});/gi, (_, hex) => codePoint(parseInt(hex, 16)))
.replace(/(\d{1,7});/g, (_, dec) => codePoint(Number(dec)))
.replace(/&([a-z]+);/gi, (whole, name) => ENTITIES[name.toLowerCase()] ?? whole)
.replace(/\s+/g, " ")
.trim();
}
/* ── Scanning markup ───────────────────────────────────────────
Pages and feeds come from other people's servers, so nothing here
runs a regex over the whole document: a pattern like
/]*>/ restarts at every "", "/", " ", "\t", "\n", "\r"]);
/* Where the next ) starts, or -1. */
function tagStart(lower, name, from) {
for (let i = from; ; ) {
const at = lower.indexOf(name, i);
if (at === -1 || TAG_END.has(lower[at + name.length] ?? "")) return at;
i = at + name.length;
}
}
/* Each opening in text, up to `limit` of them. */
export function openTags(text, tag, limit = 200) {
const lower = text.toLowerCase();
const name = `<${tag.toLowerCase()}`;
const out = [];
for (let i = 0; out.length < limit; ) {
const start = tagStart(lower, name, i);
if (start === -1) break;
const end = lower.indexOf(">", start);
if (end === -1) break;
out.push(text.slice(start, end + 1));
i = end + 1;
}
return out;
}
/* Each whole … in text, up to `limit` of them. */
export function elements(text, tag, limit) {
const lower = text.toLowerCase();
const name = `<${tag.toLowerCase()}`;
const close = `${tag.toLowerCase()}>`;
const out = [];
for (let i = 0; out.length < limit; ) {
const start = tagStart(lower, name, i);
if (start === -1) break;
const end = lower.indexOf(close, start);
if (end === -1) break;
out.push(text.slice(start, end + close.length));
i = end + close.length;
}
return out;
}
/* What's between the first and its , or null. */
export function innerOf(text, tag) {
const lower = text.toLowerCase();
const start = tagStart(lower, `<${tag.toLowerCase()}`, 0);
if (start === -1) return null;
const open = lower.indexOf(">", start);
if (open === -1) return null;
const end = lower.indexOf(`${tag.toLowerCase()}>`, open);
return end === -1 ? null : text.slice(open + 1, end);
}
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 openTags(html, "meta")) {
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.slice(0, 2000));
}
const title = innerOf(html, "title")?.slice(0, 1000);
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;
}