/** * Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for * local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts). */ import dns from 'node:dns/promises'; import net from 'node:net'; import type { Ctx } from '../context.js'; const TIMEOUT_MS = 15000; const MAX_BYTES = 5 * 1024 * 1024; export class LinkCallError extends Error { constructor(message: string, public code: string, public status = 502, public data: unknown = null) { super(message); } } export function isPrivateAddress(ip: string): boolean { if (net.isIPv4(ip)) { const [a, b] = ip.split('.').map(Number) as [number, number]; return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224; } if (net.isIPv6(ip)) { const v = ip.toLowerCase(); if (v === '::1' || v === '::') return true; const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v); if (mapped) return isPrivateAddress(mapped[1]!); return /^f[cd]/.test(v) || /^fe[89ab]/.test(v); } return true; } export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise { let url: URL; try { url = new URL(path, base.endsWith('/') ? base : `${base}/`); } catch { throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400); } const allow = ctx.config.allowPrivateLinks; if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400); if (!allow) { const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []); if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400); } return url; } export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record }): Promise { let res: Response; try { res = await fetch(url, { method: init.method, headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers }, body: init.body, redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT_MS), }); } catch (e) { throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE'); } if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED'); const text = await res.text(); if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE'); let data: unknown = null; try { data = text ? JSON.parse(text) : null; } catch { if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON'); } if (!res.ok) { const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } }; throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data); } return data; }