90 lines
3.9 KiB
TypeScript
90 lines
3.9 KiB
TypeScript
import "server-only";
|
|
import { lookup } from "node:dns/promises";
|
|
import { isIP } from "node:net";
|
|
|
|
// Eine fremde Seite holen, ohne die Box zum Werkzeug zu machen: nur http(s),
|
|
// keine Adressen im eigenen Netz (Router, Olares-Dienste, Cluster), höchstens
|
|
// drei Weiterleitungen, zehn Sekunden, drei Megabyte. Jede Weiterleitung wird
|
|
// neu geprüft. (Ein DNS-Rebinding zwischen Prüfung und Abruf bleibt
|
|
// theoretisch möglich; der Abruf läuft ohne Sitzung und ohne Antwort-Durchreiche.)
|
|
|
|
const MAX_BYTES = 3 * 1024 * 1024;
|
|
const MAX_REDIRECTS = 3;
|
|
|
|
export class FetchRefused extends Error {}
|
|
|
|
function privateV4(ip: string): boolean {
|
|
const [a, b] = ip.split(".").map(Number) as [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 >= 224
|
|
);
|
|
}
|
|
|
|
export function isPrivateAddress(ip: string): boolean {
|
|
if (isIP(ip) === 4) return privateV4(ip);
|
|
const v6 = ip.toLowerCase();
|
|
const mapped = v6.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
|
|
if (mapped) return privateV4(mapped[1]!);
|
|
return v6 === "::" || v6 === "::1" || v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("fe8") || v6.startsWith("fe9") ||
|
|
v6.startsWith("fea") || v6.startsWith("feb") || v6.startsWith("ff");
|
|
}
|
|
|
|
async function checkUrl(raw: string): Promise<URL> {
|
|
let url: URL;
|
|
try {
|
|
url = new URL(raw);
|
|
} catch {
|
|
throw new FetchRefused("url");
|
|
}
|
|
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new FetchRefused("url");
|
|
// Nur für den Browser-Test (e2e/gerichte.spec.ts): eine einzige, genau benannte
|
|
// lokale Quelle. Das Chart setzt die Variable nie.
|
|
if (process.env.IMPORT_TEST_ORIGIN && url.origin === process.env.IMPORT_TEST_ORIGIN) return url;
|
|
if (url.port && !["80", "443"].includes(url.port)) throw new FetchRefused("port");
|
|
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
if (/(^|\.)(local|localhost|internal|svc|cluster\.local)$/i.test(host)) throw new FetchRefused("host");
|
|
const addresses = isIP(host) ? [{ address: host }] : await lookup(host, { all: true }).catch(() => []);
|
|
if (!addresses.length || addresses.some((a) => isPrivateAddress(a.address))) throw new FetchRefused("host");
|
|
return url;
|
|
}
|
|
|
|
/** Holt eine HTML-Seite (oder ein Bild, wenn `accept` es sagt) und gibt Text bzw. Bytes zurück. */
|
|
export async function fetchPublic(raw: string, accept: "html" | "image" = "html"): Promise<{ url: string; body: Buffer; type: string }> {
|
|
let url = await checkUrl(raw);
|
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
const res = await fetch(url, {
|
|
redirect: "manual",
|
|
signal: AbortSignal.timeout(10_000),
|
|
headers: {
|
|
"user-agent": "Mozilla/5.0 (compatible; Lunch/1.0; recipe import)",
|
|
accept: accept === "html" ? "text/html,application/xhtml+xml" : "image/*",
|
|
},
|
|
}).catch(() => {
|
|
throw new FetchRefused("network");
|
|
});
|
|
if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
|
|
url = await checkUrl(new URL(res.headers.get("location")!, url).toString());
|
|
continue;
|
|
}
|
|
if (!res.ok || !res.body) throw new FetchRefused(`status ${res.status}`);
|
|
const type = res.headers.get("content-type") ?? "";
|
|
if (accept === "html" ? !/html|xml/.test(type) : !/^image\//.test(type)) throw new FetchRefused("type");
|
|
const chunks: Uint8Array[] = [];
|
|
let size = 0;
|
|
const reader = res.body.getReader();
|
|
for (;;) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
size += value.byteLength;
|
|
if (size > (accept === "html" ? MAX_BYTES : 15 * 1024 * 1024)) {
|
|
await reader.cancel();
|
|
throw new FetchRefused("size");
|
|
}
|
|
chunks.push(value);
|
|
}
|
|
return { url: url.toString(), body: Buffer.concat(chunks), type };
|
|
}
|
|
throw new FetchRefused("redirects");
|
|
}
|